Questions tagged [django-tests]

1

votes
1

answer
84

Views

Mock function outside package

I'm developing a Django software with different apps on it. I'm testing some views and I want to mock the return of a function inside these views. For example I have this view (located at apps.policies.views): def upload_policy_document(request): # code fragment avoid # save document ot ipfs respo...
Albert Diaz
1

votes
0

answer
238

Views

Install hstore extension for django tests

I am trying to install the hstore extension before running django tests. For that, I have overridden the default DiscoverRunner's setup_databases method. However, the extension is not installed & the tests show this error django.db.utils.ProgrammingError: type 'hstore' does not exist Here's my code...
Pranjal
1

votes
1

answer
60

Views

Django testing - spoofing an Ajax POST request method with Client() to pass request.is_ajax() validation

Not sure if this is possible, but I have the following validation check for an Ajax POST request in my views.py: if request.is_ajax() and request.method == 'POST': # Do some amazing stuff here... context['is_ajax'] = True Now, running a few tests in the shell: from django.test import Client >>> c =...
1

votes
1

answer
47

Views

django: test case development to check: a logged in user is redirected to different views based on staff status

I am a testing a Django Library application, for two types of Users: customers and library staff. This is the urls.py path('dashboard_customer/', views.LoanedBooksByUserListView.as_view(), name='dashboard_customer'), path('dashboard_staff/', views.LoanedBooksAllListView.as_view(), name='dashboard_st...
Simran
1

votes
0

answer
14

Views

Django Template Error at Circle CI while Writing Test

All of my settings work perfectly fine and have no issue as such. Its just that CircleCI is not getting the most simplest possible test work fine. I've created a home page and wrote a test for it. The test at local ubuntu machine runs fine with python manage.py runserver and with pytest as well. Als...
Shazia Nusrat
1

votes
1

answer
18

Views

Getting Typeerror: can't concat str to bytes, when writing a test case to enter request files in django rest framework?

I was working on a project where I can add a csv to upload shirts details to the database. I wrote a viewset that takes shirt csv files input from request.data in django rest framework, and am writing a test case for the same. Though, while writing the test case, rather than creating a seperate csv...
Mayank
1

votes
1

answer
634

Views

Where do I initialize my webdriver in Django using Selenium along django.test

I am willing to test my Django application using Selenium. From what I read, Django already cover the testing part and allow you to write your own tests. Willing to use this with Selenium, here is my /test.py: from some.path.to.my.utilitary.module import TestTools class FormTestCase(TestCase): def s...
1

votes
1

answer
735

Views

how to init database for testcase in django

In the testcase, there are many test functions and all the test functions use the same data. class Mytest(TestCase): def init_data(self): insert data1 insert data2 ..... def test1: do something def test2: do something .... where should I call the init_data function. If I call the function in all the...
user2256235
1

votes
1

answer
73

Views

How to make my test fixtures loaded only while testing in Django?

I have a Django project with production fixtures and testing fixtures. How to make testing fixtures loaded only while running tests?
Sashko Lykhenko
1

votes
1

answer
821

Views

Django: How to associate a user with a request factory

I am writing some tests for a form on a Django site. I want to test that a logged in user is able to use the form assuming correct input. To that end, I am using a Django request factory. I can't seem to get my test user logged in though. That, or I'm not even making the request correctly. I'm...
fildred13
1

votes
2

answer
172

Views

Unusual error in Django tests wrongly thinking instance doesn't exist

I have very customised Django app that checking to see if a user can change a ForeignKey to certain values. In this instance, a User belongs to a Workgroup and an Item can also belong to a Workgroup, and consequently, when a User makes an Item, they can only put it in Workgroups they belong to. Comp...
1

votes
1

answer
491

Views

Login test cases failing in Django 1.8

Today I am learning to write test cases in Django, and wrote a test case for checking authentication of valid users. from django.test import TestCase from django.http import HttpRequest from aptly_dash.views import newRepo, homePage from selenium import webdriver from django.test import Client clas...
python
1

votes
1

answer
667

Views

Testing url redirection in Django

If I go to http://localhost:8000/login/, login form will be displayed and you have to input username and password. If the credentials are right then you will be redirected to http://localhost:8000/dashboard/. The problem I am facing while testing is even though my username and password are correct i...
python
1

votes
2

answer
507

Views

Test case for GET api for APIView not working in djangorestframework

I am writing a test case in Django on GET API. I just want to make the very first test pass. Here is my code. class InventoryItemDetailTestCase(APITestCase): ''' This is the API test case for the reserve/express detail api ''' def setUp(self): self.resource_uri = '/api/v2/inventory/inventory_item_de...
Chitrank Dixit
1

votes
1

answer
539

Views

TestCase self.assertEqual does not match a similar string

I'am trying to create a model unittest for a ManyToMany relationship. The aim is to check, if there is the right category saved in the table Ingredient. class IngredientModelTest(TestCase): def test_db_saves_ingredient_with_category(self): category_one = IngredientsCategory.objects.create(name='Food...
pillow_willow
1

votes
1

answer
302

Views

Django test print or log failure

I have a django_rest_framework test (the problem is the same with a regular django test) that looks like this: from rest_framework.test import APITestCase class APITests(APITestCase): # tests for unauthorized access def test_unauthorized(self): ... for api in apipoints: response = self.client.option...
Alejandro Veintimilla
1

votes
1

answer
354

Views

I can't update the Model instance while Testing

I'm testing a CBV on Update and each time the model instance can't seems to update. console output > self.assertEqual(product.showoff, data['showoff']) E AssertionError: 'uMsvXoRJbwFeieMvoCmR' != 'showoff 33333' E - uMsvXoRJbwFeieMvoCmR E + showoff 33333 views.py class Produc...
1

votes
2

answer
1.1k

Views

Django Testing - loading data into the database before loading the apps

I'm currently writting some tests for a Django app (+ REST framework), and having some issues loading the test data into the database. Let me explain with some (very simplified) code : I have a django view which is something like : view.py from myapp.models import Item from myapp.utils import MyClas...
Duf59
1

votes
1

answer
207

Views

Pass a static string parameter (a model choice) through URL in Django?

Django 2.0 I've got the following model: class Visitor(models.Model): TYPE_CHOICES = ( ('P', 'Person'), ('E', 'Employee'), ) type = models.CharField(choices=TYPE_CHOICES, max_length=1) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) birth_date = models.DateFi...
Hanny
1

votes
1

answer
265

Views

Conect to Django test database

Is there a way to connect to django test database using connections? I have tried cursor = connections['test_name_of_main_db'].cursor() and also specified the test db name in settings but I still receive errors: Traceback (most recent call last): File '/home/tets/4d/lib/python3.5/site-packages/djang...
Beliaf
1

votes
1

answer
328

Views

form.is_valid() failing in Django unit test

I'm running a unit test for a Django form, and form.is_valid() keeps returning False and I cannot find the error. Here's the code for forms.py: class CustomClearableFileInput(forms.ClearableFileInput): template_name = 'forums/templates/clearable_file_input.html' class NewQuestionForm(forms.ModelForm...
1

votes
2

answer
340

Views

Django Rest Framework: How to pass a list of UUIDs for a nested relationship to a serializer?

TL;DR: What could be the reason the incoming data for one of my serializers does not get processed? I'm working on a serializer for a nested relationship. The serializer should get a list of UUIDs, so that I can make many to many relationships. Here is the model: class Order( UniversallyUniqueIdenti...
J. Hesters
1

votes
1

answer
15

Views

Is there a limitation on running db query in imported function in django tests?

I am using function in views to query db (postgresql), calculate values and return list of lists. When I call it from views.py I get what is expected. When I call it from test.py I get empty list (not error, not None). To investigate I have created list of lists in views function manually and it wa...
Frantisek Dolezel
1

votes
1

answer
44

Views

How can I pass in a parameter to my TestCase in Django?

Using an edited version of the example from Django's own doc, lets say my code looks like this: from django.test import TestCase from myapp.models import Animal class AnimalTestCase(TestCase): def __init__(self, animal_family): self.animal_family = animal_family def setUp(self): Animal.objec...
darkhorse
1

votes
2

answer
259

Views

Django Rest Framework API Client Custom Header

I am trying to use bulk update from drf-extensions. To make it work, there is a safeguard requiring the header 'X-BULK-OPERATION': 'true'. I can get the application working using curl or my angular app, but in my tests I am trying to use rest_framework.test.APIClient to send the partial_update reque...
Murphy4
1

votes
1

answer
0

Views

django test case ValueError: The given username must be set

I am testing a Django application, for its user sign-up feature, whether the posted data is correct and post request executes successfully. In views.py, the Class CustomerSignUpView class CustomerSignUpView(View): def post(self, request): name_r = request.POST.get('customer_username') password_r = r...
Simran
1

votes
1

answer
526

Views

django not running tests after adding south

I've come accross an issue I believe is a problem with Django South, SQLite and testing. My tests used to work before South was introduced into the application. I used to use the in-memory SQLite and everything worked fine. Now with South I get an error saying one of my DB tables already exists a...
renderbox
1

votes
1

answer
366

Views

django pass response context none

In my browser, everything is fine. Until I make a test here is my polls/views.py from django.shortcuts import render from polls.models import Poll def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date') context = {'latest_poll_list':latest_poll_list} return render(request,'po...
1

votes
1

answer
698

Views

Model Mommy Recipe with Reverse FK

I'm using model_mommy with Django tests to create objects. I'm having trouble creating a model with a reverse FK. I can do it the opposite way round as a workaround, but whilst it works it doesn't look right so I wonder if I can do it the other way round? Say I have two models, User and Profile, rel...
Ludo
1

votes
1

answer
530

Views

Django Test client.get() returns 302 code instead of 200

Running a test on a url returns 302 instead of 200. Yet testing the same urls in production with a redirect tester returns 200. Not really sure what's going on. tests.py def test_detail(self): response = self.client.get('/p/myproduct-detail.html') self.assertEqual(response.status_code, 200) urls.py...
KingFu
1

votes
1

answer
37

Views

Django requested URL was not found on this server in TestClass

My TestClass looks like: from django.test import TestCase, Client class TestGetSomething(TestCase): def test_get_first_url(self): path = 'some/long/path' client = Client() response = client.get(path=path) self.assertEqual(response.status_code, 200) But assertEquals raises the exception, 404 != 200...
N.C.
1

votes
1

answer
396

Views

Django test model with fake user

I have a django model I want to test. The model includes a 'user' field. Is there a way of creating a temporary user for the purposes of testing? tests.py from django.test import TestCase from .models import Task from django.utils import timezone from .forms import Taskform # models test class TaskT...
Davtho1983
1

votes
1

answer
110

Views

Django TestCase not destroying test data after tests finish running

I am currently trying to write my first Django specs for an application. However, everytime I run the tests I receive a IntegrityError: UNIQUE constraint failed: auth_user.username due to the user I created in the previous running of the test now existing in the database. I was under the impression...
Todd Drinkwater
1

votes
1

answer
195

Views

Unit testing in Django with flexible url patterns

I was using the following test to check whether page resolves to correct template: from django.test import TestCase class HomePageTest(TestCase): def test_landing_page_returns_correct_html(self): response = self.client.get('/') self.assertIn(member='Go to the', container=response.content.decode())...
HBat
0

votes
0

answer
21

Views

Python read csv file and add new row and then after some test delete the row

I am using a CSV file where first tasks is to just push that file to a server, second after the first tasks make some changes in csv file which now has an object, {'file': } response = client.post('/path/to/push/', data=files) So point is to make a change in this file object and again push the newly...
aakash singh
2

votes
1

answer
110

Views

Python unittest task.apply_async()

Using coverage to look what has to be tested, and coverage shows that next to this has to be tested: send_alert.apply_async() I know it is celery task, but is there any way to test the line of code? rest of code to understand logic for test: class SomeView(GenericAPIView) def post(self, request, *ar...
Beliaf
2

votes
1

answer
129

Views

How to correctly use assertRaises in Django

I have the following validation function in my model: @classmethod def validate_kind(cls, kind): if kind == 'test': raise ValidationError('Invalid question kind') which I am trying to test as follows: w = Model.objects.get(id=1) self.assertRaises(ValidationError, w.validate_kind('test'),msg='Invali...
Beliaf
2

votes
2

answer
194

Views

Django unit testing: How should one test abstract models?

In my Django Project I have an app called 'core' which contains all my reusable model mixins / abstract models (behaviors.py), models (models.py), views (views.py) and helpers functions (utils.py): core/ __init__.py behaviors.py models.py utils.py views.py I know want to write tests for these file...
J. Hesters
5

votes
1

answer
687

Views

Can't invoke celery task in Django tests synchronously

I'd like to invoke celery tasks synchronously during my Django tests without need to run celery worker. To achieve this I have specified CELERY_ALWAYS_EAGER=True in my settings.py but it doesn't seem to work. So I decided to apply override_settings decorator to specific test that looks like this @ov...
mateuszb
2

votes
0

answer
1.2k

Views

How I can test form_valid method from CreateView class

I have a Class view that inherits of CreateView class CreateErrandView(ErrandFormMixin, CreateView): form_class = ErrandForm @method_decorator(ensure_csrf_cookie) def dispatch(self, *args, **kwargs): print('passes through here') return super(CreateErrandView, self).dispatch(*args, **kwargs) def form...
individuo7

View additional questions