import json from django.contrib.auth.models import User from django.test import TestCase, Client from contribmap.models import Contrib class APITestClient(Client): def json_get(self, *args, **kwargs): """ Annotate the response with a .data containing parsed JSON """ response = super().get(*args, **kwargs) response.data = json.loads(response.content.decode('utf-8')) return response class APITestCase(TestCase): def setUp(self): super().setUp() self.client = APITestClient() class TestContrib(TestCase): def test_comma_separatedcharfield(self): co = Contrib(name='foo', orientations=['SO', 'NE']) co.save() self.assertEqual( Contrib.objects.get(name='foo').orientations, ['SO', 'NE']) co.orientations = ['S'] co.save() class TestContribPrivacy(TestCase): def test_always_private_field(self): c = Contrib.objects.create( name='John', phone='010101010101', contrib_type=Contrib.CONTRIB_CONNECT, ) self.assertEqual(c.get_public_field('phone'), None) def test_public_field(self): c = Contrib.objects.create( name='John', phone='010101010101', contrib_type=Contrib.CONTRIB_CONNECT, privacy_name=True, ) self.assertEqual(c.get_public_field('name'), 'John') def test_public_callable_field(self): c = Contrib.objects.create( name='John', phone='010101010101', orientations=['N'], contrib_type=Contrib.CONTRIB_CONNECT, privacy_name=True, ) self.assertEqual(c.get_public_field('angles'), [[-23, 22]]) def test_private_field(self): c = Contrib.objects.create( name='John', phone='010101010101', contrib_type=Contrib.CONTRIB_CONNECT, ) self.assertEqual(c.privacy_name, False) self.assertEqual(c.get_public_field('name'), None) class TestViews(APITestCase): def test_public_json(self): response = self.client.json_get('/map/public.json') self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data['features']), 0) Contrib.objects.create( name='John', phone='010101010101', contrib_type=Contrib.CONTRIB_CONNECT, privacy_coordinates=False, ) response = self.client.json_get('/map/public.json') self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data['features']), 1) def test_private_json(self): self.client.force_login( User.objects.create(username='foo', is_staff=False)) response = self.client.get('/map/private.json') self.assertEqual(response.status_code, 403) def test_private_json_staff(self): self.client.force_login( User.objects.create(username='foo', is_staff=True)) response = self.client.get('/map/private.json') self.assertEqual(response.status_code, 200) class TestDataImport(TestCase): fixtures = ['bottle_data.yaml'] def test_re_save(self): for contrib in Contrib.objects.all(): contrib.full_clean() contrib.save()