简体   繁体   中英

How to mock in python unit tests aws-assume-role-lib and boto3 libraries?

i have a function that has the following code in it

ses = boto3.Session()
as_role = aws_assume_role_lib.assume_role(session, "some_role")

i'm trying to unit test it and i need to mock those two calls. What's the best way to do so?

Without more information, there's no way to answer your question. Any direct answer would require a lot more information. What is it that you want to test? It certainly can't be the code you're showing us because if you mock out both of these calls, there's nothing left to test.

Mocking involves injecting stand-ins for specific test cases such that for those test cases, the mocks return predetermined values without calling the real routines. So what do you want those values to be? The mocks could also have side effects, or change their behavior based on external state, but you want to try to avoid either of those situations. Mocks are usually functional...returning a specific output for each set of specific explicit inputs, and neither modifying or being affected by implicit (external) state.

I assume that ses should be session so that the result of the first call is passed to the second call. In this case, neither of these calls takes varying data, so you can mock the result of the two calls by just assigning a static value to as_role ...whatever value your later code wants to see. Since there is only one set of inputs, there should only be one possible output.

It would be more complicated if you need the mocks to change their behavior based on external state. How you might mock in that case is entirely dependent on the external states that are possible, where they come from, and how they affects the value of as_role . Likewise, if you need your mocks to cause a change in external state, like modifying global variables, you'd need to specify that, and that might affect how you'd choose to mock.

In short, you should define a spec describing how you want your mocks to act under a restricted set of particular conditions. Having that spec will let you begin to decide how to implement them.

If you're just asking how to generally build mocks in Python, check out one or more of the existing Python mocking frameworks, like mock , flexmock , mox , Mocker , etc. A quick Google pointed me to this, which might be helpful: https://garybernhardt.github.io/python-mock-comparison/ . Asking for library recommendations is against SO policy as it involves mostly personal opinions, so if you're asking for that, you should look elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM