Opened 15 years ago

Closed 15 years ago

#12530 closed (wontfix)

Code in test classes can get access to live database

Reported by: Art Owned by: nobody
Component: Testing framework Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When assigning fields in a test case class like this:

from django.test import TestCase

class TestClass(TestCase):

    field = [x for x in DataBaseObject.objects.all()]

The code is actually executed against "normal" database in settings.py, not the one which is temporarily created.
Possible workaround is to use property/lambda syntax.

Change History (3)

comment:1 by Russell Keith-Magee, 15 years ago

Resolution: wontfix
Status: newclosed

I acknowledge that this is a problem, but there really isn't anything we can do. A field defined like that will be instantiated when the class is loaded, which occurs before the test framework has a chance to redirect the database that is in use.

The other solution that you don't mention (and the solution that makes more sense to me anyway) is to set up the field in the setUp() method. During the call to setUp(), the test database will be in place. As an added bonus, setUp() is called at the start of every test run, guaranteeing that you won't have any artefact leakage between tests (i.e., test_1 modifies self.field, affecting the outcome of test_2).

Marking wontfix because there isn't really a fix, and the workaround is preferable to the problematic syntax.

comment:2 by Art, 15 years ago

Resolution: wontfix
Status: closedreopened

I would like to re-open this.

My impression was that creation of instances of Test Classes was controlled by django.
If that's the case (only if!) then why can't it initialise the settings beforehand?

The whole thing is kind of dangerous - I can see the use case when you need to run the tests in production, and having any test code there which can potentially modify prod data is really bad.

comment:3 by Russell Keith-Magee, 15 years ago

Resolution: wontfix
Status: reopenedclosed

We control the creation of test classes, but we don't control the way that Python parses code. The problem here is that the class-level property is instantiated when the class is parsed - which is when you test module is imported.

Please don't reopen tickets once they have been closed by a core developer or member of the triage team. If you disagree with a decision that has been made, open a discussion on the django-developers mailing list.

Note: See TracTickets for help on using tickets.
Back to Top