How to generate Factory Boy Fuzzy Attribute before running each test?

1

I'm creating unit tests to perform integration tests for my web application. The tools I am using are: Mongomock to create a temporary instance of the database for testing and Factory Boy to create mock instances of my entities.

In each test_case, I generate 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 Test.App and Paste.deploy I established a private environment to run 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 has been set with the "name" field set to "required" and "unique".

class Application(Document):
    name = StringField(required=True, unique = True)

To circumvent this restriction, I decided to use the Factory Boy decorator to create a new "name" before running 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()

However, after running the test_cases with Pytest , I still get the "Tried to save duplicate unique keys" error message. This error meets the above-mentioned definitions for Mongoengine .

I would like to know how can I generate a random "name" for each mock object so that it is updated before each test runs.

I could set the "name" field during the creation of each mock object in the test_cases, but I try to understand better the operation of Factory Boy and the other tools mentioned.

  • Note_0: the test_cases are part of the "test" module and the objects mock are created in module "object_factories";

  • Note_1: The environment setup details were issued, because I believe that the solution to the problem goes through Factory Boy.

asked by anonymous 28.11.2017 / 14:43

0 answers