Skip to content

Commit

Permalink
Split tests in multiple files + cleanup
Browse files Browse the repository at this point in the history
* split tests in multiple files for clarity
* eliminated redundant (copy & paste) tests
* ensured tests belong to what is being tested (had to move few tests between the suites)
  • Loading branch information
nemesifier committed Jun 29, 2015
1 parent 2097af1 commit 5e403bf
Show file tree
Hide file tree
Showing 8 changed files with 1,911 additions and 2,014 deletions.
2,014 changes: 0 additions & 2,014 deletions tests/django_hstore_tests/tests.py

This file was deleted.

Empty file.
688 changes: 688 additions & 0 deletions tests/django_hstore_tests/tests/test_dictionary_field.py

Large diffs are not rendered by default.

73 changes: 73 additions & 0 deletions tests/django_hstore_tests/tests/test_gis_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from django_hstore.apps import GEODJANGO_INSTALLED

if GEODJANGO_INSTALLED:
from django.test import TestCase
from django.contrib.gis.geos import GEOSGeometry
from django_hstore_tests.models import Location

class TestDictionaryFieldPlusGIS(TestCase):
""" Test DictionaryField with gis backend """
pnt1 = GEOSGeometry('POINT(65.5758316 57.1345383)')
pnt2 = GEOSGeometry('POINT(65.2316 57.3423233)')

def setUp(self):
Location.objects.all().delete()

def _create_locations(self):
loc1 = Location.objects.create(name='Location1', data={'prop1': '1', 'prop2': 'test_value'}, point=self.pnt1)
loc2 = Location.objects.create(name='Location2', data={'prop1': '2', 'prop2': 'test_value'}, point=self.pnt2)
return loc1, loc2

def test_location_create(self):
l1, l2 = self._create_locations()
other_loc = Location.objects.get(point__contains=self.pnt1)
self.assertEqual(other_loc.data, {'prop1': '1', 'prop2': 'test_value'})

def test_location_hupdate(self):
l1, l2 = self._create_locations()
Location.objects.filter(point__contains=self.pnt1).hupdate('data', {'prop1': '2'})
loc = Location.objects.exclude(point__contains=self.pnt2)[0]
self.assertEqual(loc.data, {'prop1': '2', 'prop2': 'test_value'})
loc = Location.objects.get(point__contains=self.pnt2)
self.assertNotEqual(loc.data, {'prop1': '1', 'prop2': 'test_value'})

def test_location_contains(self):
l1, l2 = self._create_locations()
self.assertEqual(Location.objects.filter(data__contains={'prop1': '1'}).count(), 1)
self.assertEqual(Location.objects.filter(data__contains={'prop1': '2'}).count(), 1)

def test_location_geomanager(self):
l1, l2 = self._create_locations()
d1 = Location.objects.filter(point__distance_lte=(self.pnt1, 70000))
self.assertEqual(d1.count(), 2)

def test_manager(self):
from django_hstore.managers import HStoreGeoManager
isinstance(Location.objects, HStoreGeoManager)
hasattr(Location.objects, 'hpeek')
hasattr(Location.objects, 'hslice')
hasattr(Location.objects, 'hkeys')

# noqa
class TestReferencesFieldPlusGIS(TestDictionaryFieldPlusGIS):
""" Test ReferenceField with gis backend """

def _create_locations(self):
loc1 = Location.objects.create(name='Location1', data={'prop1': '1', 'prop2': 'test_value'}, point=self.pnt1)
loc2 = Location.objects.create(name='Location2', data={'prop1': '2', 'prop2': 'test_value'}, point=self.pnt2)
return loc1, loc2

def test_location_create(self):
l1, l2 = self._create_locations()
loc_1 = Location.objects.get(point__contains=self.pnt1)
self.assertEqual(loc_1.data, {'prop1': '1', 'prop2': 'test_value'})
loc_2 = Location.objects.get(point__contains=self.pnt2)
self.assertEqual(loc_2.data, {'prop1': '2', 'prop2': 'test_value'})

def test_location_hupdate(self):
l1, l2 = self._create_locations()
Location.objects.filter(point__contains=self.pnt1).hupdate('data', {'prop1': '2'})
loc = Location.objects.exclude(point__contains=self.pnt2)[0]
self.assertEqual(loc.data, {'prop1': '2', 'prop2': 'test_value'})
loc = Location.objects.get(point__contains=self.pnt2)
self.assertNotEqual(loc.data, {'prop1': '1', 'prop2': 'test_value'})
39 changes: 39 additions & 0 deletions tests/django_hstore_tests/tests/test_not_transactional.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from django import VERSION as DJANGO_VERSION
from django.db import transaction, connection
from django.test import SimpleTestCase

from django_hstore.fields import HStoreDict

from django_hstore_tests.models import DataBag


class TestNotTransactional(SimpleTestCase):
if DJANGO_VERSION[:2] >= (1, 8):
def setUp(self):
# avoid error "connection already closed"
connection.connect()

if DJANGO_VERSION[:2] >= (1, 6):
def test_hstore_registring_in_transaction_block(self):
obj1 = DataBag.objects.create(name='alpha1', data={'v': '1', 'v2': '3'})
obj2 = DataBag.objects.create(name='alpha2', data={'v': '1', 'v2': '3'})
# Close any existing connection before doing anything
connection.close()
with transaction.atomic():
qs = DataBag.objects.filter(name__in=["alpha2", "alpha1"])
self.assertIsInstance(qs[0].data, HStoreDict)
obj1.delete()
obj2.delete()
connection.close()
else:
def test_hstore_registring_in_transaction_block(self):
obj1 = DataBag.objects.create(name='alpha1', data={'v': '1', 'v2': '3'})
obj2 = DataBag.objects.create(name='alpha2', data={'v': '1', 'v2': '3'})
# Close any existing connection before doing anything
connection.close()
with transaction.commit_on_success():
qs = DataBag.objects.filter(name__in=["alpha2", "alpha1"])
self.assertIsInstance(qs[0].data, HStoreDict)
obj1.delete()
obj2.delete()
connection.close()
192 changes: 192 additions & 0 deletions tests/django_hstore_tests/tests/test_reference_field.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.test import TestCase
from django import forms

from django_hstore.forms import ReferencesFieldWidget
from django_hstore.utils import unserialize_references, serialize_references, acquire_reference

from django_hstore_tests.models import Ref, RefsBag, NullableRefsBag


class TestReferencesField(TestCase):
def setUp(self):
Ref.objects.all().delete()
RefsBag.objects.all().delete()

def _create_bags(self):
refs = [Ref.objects.create(name=str(i)) for i in range(4)]
alpha = RefsBag.objects.create(name='alpha', refs={'0': refs[0], '1': refs[1]})
beta = RefsBag.objects.create(name='beta', refs={'0': refs[2], '1': refs[3]})
return alpha, beta, refs

def test_empty_instantiation(self):
bag = RefsBag.objects.create(name='bag')
self.assertTrue(isinstance(bag.refs, dict))
self.assertEqual(bag.refs, {})

def test_unsaved_empty_instantiation(self):
bag = RefsBag(name='bag')
self.assertEqual(bag.refs.get('idontexist', 'default'), 'default')
self.assertTrue(isinstance(bag.refs, dict))

def test_unsave_empty_instantiation_of_nullable_ref(self):
bag = NullableRefsBag(name='bag')
self.assertEqual(bag.refs.get('idontexist', 'default'), 'default')
self.assertTrue(isinstance(bag.refs, dict))

def test_simple_retrieval(self):
alpha, beta, refs = self._create_bags()
alpha = RefsBag.objects.get(name='alpha')
self.assertEqual(Ref.objects.get(name='0'), alpha.refs['0'])

def test_simple_retrieval_get(self):
alpha, beta, refs = self._create_bags()
alpha = RefsBag.objects.get(name='alpha')
self.assertEqual(Ref.objects.get(name='0'), alpha.refs.get('0'))

# try getting a non existent key
self.assertEqual(alpha.refs.get('idontexist', 'default'), 'default')
self.assertEqual(alpha.refs.get('idontexist'), None)

def test_empty_querying(self):
RefsBag.objects.create(name='bag')
self.assertTrue(RefsBag.objects.get(refs={}))
self.assertTrue(RefsBag.objects.filter(refs={}))
self.assertTrue(RefsBag.objects.filter(refs__contains={}))

def test_equivalence_querying(self):
alpha, beta, refs = self._create_bags()
for bag in (alpha, beta):
refs = {'0': bag.refs['0'], '1': bag.refs['1']}
self.assertEqual(RefsBag.objects.get(refs=refs), bag)
r = RefsBag.objects.filter(refs=refs)
self.assertEqual(len(r), 1)
self.assertEqual(r[0], bag)

def test_key_value_subset_querying(self):
alpha, beta, refs = self._create_bags()
for bag in (alpha, beta):
r = RefsBag.objects.filter(refs__contains={'0': bag.refs['0']})
self.assertEqual(len(r), 1)
self.assertEqual(r[0], bag)
r = RefsBag.objects.filter(refs__contains={'0': bag.refs['0'], '1': bag.refs['1']})
self.assertEqual(len(r), 1)
self.assertEqual(r[0], bag)

def test_multiple_key_subset_querying(self):
alpha, beta, refs = self._create_bags()
for keys in (['0'], ['0', '1']):
self.assertEqual(RefsBag.objects.filter(refs__contains=keys).count(), 2)
for keys in (['0', 'nv'], ['n1', 'n2']):
self.assertEqual(RefsBag.objects.filter(refs__contains=keys).count(), 0)

def test_single_key_querying(self):
alpha, beta, refs = self._create_bags()
for key in ('0', '1'):
self.assertEqual(RefsBag.objects.filter(refs__contains=[key]).count(), 2)
for key in ('n1', 'n2'):
self.assertEqual(RefsBag.objects.filter(refs__contains=[key]).count(), 0)

def test_hkeys(self):
alpha, beta, refs = self._create_bags()
self.assertEqual(RefsBag.objects.hkeys(id=alpha.id, attr='refs'), ['0', '1'])

def test_hpeek(self):
alpha, beta, refs = self._create_bags()
self.assertEqual(RefsBag.objects.hpeek(id=alpha.id, attr='refs', key='0'), refs[0])
self.assertEqual(RefsBag.objects.filter(id=alpha.id).hpeek(attr='refs', key='0'), refs[0])
self.assertEqual(RefsBag.objects.hpeek(id=alpha.id, attr='refs', key='invalid'), None)

def test_hremove(self):
alpha, beta, refs = self._create_bags()
self.assertEqual(RefsBag.objects.get(name='alpha').refs['0'], alpha.refs['0'])
self.assertEqual(RefsBag.objects.get(name='alpha').refs['1'], alpha.refs['1'])
self.assertIn("0", RefsBag.objects.get(name='alpha').refs)
RefsBag.objects.filter(name='alpha').hremove('refs', '0')
self.assertNotIn("0", RefsBag.objects.get(name='alpha').refs)
self.assertIn("1", RefsBag.objects.get(name='alpha').refs)

self.assertEqual(RefsBag.objects.get(name='beta').refs['0'], beta.refs['0'])
self.assertEqual(RefsBag.objects.get(name='beta').refs['1'], beta.refs['1'])
RefsBag.objects.filter(name='beta').hremove('refs', ['0', '1'])
self.assertEqual(RefsBag.objects.get(name='beta').refs, {})

def test_hslice(self):
alpha, beta, refs = self._create_bags()
self.assertEqual(RefsBag.objects.hslice(id=alpha.id, attr='refs', keys=['0']), {'0': refs[0]})
self.assertEqual(RefsBag.objects.filter(id=alpha.id).hslice(attr='refs', keys=['0']), {'0': refs[0]})
self.assertEqual(RefsBag.objects.hslice(id=alpha.id, attr='refs', keys=['invalid']), {})

def test_admin_reference_field(self):
alpha, beta, refs = self._create_bags()

# create admin user
admin = User.objects.create(username='admin', password='tester', is_staff=True, is_superuser=True, is_active=True)
admin.set_password('tester')
admin.save()
# login as admin
self.client.login(username='admin', password='tester')

# access admin change form page
url = reverse('admin:django_hstore_tests_refsbag_change', args=[alpha.id])
response = self.client.get(url)
# ensure textarea with id="id_data" is there
self.assertContains(response, 'textarea')
self.assertContains(response, 'id_refs')

def test_unserialize_references_edge_cases(self):
alpha, beta, refs = self._create_bags()

refs = unserialize_references(alpha.refs)
# repeat
refs = unserialize_references(alpha.refs)
self.assertEqual(len(unserialize_references(refs).keys()), 2)
self.assertEqual(unserialize_references(None), {})

def test_unserialize_references(self):
alpha, beta, refs = self._create_bags()
ref = dict(alpha=alpha, beta=beta)
serialized_refs = serialize_references(ref)
unserialized_refs = unserialize_references(serialized_refs)
self.assertEqual(unserialized_refs['alpha'].pk, alpha.pk)
self.assertEqual(unserialized_refs['beta'].pk, beta.pk)

def test_serialize_references_edge_cases(self):
self.assertEqual(serialize_references(None), {})
self.assertEqual(serialize_references({'test': 'test'}), {'test': 'test'})

def test_acquire_references_value_error(self):
with self.assertRaises(ValueError):
acquire_reference(None)
with self.assertRaises(ValueError):
acquire_reference('')

def test_acquire_references_none(self):
self.assertIsNone(acquire_reference('django_hstore_tests.models.SchemaDataBag:2'))

def test_str(self):
r = RefsBag()
self.assertEqual(str(r.refs), '{}')

def test_references_default_admin_widget(self):
class HForm(forms.ModelForm):
class Meta:
model = RefsBag
exclude = []

form = HForm()
self.assertEqual(form.fields['refs'].widget.__class__, ReferencesFieldWidget)

def test_references_custom_admin_widget(self):
class CustomWidget(forms.Widget):
pass

class HForm(forms.ModelForm):
class Meta:
model = RefsBag
widgets = {'refs': CustomWidget}
exclude = []

form = HForm()
self.assertEqual(form.fields['refs'].widget.__class__, CustomWidget)
Loading

0 comments on commit 5e403bf

Please sign in to comment.