7
7
7a-6662021-04-10 22:37:26
Django
7a-666, 2021-04-10 22:37:26

How to lock a function in a specific place?

The essence of the problem is this
. I have a test that should check the correct operation of the function that creates the path for the file
Test code and function code

@mock.patch('uuid.uuid4', return_value='name_file.png')
    def test_path_to_restaurant_image(self, fake_func):
        """
        Checking that the path for the restaurant pictures is formed correctly
        """
        restaurant = RestaurantFactory()
        expected_value = restaurant_image_upload_handler(
            restaurant, self.file_name,
        )
        result = os.path.join(
            'restaurant',
            'images',
            self.file_name,
        )
        self.assertEqual(result, expected_value)

def restaurant_image_upload_handler(instance, filename):
    unique_id = str(uuid.uuid4())
    ext = filename.split('.')[-1]
    return os.path.join(
        'restaurant',
        'images',
        f'{unique_id}.{ext}'.lower(),
    )


I messed up the uuid.uuid4() function to accurately check the file name
But to create test objects I use a factory (restaurant = RestaurantFactory()) and it uses the uuid.uuid4() function somewhere
and it crashes there because I The question is how to lock the uuid.uuid4

() function only for my function (unique_id = str(uuid.uuid4())) or an alternative

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2021-04-10
@7a-666

In the restaurant_image_upload_handler function, you can use the function to get the unique_id

def  get_unique_id():
    return str(uuid.uuid4())
...
unique_id = get_unique_id()

Then you can lock get_unique_id, not the library uuid.uuid4()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question