pytest-dev / pytest-dev/pytest-django

Test works locally but fails when ran on Travis-CI

Open
#1,017 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.5k
Forks
367
PR merge metrics
No merged PRs in 30d

Description

Please for some reason one of my test is failing on Travis CI but passes locally.

This is the code for the test:

@pytest.mark.django_db(transaction=True)
class TestCreateItem:
    def test_successful_item_creation(self, client, seller_token):
        """
        Test for successful item creation

        GIVEN: A seller enters name, price, image and description of items
        WHEN: The seller submits the form
        THEN: They should get a success response of status code 201, A message that says 'Item has been created successfully'
        """
        with open('tests/test_item/0_U8TbUaajSO7rXk1j.jpg', 'rb') as image:
            data = {
                "name": "An Item",
                "price": 15000.55,
                "description": "This is a random item",
                "image": image
            }
        
            response = client.post("/items/create_item", data=data, **seller_token)
            response_data = response.json()
            print(response_data)
            assert response.status_code == 201
            assert response_data["message"] == "Item has been created successfully"

When I run the test locally, it passes, but when it is ran on Travis CI it fails without any descriptive information as to what went wrong. Below is a snippet of the error:

tests/test_item/test_fetch_item_queryset.py ....                         [ 21%]
tests/test_seller/test_seller_authentication.py ........                 [ 63%]
tests/test_item/test_create_item.py F......                              [100%]
=================================== FAILURES ===================================
_________________ TestCreateItem.test_successful_item_creation _________________
self = CreateItemSerializer(data=<QueryDict: {'name': ['An Item'], 'price': ['15000.55'], 'description': ['This is a random i...digits=10)
    image = ImageField(max_length=100)
    description = CharField(style={'base_template': 'textarea.html'})
validated_data = {'description': 'This is a random item', 'image': <InMemoryUploadedFile: 0_U8TbUaajSO7rXk1j.jpg (image/jpeg)>, 'name': 'An Item', 'price': Decimal('15000.55'), ...}
    def create(self, validated_data):
        """
        We have a bit of extra checking around this in order to provide
        descriptive messages when something goes wrong, but this method is
        essentially just:
    
            return ExampleModel.objects.create(**validated_data)
    
        If there are many to many fields present on the instance then they
        cannot be set until the model is instantiated, in which case the
        implementation is like so:
    
            example_relationship = validated_data.pop('example_relationship')
            instance = ExampleModel.objects.create(**validated_data)
            instance.example_relationship = example_relationship
            return instance
    
        The default implementation also does not handle nested relationships.
        If you want to support writable nested relationships you'll need
        to write an explicit `.create()` method.
        """
        raise_errors_on_nested_writes('create', self, validated_data)
    
        ModelClass = self.Meta.model
    
        # Remove many-to-many relationships from validated_data.
        # They are not valid arguments to the default `.create()` method,
        # as they require that the instance has already been saved.
        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)
    
        try:
>           instance = ModelClass._default_manager.create(**validated_data)
../../../virtualenv/python3.9.12/lib/python3.9/site-packages/rest_framework/serializers.py:939: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
self = <django.db.models.manager.Manager object at 0x7f6e234c47f0>, args = ()
kwargs = {'description': 'This is a random item', 'image': <InMemoryUploadedFile: 0_U8TbUaajSO7rXk1j.jpg (image/jpeg)>, 'name': 'An Item', 'price': Decimal('15000.55'), ...}
    def manager_method(self, *args, **kwargs):
>       return getattr(self.get_queryset(), name)(*args, **kwargs)
../../../virtualenv/python3.9.12/lib/python3.9/site-packages/django/db/models/manager.py:85: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
self = <QuerySet []>
kwargs = {'description': 'This is a random item', 'image': <InMemoryUploadedFile: 0_U8TbUaajSO7rXk1j.jpg (image/jpeg)>, 'name': 'An Item', 'price': Decimal('15000.55'), ...}
obj = <Items: johndoe@gmail.com An Item>
    def create(self, **kwargs):
        """
        Create a new object with the given kwargs, saving it to the database
        and returning the created object.
        """
        obj = self.model(**kwargs)
        self._for_write = True
>       obj.save(force_insert=True, using=self.db)


I would appreciate any pointers as to what the problem is

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with tests/test_item/test_create_item.py and the provided Travis-CI traceback, then compare the test and runtime environments described in the report. Done means identifying the CI-only failure cause and making the test pass under Travis-CI with a descriptive failure if the problem recurs.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
ci-cd, testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.