335 questions
0
votes
1
answer
41
views
Django Unit Test - using factory_boy build() on a Model with Many-To-Many relationship
I’m working on writing unit tests for a DRF project using pytest and factory_boy.
I’m running into issues with many-to-many relationships. Specifically, when I try to use .build() in my unit tests, ...
1
vote
0
answers
61
views
unit testing in DRF, Error mock.patch transaction.atomic with unittest.mock.patch
@transaction.atomic
def deposit(user: User, account_number: str, amount: float) -> None:
account = get_object_or_404(
Account.objects.select_for_update(), account_number=account_number, ...
0
votes
0
answers
26
views
Django: Unit Test Fixtures not loading in VSCode Debug Mode
I have written some unit tests with Django, with fixtures set up. I want to debug these tests and have a configuration on VSCode to do this...
{
// Use IntelliSense to learn about possible ...
-2
votes
1
answer
145
views
A more elegant approach to writing Django’s unit tests
I am currently writing tests using Django’s unit tests (based on Python standard library module: unittest). I have written this test for my Contact model which passes:
class ContactTestCase(TestCase):
...
0
votes
0
answers
40
views
Define return value after chained mocks
I am using unittest.mock to test my Django application.
The set-up is the following:
I want to test a function foo
foo uses a method X which is a constructor from an external package
X is called in ...
0
votes
1
answer
52
views
How to send extra parameter to unittest's side_effect in Python?
I'm using side_effect for dynamic mocking in unittest.
This is the code.
// main functionn
from api import get_users_from_api
def get_users(user_ids):
for user_id in user_ids:
res = ...
2
votes
0
answers
85
views
running django tests --parallel and splitting log files per test-runner worker
I'm using manage.py test --parallel to run my tests and want to create a separate log file for each test runner.
Currently, all the test runner worker write to the same log file, so I get a single log ...
0
votes
1
answer
81
views
Dynamic mocking using patch from unittest in Python
I'm going to mock a Python function in unit tests.
This is the main function.
from api import get_users_from_api
def get_users(user_ids):
for user_id in user_ids:
res = get_users_from_api(...
2
votes
2
answers
183
views
Django - is there a way to shuffle and run only a subset of tests?
We are using Django with tests. We have in total about 6,000 tests which take about 40 minutes to run. Is there a way to shuffle the tests and run only 200 (randomly chosen) tests? This should be done ...
1
vote
0
answers
28
views
How can I do mocked reverse_lazy from django.urls?
# views.py
from django.contrib.auth import get_user_model
from django.urls import reverse_lazy
from django.views import generic
from accounts import forms
User = get_user_model()
class ...
0
votes
0
answers
82
views
How can I post data to django import_export
I would like to test the import function from import_export django. When I run my test the code says I provide no dataset (None) even though I do provide a proper CSV file. Thus, my assertions (...
0
votes
0
answers
205
views
django.db.utils.ProgrammingError: (1146, "Table 'test_conect.projects' doesn't exist") while testing
I'm trying to test models for the first time in my django app,but when i run
python manage.py test
I get the following error
django.db.utils.ProgrammingError: (1146, "Table 'test_conect.projects' ...
0
votes
1
answer
49
views
jwt decode giving empty username in django unittest while using request.META
I am generating the token as follows:
class LoginView(APIView):
@swagger_auto_schema(request_body=UserSerializer)
def post(self, request):
username = request.data['email']
...
0
votes
1
answer
45
views
cannot static file through static url using django.test.client
1.env
python : 3.8.14
django version : '4.2.4'
2.Purpose
Make sure that the static file is saved
Make sure that the static file can be accessed from the web browser
3.Issue
The problem is that ...
0
votes
1
answer
101
views
How can I mock dynamic attributes using django test case?
I have some functionality that makes a request to a third party. Within that request are some values that are dynamically created—for example, a date.
# example.py
...
payload = json.dumps({
'id'...
7
votes
1
answer
6k
views
Sonarqube displaying 0% of coverage and no unittest in django project using coverage.py
I'm working on creating unitest for a django project
I installed sonarqube:
docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latest
through docker image ...
0
votes
1
answer
36
views
How to unit test for natural key in models.py in django
I want to unit test for the models.py in django. I do not know how to unit test for the function natural_key()
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email ...
1
vote
1
answer
35
views
I want test the post method by django
I created a "Like" function that works properly.
good. good. good.
# a test file
from django.test import TestCase
from django.urls import reverse
from register.models import User
from ...
1
vote
1
answer
187
views
Test validate_unique raises ValidationError Django forms
I have a ModelForm called SignUpForm located in myproj.accounts.forms
SignUpForm overrides Django's validate_unique so that the 'email' field is excluded from 'unique' validation as required by the ...
4
votes
1
answer
440
views
Django 4 - TransactionTestCase - Postgresql sqlflush error
My code:
Django 4.1
I am using multiple postgresql schemas for my models, postgresql12 with out-of-box ubuntu 20.04 setup.
I am performing unit tests of some code which uses transactions.
migrations ...
0
votes
0
answers
206
views
Is there a chance that emails are sent in parallel and thus `mail.outbox.clear()` doesn't really clear outbox in my django tests?
I have written django tests to check my outbox emails as shown below
class TestX(TestCase):
def setUp(self):
# Clear outbox.
mail.outbox.clear()
super().setUp()
def ...
3
votes
1
answer
449
views
Why is Django test cases checking actual DB and raising IntegrityError instead of just running in-memory?
When I run my tests with the DB empty (the actual application DB), everything goes fine. But when the DB has data, Django raises an IntegrityError for basically every test. The stact trace looks like ...
0
votes
1
answer
233
views
Is it possible to create an artificial model in FactoryBoy?
I wanted to know if in the tests it is possible to somehow create an "artificial" model using FactoryBoy without touching models.py
I mean a simple model such as:
class SomeMod(models.Model):...
0
votes
1
answer
373
views
How to mock settings in Django Unit testing
I am new to Django Unit testing and am trying to write unit test for a simple function which is like below:
utils.py
#some import statements
from django.conf import settings
if platform.system() == '...
1
vote
0
answers
81
views
do some things same time in the Django unit test
How can I test if two users can reserve the same car simultaneously?
def test_if_two_users_can_reserve_the_same_car_simultaneously(self):
with patch.object(
timezone,
"now&...
2
votes
1
answer
2k
views
VS Code Pytest/Unittest debugger doesn't stop on breakpoints
I wrote unittest-based tests with pytest. according to this document:
https://docs.pytest.org/en/7.1.x/how-to/unittest.html
then I tried to run the tests by Python testing in Visual Studio Code ...
1
vote
0
answers
443
views
Django - How to copy schema of existing database into test database?
In my django project, I am using an existing database (Postgres) and with python manage.py inspectdb I created models.
now I want to write unit tests and my problem is django just creates an empty ...
1
vote
1
answer
184
views
Add additional field to response in pytest-django
I'm new to testing and I spent a day finding a solution for my problem but I couldn't find any.
this is my serializer
serilaizer.py
class LeadSerializer(serializers.ModelSerializer):
def create(...
0
votes
1
answer
293
views
How to test Django reusable templates?
In one of my templates for detailed view of a device assignment I had logic pertaining to if buttons should appear depending on the user's permission. I wrote tests for these buttons and they work as ...
0
votes
1
answer
111
views
Django unit tests - django.db.utils.IntegrityError: duplicate key value violates
What's the best way
class BankLoanApplicationFile(TestCase):
"""Test cases for loan_application.py file."""
def setUp(self) -> None:
""&...
0
votes
2
answers
446
views
Django unittest: required mock patch dotted path varies depending on how one calls/runs the tests
It took me hours to figure out how to patch the below code. The path to it was very much unexpected.
Depending on how I run the tests, and which dir I am in, I find the dotted path to the module to ...
0
votes
2
answers
1k
views
How to test query_params?
How can I test query_params? I have provided a response and a request, but it still doesn't work. Initially, the error was like this:
price = int(self.context.get('request').query_params.get('price', ...
0
votes
0
answers
228
views
How to use django unit tests with elasticsearch?
I use django unit tests to test my application. It worked very well until today.
I integrated elasticsearch to the project with the 2 modules django_elasticsearch_dsl and django_elasticsearch_dsl_drf.
...
2
votes
1
answer
306
views
Django TestCase DB missing columns that are in the DB when I runserver
When I start my app it works perfectly, but when I try to run a testcase it creates the test DB from my local copy and errors for a missing column that I can see in my local DB and was part of an ...
1
vote
0
answers
37
views
Writting Unnittest Test for Django Model
I've written a test for the get_rendered_text() method in my django app as seen in the Model below. But when i run a coverage report, it still says i haven't tested this particular method meanwhile ...
0
votes
0
answers
176
views
Django Operational Error : No Such Column
I have a test case using Django MigratorTestCase. Previously the test case was working fine but then I had to add a column called updated and I made migrations to the project but ever since then the ...
0
votes
0
answers
397
views
Django unable to save FloatField value to 0.0
I have a method on a model that updates a value to 0.0 and calls save(). Problem is save() is never saving the value if it is 0.
Here is the code:
class Item(models.Model):
stock_quantity = models....
1
vote
1
answer
991
views
How to mock instance attribute of django form
I'm doing a unit test where I'm mocking a Django form, but I'm having some trouble because I need to mock two things from the form:
An instance attribute (token)
A method (is_valid)
I'm using the ...
3
votes
0
answers
832
views
Is there a way to mock the firebase_admin credentials.Certificate class in Django?
In my project, FirebaseAuthentication is used and while running the test cases(pipenv run python manage.py test) I am getting the following error - ValueError: Invalid certificate argument: "None&...
0
votes
1
answer
254
views
How to modify all databases when overriding DiscoverRunner setup_databases with parallel
I'm running the tests with --parallel and want to add some object to every database that is created (for each process).
currently, I have a CustomTestRunner which inherit from DiscoverRunner.
In that ...
2
votes
1
answer
3k
views
How to read env vars from settings in django unittest?
I am new to unittesting. I want to read some env vars in django unittests, but I am having some troubles when trying to read the env var from django.conf.settings, but I can read the env var using os....
0
votes
1
answer
850
views
ModuleNotFoundError: No module named 'jiraglean.jiraglean'; 'jiraglean'
I am trying to run a tests file in a Django project, the app is called jira and project jiraglean , test file is tests.py
I run the test with:
jiraglean test jira.tests --settings=core.settings.test
...
2
votes
1
answer
2k
views
Django unittest run specific test syntax
I want to run one specific unit test from my app bank/tests.py in the pipeline but I keep getting errors, I believe I am missing something on the syntax here
This is my test:
class SettingsTestCase(...
1
vote
1
answer
417
views
Django Unit Test Case
Hello I'm a newbie to Django Unit test as I'm working on Django Rest Framework using modelviewset. I need to test few models, serializers, views & urls. I'm not sure how to perform it. As I have ...
0
votes
1
answer
155
views
testing in Django
I am trying to test my Django application to get 100 % statement coverage.
I Am using class-based view and overwriting some af the functionalities. One of them is the form valid in my ...
0
votes
1
answer
291
views
Best approach to load specific urls (views) in Django project
I have a Django app that exposes the following views: A,B,C...Z. This app is deployed on MACHINE-1.
There was a new business requirement to deploy on MACHINE-2 the same Django app but with a subset of ...
1
vote
1
answer
1k
views
Testing a custom auth backend with Django RestFramework
I created a custom authentication backend for my DRF application.
I can't figure out how to test it.
Calling the client.post calls my authenticate function (cause that's in my view)
But I need to mock ...
0
votes
1
answer
423
views
Django - Unit test object's delection does not work as expacted
For 2 of my models, Users and Groups, I have a view to delete objects. The code is almost the same for each of them, it works in the application but unit test have different results: it works for ...
0
votes
1
answer
592
views
Django Unit Test Assertion Error for Serialization
I am trying to perform the unit test for a feature in my website, whereby the user uploads a JSON file and I test if the JSON file is valid using serialization and JSON schema. When running the ...
1
vote
1
answer
381
views
Django unittest self.assertTemplateUsed, how to check the occurrence of multiple templates
self.assertTemplateUsed(response,('goods/item_list.html', 'base.html', 'inc/_nav.html') ,)
error
AssertionError: False is not true : Template '('goods/item_list.html',
'base.html', 'inc/_nav.html')' ...