1
I am creating unit tests to perform integration tests of my web application. The tools I am using are: Mongomock to create a temporary bank instance for testing and Factory Boy to create mock instances of my entities.
In each test_case, Gero a mock object, saved in the database and test the corresponding route. Next, I make the necessary asserts.
random_application = MockApplicationFactory.build()
random_application.save()
Through the Test App. and of Paste.deploy established a particular environment to perform the tests.
def setUp(self):
'''
This method is called before each test's execution and it set's up the environment for tests execution. It
creates, among other things:
- Mongomock connect through mongoengine in the test execution context;
- Loads WSGI using a combination of the libraries webtest and paste.deploy;
- Creates mocked function calls that are necessary to perform the tests.
:return:
'''
# changes db connection to mongo mock
# builds the test app to respond to requests
# mock authentication
def tearDown(self):
'''
Method called after the execution of each test. This is used to ensure that both the Database current connection
and the Mocked methods are proplerly reseted in between the tests.
:return:
'''
However, my Application entity was defined with the "name" field determined as "required" and "Unique".
class Application(Document):
name = StringField(required=True, unique = True)
To circumvent this restriction, I decided to use the Developer @factory.post_generation
of Factory Boy aiming to create a new "name" before the execution of each test.
class MockApplicationFactory(factory.Factory):
"""
Factory class for mock applications
"""
class Meta:
model = Application
credentials = ['test']
@factory.post_generation
def random_name(self, create, extracted, **kwargs):
name = factory.fuzzy.FuzzyText(length=10).fuzz()
Even so, after running the test_cases with Pytest, I keep getting the error message "Tried to save Duplicate Unique Keys". This error meets the above definitions regarding Mongoengine.
I’d like to know how can I generate a random "name" for each mock object so that it is updated before the execution of each test.
I could define the "name" field during the creation of each mock object in test_cases, but I try to understand better how Factory Boy and the other tools mentioned.
Remark_0: test_cases are part of the "test" module and objects mock are created in the module "object_factories";
Observation_1: Environment configuration details have been issued, because I believe the solution to the problem is through Factory Boy.