Menu
  • HOME
  • TAGS

Django Test Client not working with Database calls

django-testing

Create a user in either the setUp() method of the TestCase, or add one in a fixture. Here's the setUp() version: class YourTestCase(TestCase): def setUp(self): self.user = User.objects.create( username='someuser', email='[email protected]', password='password' ) def test_your_code(self): # now you can look it up user = User.objects.get(username='someuser') self.assertEqual(user.email, '[email protected]') ...

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

python,django,django-testing,django-tests

Wow, what a wild and crazy ride!! It turns out it was an issue in the RelatedListFilter with a custom queryset that was causing problems. The comments on this answer point out that: The filter lookups are getting cached in some way and field and field.rel objects will persist between...

Is APITest with Query params different then just normal url?

django,unit-testing,django-rest-framework,django-testing

Try passing the query parameter as a data payload instead. Change the line in your test to: response = self.client.get('/api/titles-and-blurbs/', {'genre': 'horror'}) Django docs here on the different ways to pass query parameters in urls. Another person reported a similar issue with an empty QUERY_PARAMS while testing DRF (see here)....

How to use verbosity level in your tests in Django

django,django-testing,django-unittest

You can use inspect module: from django.test import TestCase import inspect class MyTest(TestCase): def get_verbosity(self): for s in reversed(inspect.stack()): options = s[0].f_locals.get('options') if isinstance(options, dict): return int(options['verbosity']) return 1 def test_func(self): verbosity = self.get_verbosity() self.assertEqual(verbosity, 2) ...

Logging in as an inactive user in a Django test

python,django,django-authentication,django-testing,django-1.7

I was able to solve this by setting the user to active right before doing the login: class BasicTest(TestCase): def setUp(self): u = InactiveUserFactory() u.set_password('test_pass') u.save() self.participant = ParticipantFactory(user=u) self.u = self.participant.user self.u.is_active = True self.u.save() login = self.client.login(username=self.u.username, password='test_pass') assert(login is True) self.u.is_active = False self.u.save() ...

Django: How to associate a user with a request factory

python,django,testing,django-testing,django-tests

I think that the RequestFactory and the client are two different ways of testing django views. The request that is returned from rf.post is meant to be passed directly to a view function. If you were to do that, i think you will find that, the user will be detected...

Django Modular Testing

django,django-testing

You can simplify and reduce the amount of code you have by using 2 libraries: WebTest and FactoryBoy. You won't need these Mixins. https://pypi.python.org/pypi/django-webtest https://github.com/rbarrois/factory_boy Do the change step by step: 1. Starts with WebTest so you can get rid of your login_ method (and you won't need to prepare...

How to handle CommandError exceptions in Django tests

django,django-testing,django-manage.py,django-tests

If your expected behaviour is exception, you can use the assertRaises, look here: https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises

How to test ModelForm save() method saves changes in model?

python,django,django-forms,django-testing,django-modeladmin

def test_form_saves_values_to_instance_user_on_save(self): """ test form saves name, surname, email values to corresponding User object when commiting form """ person = Person.objects.get(user__username='admin') personform = PersonForm(instance=person, data={'name': 'has_changed'}) if personform.is_valid(): person = personform.save() self.assertEquals(person.user.first_name, "has_changed") else: self.fail("personform not valid") I think you also need to exclude the user field from your form...

Django test client does not handle exceptions?

python,django,http-status-code-500,django-testing

Django test client handles only some exceptions (see https://docs.djangoproject.com/en/1.7/topics/testing/tools/#exceptions). All the others are visible in the test and you can test them ;)

Fixture inheritance in django TestCase

django,django-testing

When you override fixtures in a subclass, it replaces the fixtures, it doesn't extend them. You can either explicitly repeat the fixtures: class SpecificTest(BaseTest): fixtures = ('users.json', 'transactions.json',) or refer to BaseTest.fixtures in your subclass: class SpecificTest(BaseTest): fixtures = BaseTest.fixtures + ('transactions.json',) ...

How can i stop django to recreate test database

python,django,django-testing

If you are just testing for development purposes, I'd recommend setting your testing database to use sqlite3, which will leverage an in-memory database by default and should speed up tests. I usually put this into local_settings which only gets executed for my dev environment... if 'test' in sys.argv: DATABASES['default'] =...

Write test for views containing os.remove in django

python,django,django-testing,django-tests

Yes. It's called mocking, and there is a Python library for it: mock. Mock is available in the standard library as unittest.mock for Python 3.3+, or standalone for earlier versions. So you would do something like this: from mock import patch ... @patch('mymodel_module.os.remove') def test_my_method(self, mocked_remove): call_my_model_method() self.assertTrue(mocked_remove.called) (where mymodel_module...

Integrity error when loading fixtures for Selenium testing in Django

django,selenium,fixtures,django-testing

After some more reading about how Django maintains its own models and such, it is my understanding that Django caches the contenttype, auth.Permission, etc and uses them in testing frameworks (I was using StaticLiveServerTestCase). This means that when I was loading my fixture, it was clashing with the data Django...

django 1.6 app tests.py to tests subdirectory

django,django-testing,django-1.6

Explicitly import management from app: from app.management.commands.getevents import some_function Just to prove my words with a working example, check how custom management command is imported in django-compressor tests: from compressor.management.commands.compress import Command as CompressCommand ...

Django test RequestFactory vs Client

django,unit-testing,django-views,django-rest-framework,django-testing

RequestFactory and Client have some very different use-cases. To put it in a single sentence: RequestFactory returns a request, while Client returns a response. The RequestFactory does what it says - it's a factory to create request objects. Nothing more, nothing less. The Client is used to fake a complete...

No module named .. while running Django tests with PyCharm

django,pycharm,django-testing

Ok, I found the problem. Problem was that PyCharm also have module named utils, and so the import was not using my module, but the PyCharm's one.

Django Testing: Does --keepdb reset changes made during tests?

django,django-testing,django-tests

If you're using Django's default TestCase, all tests are run in a transaction, which is rolled back when the tests finishes. If your database supports transactions, you won't have to clean up anything. If you're using Django's LiveServerTestCase or TransactionTestCase, all tables are truncated after each test, and the initial...

How to create table during Django tests with managed = False?

python,django,django-testing,django-1.7,django-migrations

I found a way. Modify the fixtures and add the SQL to generate the tables: #0001_initial.py (or followings) class Migration(migrations.Migration): operations = [ migrations.RunSQL("CREATE TABLE..."), ... ] I'm a "migrations newbie" so I don't know if this is the best option. But it works....

Django Test Discovery Issues

django,django-testing

Try to use --pattern="test*" (no py at the end).

relation “auth_user” does not exist

django,django-testing

You need to create a migration for the model WatchStock.

django test client fails, but url works

django,unit-testing,django-testing

As you can see from the traceback, id passed in kwargs is evaluated to None. This is why it is not matching the usuarios/perfil/(?P<id>\\d+)/$ url pattern. In other words usuario_fake.pk value is None. UPD: the problem was actually in the template which the traceback was complaining about....

Using coverage, how do I test this line?

python,django,django-testing

The coverage report shows that the method is being called (line 80 is green). But it also shows that it was never defined (line 75 is red). This is a classic problem of starting coverage too late. The simplest way to fix this is to use coverage to run your...

How to use Django's assertJSONEqual to verify response of view returning JsonResponse

python,django,python-3.x,django-testing,jsonresponse

It looks like you're working with Python 3 so you'll need to turn response.content into a UTF-8 encoded string before passing it to self.assertJSONEqual: class AddItemToCollectionTest(TestCase): def test_success_when_not_added_before(self): response = self.client.post('/add-item-to-collection') self.assertEqual(response.status_code, 200) self.assertJSONEqual( str(response.content, encoding='utf8'), {'status': 'success'} ) If you want to simultaneously support both Python 2.7 and Python...

Django unit test to verify None fields on model

django,python-3.x,django-testing

Try to save object to DB and test will fail: item = Item() item.save() Or shorter version with the same result: Item.objects.create() ...

Django testing wastes too much time on test database creating

python,django,testing,django-testing

You can use django-nose and reuse the database like this: REUSE_DB=1 ./manage.py test Be careful that your tests do not leave any junk in the DB. Have a look at the documentation for more info....

Authentication failed in Django test

python,django,django-testing

So I just figured it out this FN test is using default database rather then test database, so I changed the flow

Django - Writing Tests: Unit testing extra variables passed to generic views

django-class-based-views,django-testing

Okay, I finally figured this one out. Pretty simple: from django.test import TestCase from views import PurchaseIndex class IndexPageTest(TestCase): def test_current_purchase_index_displays_year(self): context = PurchaseIndex.list_year(self) self.assertEqual(2015, context) def test_current_shipments_included_in_current_purchase_index(self): context = PurchaseIndex.purchase_yrs(self) self.assertIn(2015, context) self.assertIn(2014, context) ...

Django Postgres Tests, Set DB encoding

python,django,postgresql,django-testing

You can define charset for test database in your settings.py file: https://docs.djangoproject.com/en/1.6/ref/settings/#std:setting-TEST_CHARSET

Django get_signed_cookie on manually signed cookie

python,django,cookies,django-rest-framework,django-testing

I have found my solution. It was rather straightforward actually. I tried to set my cookie on my request for the test, which made sense since the cookie should be sent in the request. A better way of testing it is to just GET a resource first (which sets te...

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

django,django-models,django-testing

I'm going to take a stab and say that its because you are using nosetests instead of the Django test runner. Because you are using nosetests, Django's setup_test_environment isn't being called, which means the code doesn't know to use the test database correctly. Here are the relevant parts of the...

Django testing ajax endpoint in view

python,ajax,django,unit-testing,django-testing

You could use something like django-casper: https://github.com/dobarkod/django-casper I haven't used it, but it appears to be a django-specific python library which interfaces with CasperJS and PhantomJS. PhantomJS is a web-kit based headless browser that gives a more light-weight alternative to browser automation with selenium....

Users not created correctly in Django test case

django,django-models,django-testing

The user is not being created, because the setup method is not being run. It should be called setUp - note the upper-case U. See the Python documentation.