Mocking a dictionary upon FastAPI router instantiation

27 Views Asked by At

Attempting to write tests for an existing route and running into some roadblocks. I'm trying to mock a dictionary that is loaded when a router is instantiated, but it seems like the @patch'd versions I am supplying are loaded after the original dict is imported and computed upon.

Here is a simplified layout of files

long_list.py

big_dictionary = {'entry1': 'value1', 'entry2':'value2}

main.py

KeyName = Enum('KeyName', names=[key for key in big_dictionary])
app = FastAPI()

@app.get("/")
async def root(key_name: KeyName):
    return key_name

I would like to get a test case like this passing:

    @patch('main.big_dictionary', {'test_entry3': 'value3', 'test_entry4': 'value4'})
    def test_root(self):
        client = TestClient(app)
        response = client.get('/', params={key_name: "TEST_ENTRY3"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), "TEST_ENTRY3")

currently, it is failing and saying that TEST_ENTRY3 is not a valid enum value.

0

There are 0 best solutions below