Questions tagged [django-testing]

1

votes
2

answer
40

Views

is there a way to override model methods in django?

I have a model like this: class Car(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) create_date = models.DateTimeField('date added', auto_now_add=True) modify_date = models.DateTimeField('date modified', auto_now=True) ... def last_tracked_location(self): ... try: url = '...
Tom
1

votes
0

answer
64

Views

How to access excel data in django response for testing?

I have used xlwt for export some data to the client in django. Now i am testing the function and hence i want to verify that the data in response are matching with expected result. How to read the excel data from the response object. The excel data is added to response something like w.save(respons...
1

votes
2

answer
200

Views

Django Tests Pass with SQLite, Fail with Other DB's

My Django tests all pass when I use the built-in SQLite as my database. However, when I switch to the built-in MySQL and PostgreSQL, they fail. (All local database servers.) The connections to the DB are live enough -- the database is created and migrations applied. But the tests aren't even hitt...
emft
1

votes
1

answer
174

Views

In Django test there is empty queryset when assigned to variable but not empty when printed in console during debug

I'm debugging Django (1.11.8) test and observing strange behavior, when stopped in debugger and switched to Ipython console typing: Model.objects.all() returns non-empty Queryset. However, when the same expressions is assigned to variable e.g.: obj_qs = Model.objects.all() then obj_qs is empty Query...
izkeros
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
69

Views

Test case data stays in Django development database Selenium

I have a simple form for registering new user. I wrote a test case for it. It looks as follows: class AccountTestCase(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() super(AccountTestCase, self).setUp() def tearDown(self): self.selenium.quit() super(AccountTestCase, self).t...
Ojas Kale
1

votes
1

answer
93

Views

How can I test alternative body content in EmailMultiAlternatives object using django test system?

I have EmailMultiAlternatives object with text and html content in my view: email = EmailMultiAlternatives(subject=subject, body=message, from_email=sender, to=recipient) email.attach_alternative(messageHTML, 'text/html') When I test the content of message body attribute contains the text version an...
1

votes
1

answer
79

Views

Django tests taking a long time to start

I'm running tests on a django App called stats which uses a Postgre database. The project keeps all tests in a folder ./stats/tests/. When I run a test i.e. python manage.py test stats.tests.test_dataGeneration, several minutes of nothing pass where the text cursor in my command line just blinks. At...
Phil Dwan
1

votes
0

answer
100

Views

factory_boy DjangoModelFactory not creating Model entries for testing

I am trying to test my django app using factory_boy to setup the model instances. I have the following factories setup for certain Django models. class StudyFactory(DjangoModelFactory): class Meta: model = Study group = SubFactory(GroupFactory) @create_attrs(values) class SomeFactory(DjangoModelFact...
Ry John
1

votes
1

answer
78

Views

Django PUT TestCase fails if client initialised in setUpTestData() but passes if client initialized in setUp()

I am writing tests where every test case passes except the PUT from django.test import TestCase from rest_framework.test import APIClient class ViewTestCase(TestCase): @classmethod def setUpTestData(cls): cls.client = APIClient() def setUp(self): '''setUp() runs before every single test method.''' s...
Abhinav
1

votes
1

answer
59

Views

Django unit test will not update BooleanField

I have a situation where I want to have published functionality for articles, and I have it. The problem is that I can't get my unit test to work properly, trying to post True to the published field. Here's what my tests look like. class ArticleDetailViewTest(TestCase): def setUp(self): email = 'tes...
1

votes
0

answer
32

Views

Testing Django Wizard Views

I'm writing tests for my wizard using this excellent example from PyDoc.net. One of the methods in my TestCase is not returning the correct step in the wizard: class WizardTests(TestCase): wizard_step_data = ( { 'step2-address': '123 Anywhere Ln.' 'wizard_wizard-current_step': 'step2' }, ) def test_...
Andrew Pulley
1

votes
1

answer
23

Views

Django TestCase on form validation fails even tough input is valid

As in the title described I've got a form which validates correctly when I am using the FormView. However as I started writting tests today the same input fails in the TestCase and I get the following error: {'programming_language': ['Select a valid choice. That choice is not one of the available c...
MushroomMauLa
1

votes
1

answer
40

Views

Testing with Django client multiple checkboxes

I read recently a book about TDD in Python and figured I could start to follow this pattern. But the first problem has already appeared and I can't seem to be able to fix it. HTML form (declared in forms.py) When I POST and print it, I get the following output: In order to test this view, into the t...
inidar
1

votes
1

answer
38

Views

VSCode debugging, passing file as Python module

I am working on a Django project and I use VSCode for an editor. More so, I've found the IDE capabilities very useful. So now I'm trying to debug the tests that have failed before. In the debugging configuration I have the following: { 'name' : 'Django: TestServer', 'type' : 'python', 'r...
Diego
1

votes
1

answer
17

Views

SMS/Text backend in Django

I want to create a backend for sending SMS/Text like the EmailBackEnd I can accomplish the task of sending SMS just fine but the trouble is testing. I can test how many email's are sent during the tests using django.core.mail.outbox I want to do something similar for SMS say sms.smsoutbox so how wou...
naveen.panwar
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
243

Views

How can reverse('opensearch') work in the shell, but fails in a Test?

I'm trying to install django-lean into my application. Open search is used in my app App. I can reverse('opensearch') in the Python shell. However, in the test, reverse('opensearch') * NoReverseMatch: Reverse for 'opensearch' with arguments '()' and keyword arguments In [47]: reverse('opensearch')...
BryanWheelock
1

votes
1

answer
191

Views

Django testing - Multiple queries when externally modifying the data. Cache Issue?

I have a legacy application which is (currently) using Django to effectively display data. A sample of one of my working tests looks like this. def test_add_property_value(self): '''Test set / get a value''' # This will do some external process which occcurs to the db. pm = Pm(mysql_db='test_bugs')...
rh0dium
1

votes
1

answer
379

Views

Installed Django app (registration) not using main urls.py for tests

I'm not sure if this is a bug with django-registration or what I'm doing. I have a bare minimum project, with django-registration installed and no apps of my own. Django-registration requires a few templates, so I have them in templates/registration. In each template, I have a template tag {% url in...
Oliver Zheng
1

votes
2

answer
1.1k

Views

Django test fails when creating test database

It fails with a number of related_name-related issues. Of course when running the actual dev server (with ./manage.py runserver) this doesn't happen, I'm guessing maybe the models are being generated twice? I'm running psycopg2 2.4.1, and here's my test output: (venv)[email protected]:boilerplate$...
Lacrymology
1

votes
2

answer
872

Views

Am I mocking this helper function right in my Django test?

lib.py from django.core.urlresolvers import reverse def render_reverse(f, kwargs): ''' kwargs is a dictionary, usually of the form {'args': [cbid]} ''' return reverse(f, **kwargs) tests.py from lib import render_reverse, print_ls class LibTest(unittest.TestCase): def test_render_reverse_is_correct(s...
CppLearner
1

votes
1

answer
556

Views

temporary TEMPLATE_DIRS override for testing does not work

For testing a custom templatetag i need to test a function that returns a rendered template. To be able to compare the output without having to know about the user-generated production template (which is going to change every now and then), i try to override the TEMPLATE_DIRS setting. Looks like a p...
marue
1

votes
1

answer
555

Views

Django selenium liveserver redirects to admin site

I'm using django 1.3 with Django liveserver backported to 1.3. It worked fine, when i was doing tutorial from Django LiverserverTestCase documentaion but with imports for django 1.3. It tests '/admin/' page and is ok, but when i try to test my urls, even just '/', it goes to admin again! why? I didn...
Feanor
1

votes
1

answer
727

Views

Make LiveServerTestCase not to call setUp() before each test

I have one problem with testing django app by using LiveServerTestCase. LiveServerTestCase execute setUp() function before executing each test. But I'm using factory-boy's factories to create objects for testing (users, items, etc...). And the same objects are created before executing each test. How...
Dmitry Belaventsev
1

votes
1

answer
52

Views

Can django testing with databases be fixed for MySQL?

I have a large django project (AskBot) that I am running the tests for. When I configure DATABASES to use sqlite, the tests pass. When I figure to use PostgreSQL, the tests pass, but when I configure to use MySQL, some of the tests fail. By inspecting the test database that is created during testing...
Robert Martin
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
49

Views

Django testing, need fixtures for picture

So I'm doing some unittests on a particular Django app. When in a testing environment, I basically create a fresh database with my own data. In a normal non-testing environment, I load up a page with a person's details. When this happens a signal is sent and it retrieves the person's picture (which...
user2564502
1

votes
1

answer
68

Views

Tests assertHTTP 400

When I try to save a model that has expired my custom error returns a 400 BadRequest. For example: Model: def save(self, force_insert=False, force_update=False, *args, **kwargs): if self.incentive.has_expired(): raise CustomBadRequest( code='missing_key', message='Expired on {expiry_date}' .format(e...
Prometheus
1

votes
1

answer
63

Views

How to test the behavior of app when the database backend out of service

Our app has a specific behavior when the database is out of service. I want to write a test for this behavior but in can't find a solution. I suppose the simplest way is to break database auth or name but : override_settings can't change the DATABASE settings ( https://code.djangoproject.com/ticket/...
fabien-michel
1

votes
1

answer
775

Views

Django DateField returns DateTime object in test

I use Django 1.7b2 and Django REST framework and write some test cases. There is a custom User model which birthday field is added as below. class User(AbstractBaseUser): first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.E...
brsbilgic
1

votes
1

answer
297

Views

Why isn't Django creating blank a database during test?

When I run a unit test, Django 1.6 doesn't seem to be creating a blank database to test from and I don't understand why. The Django docs say that Django doesn't use your production database but instead creates a separate, blank database for testing. However, when I debug my test 'test_get_user_ids...
Jim
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
1

answer
241

Views

Django-nonrel + MongoDB error while running tests

I have a setup inside a virtual environment: Django-nonrel-1.6 mongodb-engine djangotoolbox Everything works fine, the only problem is during running tests. Every time django tries to flush database after running a test function it throws an error: Traceback (most recent call last): File '/home/leh...
lehins
1

votes
1

answer
141

Views

Is it possible to run Django tests on Apache instead of the development server?

When I test my Django web application with python manage.py test, this starts Django's development server and runs the test. I want to run my Django tests on my production stack. Specifically, I want to use Apache instead of Django's development server. Is there a way to do this? I've looked through...
Travis
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
198

Views

How to create a patch/update (i.e. update an object) request in Django test client?

I am using Django 1.5. and django-tastypie I am testing a use case where, first I have to create an object and then update that object via rest api. e.g. class FooTest(TestCase): fixtures = ['df_fixtures1.json'] def setUp(self): print 'SETTING UP?' def tearDown(self): print 'Tear Down' def test_foo...
Akash Deshpande
1

votes
1

answer
428

Views

Django testcase without database migrations and syncdb

I am trying to create test cases for my migration functions (called with migrations.RunPython). My idea was to create a test case that doesn’t run migrations before starting, neither syncdb to create the database in one step. After this, I’m planning to run the first step, run associated tests,...
GergelyPolonkai
1

votes
1

answer
23

Views

Testing for exception fails

When I save a User model, I would like to check if it has a username. Therefore I wrote this pre_save: @receiver(pre_save, sender=User) def validate_user(sender, instance, **kwargs): if len(instance.username)
Saphire
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

View additional questions