def setup_models(self): self.project = ProjectFactory.create(current_questionnaire='a1') self.spatial_unit = SpatialUnitFactory(project=self.project) content_type = ContentType.objects.get( app_label='party', model='tenurerelationship') schema = Schema.objects.create( content_type=content_type, selectors=(self.project.organization.id, self.project.id, 'a1')) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create( schema=schema, name='r_name', long_name='Relationship field', attr_type=attr_type, index=0, required=False, omit=False ) content_type = ContentType.objects.get( app_label='party', model='party') schema = Schema.objects.create( content_type=content_type, selectors=(self.project.organization.id, self.project.id, 'a1')) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create( schema=schema, name='p_name', long_name='Party field', attr_type=attr_type, index=0, required=False, omit=False )
def setup_models(self): self.user = UserFactory.create() assign_policies(self.user) self.prj = ProjectFactory.create(slug='test-project', access='public') self.party1 = PartyFactory.create(project=self.prj, name='Landowner') self.su2 = SpatialUnitFactory.create(project=self.prj, type='PA')
def test_update_questionnaire_attribute_schema(self): file = self.get_file( '/questionnaires/tests/files/xls-form-attrs.xlsx', 'rb') form = self.storage.save('xls-forms/xls-form.xlsx', file) project = ProjectFactory.create(name='TestProject') q1 = models.Questionnaire.objects.create_from_form( xls_form=form, project=project ) q2 = models.Questionnaire.objects.create_from_form( xls_form=form, project=project ) assert 12 == Schema.objects.all().count() content_type = ContentType.objects.get( app_label='party', model='party') assert q1.id != q2.id s1 = Schema.objects.get( content_type=content_type, selectors=( project.organization.pk, project.pk, q1.id) ) assert s1 is not None s2 = Schema.objects.get( content_type=content_type, selectors=( project.organization.pk, project.pk, project.current_questionnaire) ) assert s2 is not None assert s1 != s2
def setup_models(self): self.project = ProjectFactory.create() self.resources = ResourceFactory.create_batch( 2, content_object=self.project, project=self.project) self.denied = ResourceFactory.create(content_object=self.project, project=self.project) ResourceFactory.create() self.user = UserFactory.create() assign_policies(self.user, add_clauses=[ { 'effect': 'deny', 'object': ['resource/*/*/' + self.denied.id], 'action': ['resource.*'], }, { 'effect': 'deny', 'object': ['resource/*/*/*'], 'action': ['resource.unarchive'], }, ]) self.storage = self.get_storage() self.file = self.get_file( '/resources/tests/files/image.jpg', 'rb') self.file_name = self.storage.save('resources/image.jpg', self.file)
def setUp(self): self.project = ProjectFactory.create(current_questionnaire='abc1') content_type = ContentType.objects.get( app_label='party', model='party') schema1 = Schema.objects.create( content_type=content_type, selectors=( self.project.organization.id, self.project.id, 'abc1')) schema2 = Schema.objects.create( content_type=content_type, selectors=( self.project.organization.id, self.project.id, 'abc1', 'GR')) create_attribute_type('text', 'Text', 'CharField', validator_type='str') create_attribute_type('boolean', 'boolean', 'BooleanField', validator_type='bool') Attribute.objects.create( schema=schema1, name='fname', long_name='Test field', attr_type=AttributeType.objects.get(name='text'), index=0 ) Attribute.objects.create( schema=schema2, name='homeowner', long_name='Homeowner', attr_type=AttributeType.objects.get(name='boolean'), index=1 )
def test_create_location_with_attributes(self): data = { 'geometry': '{"type": "Polygon","coordinates": [[[-0.1418137550354' '004,51.55240622205599],[-0.14117002487182617,51.55167' '905819532],[-0.1411914825439453,51.55181915488898],[-' '0.1411271095275879,51.55254631651022],[-0.14181375503' '54004,51.55240622205599]]]}', 'type': 'CB', 'spatialunit::default::fname': 'test' } project = ProjectFactory.create() content_type = ContentType.objects.get( app_label='spatial', model='spatialunit') schema = Schema.objects.create( content_type=content_type, selectors=(project.organization.id, project.id, )) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create( schema=schema, name='fname', long_name='Test field', attr_type=attr_type, index=0, required=False, omit=False ) form = forms.LocationForm(project=project, data=data) form.is_valid() form.save() assert SpatialUnit.objects.filter(project=project).count() == 1 unit = SpatialUnit.objects.filter(project=project).first() assert unit.attributes.get('fname') == 'test'
def test_spatial_unit_attribute_schema(self): project = ProjectFactory.create(name='TestProject') QuestionnaireFactory.create(project=project) content_type = ContentType.objects.get( app_label='spatial', model='spatialunit') create_attrs_schema( project=project, dict=location_xform_group, content_type=content_type, errors=[]) spatial_unit = SpatialUnitFactory.create( project=project, attributes={ 'quality': 'polygon_high', 'infrastructure': ['water', 'food'] } ) assert 1 == Schema.objects.all().count() schema = Schema.objects.get(content_type=content_type) assert schema is not None assert schema.selectors == [ project.organization.pk, project.pk, project.current_questionnaire] assert 'quality' in spatial_unit.attributes.attributes assert 'polygon_high' == spatial_unit.attributes['quality'] assert 'infrastructure' in spatial_unit.attributes.attributes assert 'water' in spatial_unit.attributes['infrastructure'] # notes field is omitted in xform assert 'notes' not in spatial_unit.attributes.attributes
def test_repr(self): project = ProjectFactory.build(slug='prj') questionnaire = factories.QuestionnaireFactory.build(id='abc123', project=project, title='Questions') assert repr(questionnaire) == ('<Questionnaire id=abc123 ' 'title=Questions project=prj>')
def setup_models(self): self.prj = ProjectFactory.create() self.party = PartyFactory.create(project=self.prj) self.resource = ResourceFactory.create(content_object=self.party, project=self.prj) self.user = UserFactory.create() assign_policies(self.user)
def setup_models(self): self.user = UserFactory.create() assign_policies(self.user) self.org = OrganizationFactory.create() self.prj = ProjectFactory.create( organization=self.org, add_users=[self.user]) self.party = PartyFactory.create(name="Test Party", project=self.prj)
def test_login_redirect_to_original_referer(self): user = UserFactory.create() project = ProjectFactory.create() view = LocationsAdd.as_view() request = HttpRequest() referer = '/organizations/{}/projects/{}'.format( project.organization.slug, project.slug ) request.META['HTTP_REFERER'] = referer setattr(request, 'user', user) setattr(request, 'method', 'GET') setattr(request, 'session', 'session') self.messages = FallbackStorage(request) setattr(request, '_messages', self.messages) kwargs = { 'organization': project.organization.slug, 'project': project.slug } response = view(request, **kwargs) assert response.status_code == 302 assert referer == response['location']
def test_get_schema_attrs(self): project = ProjectFactory.create(current_questionnaire='123abc') content_type = ContentType.objects.get(app_label='spatial', model='spatialunit') schema = Schema.objects.create( content_type=content_type, selectors=(project.organization.id, project.id, '123abc', )) text_type = AttributeType.objects.get(name='text') select_m_type = AttributeType.objects.get(name='select_multiple') Attribute.objects.create( schema=schema, name='key', long_name='Test field', attr_type=text_type, index=0, required=False, omit=False ) Attribute.objects.create( schema=schema, name='key_2', long_name='Test field', attr_type=text_type, index=1, required=False, omit=True ) Attribute.objects.create( schema=schema, name='key_3', long_name='Test select multiple field', attr_type=select_m_type, index=2, choices=['choice_1', 'choice_2', 'choice_3'], choice_labels=['Choice 1', 'Choice 2', 'Choice 3'], required=False, omit=False ) exporter = Exporter(project) attrs = exporter.get_schema_attrs(content_type) assert len(attrs['DEFAULT']) == 2
def test_invalid_deserialize_json(self): data = { 'id_string': 'yx8sqx6488wbc4yysnkrbnfq', 'questions': [{ 'name': "start", 'label': 'Label', 'type': "ST", 'required': False, 'constraint': None }, { 'name': "end", 'label': 'Label', 'type': "EN", }] } project = ProjectFactory.create() serializer = serializers.QuestionnaireSerializer( data=data, context={'project': project} ) assert serializer.is_valid() is False assert serializer.errors == {'title': ['This field is required.']} with pytest.raises(ValidationError): assert serializer.is_valid(raise_exception=True)
def setup_models(self): self.prj = ProjectFactory.create() self.su = SpatialUnitFactory.create(project=self.prj) self.resource = ResourceFactory.create(content_object=self.su, project=self.prj) self.user = UserFactory.create() assign_policies(self.user)
def setup_models(self): clauses = { 'clause': [ { 'effect': 'allow', 'object': ['project/*/*', 'spatial/*/*/*', 'spatial_rel/*/*/*', 'party/*/*/*', 'party_rel/*/*/*', 'tenure_rel/*/*/*'], 'action': ['project.*', 'project.*.*', 'spatial.*', 'spatial_rel.*', 'party.*', 'party_rel.*', 'tenure_rel.*'] } ] } policy = Policy.objects.create( name='basic-test', body=json.dumps(clauses)) self.user = UserFactory.create() self.user.assign_policies(policy) self.prj = ProjectFactory.create(slug='test-project', access='public') self.SR = spatial_factories.SpatialRelationshipFactory self.PR = party_factories.PartyRelationshipFactory self.TR = party_factories.TenureRelationshipFactory
def test_get_schema_attrs(self): project = ProjectFactory.create(current_questionnaire="123abc") content_type = ContentType.objects.get(app_label="spatial", model="spatialunit") schema = Schema.objects.create( content_type=content_type, selectors=(project.organization.id, project.id, "123abc") ) text_type = AttributeType.objects.get(name="text") select_m_type = AttributeType.objects.get(name="select_multiple") Attribute.objects.create( schema=schema, name="key", long_name="Test field", attr_type=text_type, index=0, required=False, omit=False ) Attribute.objects.create( schema=schema, name="key_2", long_name="Test field", attr_type=text_type, index=1, required=False, omit=True ) Attribute.objects.create( schema=schema, name="key_3", long_name="Test select multiple field", attr_type=select_m_type, index=2, choices=["choice_1", "choice_2", "choice_3"], choice_labels=["Choice 1", "Choice 2", "Choice 3"], required=False, omit=False, ) exporter = Exporter(project) attrs = exporter.get_schema_attrs(content_type) assert len(attrs) == 2
def setUp(self): super().setUp() # Create a floating resource self.user = UserFactory.build( full_name='John Lennon', username='******' ) self.last_updated = datetime.now() self.resource = ResourceFactory.build( name='Resource Name', file='https://example.com/file.txt', original_file='original_file.jpg', mime_type='image/png', contributor=self.user, last_updated=self.last_updated, ) # Attach it to a project project = ProjectFactory.create() ContentObject.objects.create( resource=self.resource, content_type=ContentType.objects.get_for_model(project), object_id=project.id, )
def _test_serialize(self, https=False): form = self._get_form('xls-form') self.url = '/collect/' user = UserFactory.create() request = APIRequestFactory().get(self.url) force_authenticate(request, user=user) if https: request.META['SERVER_PROTOCOL'] = 'HTTPS/1.1' project = ProjectFactory.create() questionnaire = QuestionnaireSerializer( data={'xls_form': form}, context={'project': project} ) assert questionnaire.is_valid(raise_exception=True) is True questionnaire.save() form = Questionnaire.objects.get(filename__contains='xls-form') serializer = serializers.XFormListSerializer( form, context={'request': request}) url_refix = 'https' if https else 'http' assert serializer.data['formID'] == questionnaire.data['id_string'] assert serializer.data['name'] == questionnaire.data['title'] assert serializer.data['version'] == questionnaire.data['version'] assert (serializer.data['downloadUrl'] == url_refix + '://testserver' + reverse('form-download', args=[form.id])) assert serializer.data['hash'] == questionnaire.data['md5_hash']
def test_login_redirect_from_project_dashboard_to_org_dashboard(self): user = UserFactory.create() assign_user_policies(user, *[]) project = ProjectFactory.create() view = org_views.ProjectDashboard.as_view() request = HttpRequest() request.META['HTTP_REFERER'] = '/account/login/' setattr(request, 'user', user) setattr(request, 'method', 'GET') setattr(request, 'session', 'session') self.messages = FallbackStorage(request) setattr(request, '_messages', self.messages) kwargs = { 'organization': project.organization.slug, 'project': project.slug } def get_full_path(): return '/organizations/{}/projects/{}/'.format( project.organization.slug, project.slug ) setattr(request, 'get_full_path', get_full_path) exp_redirect = reverse('organization:dashboard', kwargs={ 'slug': project.organization.slug}) response = view(request, **kwargs) assert response.status_code == 302 assert exp_redirect == response['location']
def setup_models(self): self.user = UserFactory.create() self.project = ProjectFactory.create() self.resource = ResourceFactory.create(content_object=self.project, project=self.project, archived=True) assign_permissions(self.user)
def setup_models(self): self.user = UserFactory.create() self.org = OrganizationFactory.create() self.prj = ProjectFactory.create(organization=self.org) OrganizationRole.objects.create( organization=self.org, user=self.user, admin=True)
def setup_models(self): self.project = ProjectFactory.create() self.relationship = TenureRelationshipFactory.create( project=self.project) self.attached = ResourceFactory.create( project=self.project, content_object=self.relationship) self.unattached = ResourceFactory.create(project=self.project)
def test_deserialize_json(self): data = { 'title': 'yx8sqx6488wbc4yysnkrbnfq', 'id_string': 'yx8sqx6488wbc4yysnkrbnfq', 'questions': [{ 'name': "start", 'label': 'Label', 'type': "ST", 'required': False, 'constraint': None }, { 'name': "end", 'label': 'Label', 'type': "EN", }] } project = ProjectFactory.create() serializer = serializers.QuestionnaireSerializer( data=data, context={'project': project} ) serializer.is_valid(raise_exception=True) serializer.save() assert Questionnaire.objects.count() == 1 questionnaire = Questionnaire.objects.first() assert project.current_questionnaire == questionnaire.id assert questionnaire.questions.count() == 2
def test_create_party_with_attributes(self): data = {"name": "Cadasta", "type": "IN", "attributes::fname": "test"} project = ProjectFactory.create() content_type = ContentType.objects.get(app_label="party", model="party") schema = Schema.objects.create(content_type=content_type, selectors=(project.organization.id, project.id)) Attribute.objects.create( schema=schema, name="fname", long_name="Test field", attr_type=AttributeType.objects.get(name="text"), index=0, ) form = forms.PartyForm( project_id=project.id, data=data, schema_selectors=( {"name": "organization", "value": project.organization, "selector": project.organization.id}, {"name": "project", "value": project, "selector": project.id}, ), ) form.is_valid() form.save() assert Party.objects.filter(project=project).count() == 1 party = Party.objects.filter(project=project).first() assert party.attributes.get("fname") == "test"
def test_deserialize(self): form = self.get_form('xls-form') project = ProjectFactory.create() serializer = serializers.QuestionnaireSerializer( data={'xls_form': form}, context={'project': project} ) assert serializer.is_valid(raise_exception=True) is True serializer.save() assert Questionnaire.objects.count() == 1 questionnaire = Questionnaire.objects.first() assert questionnaire.id_string == 'question_types' assert questionnaire.filename == 'xls-form' assert questionnaire.title == 'Question types' assert serializer.data['id'] == questionnaire.id assert serializer.data['filename'] == questionnaire.filename assert serializer.data['title'] == questionnaire.title assert serializer.data['id_string'] == questionnaire.id_string assert serializer.data['xls_form'] == questionnaire.xls_form.url assert serializer.data['version'] == questionnaire.version assert len(serializer.data['questions']) == 1
def test_party_attribute_schema(self): project = ProjectFactory.create(name='TestProject') QuestionnaireFactory.create(project=project) content_type = ContentType.objects.get( app_label='party', model='party') create_attrs_schema( project=project, dict=individual_party_xform_group, content_type=content_type, errors=[]) party = PartyFactory.create( name='TestParty', project=project, type='IN', attributes={ 'homeowner': 'yes', 'dob': '1980-01-01' } ) assert 1 == Schema.objects.all().count() schema = Schema.objects.get(content_type=content_type) assert schema is not None assert schema.selectors == [ project.organization.pk, project.pk, project.current_questionnaire, party.type] assert 'homeowner' in party.attributes.attributes assert 'dob' in party.attributes.attributes assert 'gender' in party.attributes.attributes assert 3 == Attribute.objects.filter(schema=schema).count() assert party.attributes['homeowner'] == 'yes' assert party.attributes['dob'] == '1980-01-01'
def setup_models(self, access='public'): self.user = UserFactory.create() assign_policies(self.user) self.prj = ProjectFactory.create(slug='test-project', access='public') self.su1 = SpatialUnitFactory.create(project=self.prj, type='AP') self.su2 = SpatialUnitFactory.create(project=self.prj, type='BU')
def test_get_values(self): project = ProjectFactory.create(current_questionnaire="123abc") exporter = Exporter(project) content_type = ContentType.objects.get(app_label="party", model="tenurerelationship") schema = Schema.objects.create( content_type=content_type, selectors=(project.organization.id, project.id, "123abc") ) text_type = AttributeType.objects.get(name="text") select_m_type = AttributeType.objects.get(name="select_multiple") attr = Attribute.objects.create( schema=schema, name="key", long_name="Test field", attr_type=text_type, index=0, required=False, omit=False ) attr2 = Attribute.objects.create( schema=schema, name="key_2", long_name="Test select multiple field", attr_type=select_m_type, index=1, choices=["choice_1", "choice_2", "choice_3"], choice_labels=["Choice 1", "Choice 2", "Choice 3"], required=False, omit=False, ) ttype = TenureRelationshipType.objects.get(id="LH") item = TenureRelationshipFactory.create( project=project, tenure_type=ttype, attributes={"key": "text", "key_2": ["choice_1", "choice_2"]} ) model_attrs = ("id", "party_id", "spatial_unit_id", "tenure_type.label") schema_attrs = [attr, attr2] values = exporter.get_values(item, model_attrs, schema_attrs) assert values == [item.id, item.party_id, item.spatial_unit_id, "Leasehold", "text", "choice_1, choice_2"]
def setup_models(self): self.project = ProjectFactory.create() self.org_slug = self.project.organization.slug self.resource = ResourceFactory.create(project=self.project) self.location = SpatialUnitFactory.create(project=self.project) self.party = PartyFactory.create(project=self.project) self.tenurerel = TenureRelationshipFactory.create(project=self.project) self.project_attachment = ContentObject.objects.create( resource_id=self.resource.id, content_object=self.project, ) self.location_attachment = ContentObject.objects.create( resource_id=self.resource.id, content_object=self.location, ) self.party_attachment = ContentObject.objects.create( resource_id=self.resource.id, content_object=self.party, ) self.tenurerel_attachment = ContentObject.objects.create( resource_id=self.resource.id, content_object=self.tenurerel, ) self.user = UserFactory.create() assign_permissions(self.user)
def test_save_new_party_with_attributes(self): project = ProjectFactory.create() questionnaire = QuestionnaireFactory.create(project=project) spatial_unit = SpatialUnitFactory.create(project=project) content_type = ContentType.objects.get( app_label='party', model='tenurerelationship') schema = Schema.objects.create( content_type=content_type, selectors=( project.organization.id, project.id, questionnaire.id, )) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create( schema=schema, name='r_name', long_name='Relationship field', attr_type=attr_type, index=0, required=False, omit=False ) content_type = ContentType.objects.get( app_label='party', model='party') schema_gr = Schema.objects.create( content_type=content_type, selectors=( project.organization.id, project.id, questionnaire.id, 'GR')) Attribute.objects.create( schema=schema_gr, name='p_gr_name', long_name='Party GR field', attr_type=attr_type, index=0, required=True, omit=False ) form = forms.TenureRelationshipForm( project=project, spatial_unit=spatial_unit, data={'new_entity': 'on', 'id': '', 'name': 'The Beatles', 'party::gr::p_gr_name': 'Party Group Name', 'party_type': 'GR', 'tenure_type': 'CU', 'tenurerelationship::default::r_name': 'Rel Name'}) assert form.is_valid() form.save() assert Party.objects.count() == 1 party = Party.objects.first() assert party.name == 'The Beatles' assert party.type == 'GR' assert party.attributes.get('p_gr_name') == 'Party Group Name' assert TenureRelationship.objects.count() == 1 rel = TenureRelationship.objects.first() assert rel.party == party assert rel.spatial_unit == spatial_unit assert rel.tenure_type_id == 'CU' assert rel.attributes.get('r_name') == 'Rel Name'
def test_pack_resource_data(self): project = ProjectFactory.create() exporter = ResourceExporter(project) res = ResourceFactory.create(project=project) loc = SpatialUnitFactory.create(project=project) loc2 = SpatialUnitFactory.create(project=project) par = PartyFactory.create(project=project) rel = TenureRelationshipFactory.create(project=project) ContentObject.objects.create(resource=res, content_object=loc) ContentObject.objects.create(resource=res, content_object=loc2) ContentObject.objects.create(resource=res, content_object=par) ContentObject.objects.create(resource=res, content_object=rel) packed = exporter.pack_resource_data(res) assert packed[0] == res.id assert packed[1] == res.name assert packed[2] == res.description assert packed[3] == res.original_file assert loc.id in packed[4] assert loc2.id in packed[4] assert par.id in packed[5] assert rel.id in packed[6]
def test_login_redirect_to_project_dashboard(self): user = UserFactory.create() project = ProjectFactory.create() view = LocationsAdd.as_view() request = HttpRequest() request.META['HTTP_REFERER'] = '/account/login/' setattr(request, 'user', user) setattr(request, 'method', 'GET') setattr(request, 'session', 'session') self.messages = FallbackStorage(request) setattr(request, '_messages', self.messages) kwargs = { 'organization': project.organization.slug, 'project': project.slug } exp_redirect = reverse('organization:project-dashboard', kwargs=kwargs) response = view(request, **kwargs) assert response.status_code == 302 assert exp_redirect == response['location']
def setup_models(self): clauses = { 'clause': [{ 'effect': 'allow', 'object': [ 'project/*/*', 'spatial/*/*/*', 'spatial_rel/*/*/*', 'party/*/*/*', 'party_rel/*/*/*', 'tenure_rel/*/*/*' ], 'action': [ 'project.*', 'project.*.*', 'spatial.*', 'spatial_rel.*', 'party.*', 'party_rel.*', 'tenure_rel.*' ] }] } policy = Policy.objects.create(name='basic-test', body=json.dumps(clauses)) self.user = UserFactory.create() self.user.assign_policies(policy) self.prj = ProjectFactory.create(slug='test-project', access='public') self.SR = spatial_factories.SpatialRelationshipFactory self.PR = party_factories.PartyRelationshipFactory self.TR = party_factories.TenureRelationshipFactory
def setUp(self): super().setUp() self.project = ProjectFactory.create() QuestionnaireFactory.create(project=self.project) content_type = ContentType.objects.get(app_label='spatial', model='spatialunit') create_attrs_schema( project=self.project, dict=attr_schemas.location_xform_group, content_type=content_type, ) content_type = ContentType.objects.get(app_label='party', model='party') create_attrs_schema( project=self.project, dict=attr_schemas.default_party_xform_group, content_type=content_type, ) create_attrs_schema( project=self.project, dict=attr_schemas.individual_party_xform_group, content_type=content_type, ) create_attrs_schema( project=self.project, dict=attr_schemas.group_party_attributes, content_type=content_type, ) content_type = ContentType.objects.get(app_label='party', model='tenurerelationship') create_attrs_schema( project=self.project, dict=attr_schemas.tenure_relationship_xform_group, content_type=content_type, )
def test_save_new_party(self): project = ProjectFactory.create() spatial_unit = SpatialUnitFactory.create(project=project) form = forms.TenureRelationshipForm(project=project, spatial_unit=spatial_unit, data={'new_entity': 'on', 'id': '', 'name': 'The Beatles', 'party_type': 'GR', 'tenure_type': 'CU'}) form.is_valid() form.save() assert Party.objects.count() == 1 party = Party.objects.first() assert party.name == 'The Beatles' assert party.type == 'GR' assert TenureRelationship.objects.count() == 1 rel = TenureRelationship.objects.first() assert rel.party == party assert rel.spatial_unit == spatial_unit assert rel.tenure_type_id == 'CU'
def test_deserialize(self): form = self.get_form('xls-form') project = ProjectFactory.create() serializer = serializers.QuestionnaireSerializer( data={'xls_form': form}, context={'project': project}) assert serializer.is_valid(raise_exception=True) is True serializer.save() assert Questionnaire.objects.count() == 1 questionnaire = Questionnaire.objects.first() assert questionnaire.id_string == 'question_types' assert questionnaire.filename == 'xls-form' assert questionnaire.title == 'Question types' assert serializer.data['id'] == questionnaire.id assert serializer.data['filename'] == questionnaire.filename assert serializer.data['title'] == questionnaire.title assert serializer.data['id_string'] == questionnaire.id_string assert serializer.data['xls_form'] == questionnaire.xls_form.url assert serializer.data['version'] == questionnaire.version assert len(serializer.data['questions']) == 1
def test_left_and_right_project_ids(self): with pytest.raises(exceptions.ProjectRelationshipError): project1 = ProjectFactory() project2 = ProjectFactory() PartyRelationshipFactory.create(party1__project=project1, party2__project=project2)
def setup_models(self): self.user = UserFactory.create() assign_policies(self.user) self.prj = ProjectFactory.create(slug='test-project', access='public') self.su = SpatialUnitFactory(project=self.prj, type='PA')
def test_project_relationship_invalid(self): with pytest.raises(exceptions.ProjectRelationshipError): project = ProjectFactory() PartyRelationshipFactory.create(party1__project=project)
def test_init(self): project = ProjectFactory.build() exporter = ResourceExporter(project) assert exporter.project == project
def test_left_and_right_project_ids(self): with pytest.raises(exceptions.ProjectRelationshipError): project = ProjectFactory() SpatialRelationshipFactory(su1__project=project)
def test_get_values_with_conditional_selector(self): project = ProjectFactory.create(current_questionnaire='123abc') exporter = Exporter(project) content_type = ContentType.objects.get(app_label='party', model='party') schema = Schema.objects.create(content_type=content_type, selectors=( project.organization.id, project.id, '123abc', )) schema_in = Schema.objects.create(content_type=content_type, selectors=(project.organization.id, project.id, '123abc', 'IN')) schema_gr = Schema.objects.create(content_type=content_type, selectors=(project.organization.id, project.id, '123abc', 'GR')) text_type = AttributeType.objects.get(name='text') select_m_type = AttributeType.objects.get(name='select_multiple') Attribute.objects.create(schema=schema, name='key', long_name='Test field', attr_type=text_type, index=0, required=False, omit=False) Attribute.objects.create( schema=schema_in, name='key_2', long_name='Test select multiple field', attr_type=select_m_type, index=1, choices=['choice_1', 'choice_2', 'choice_3'], choice_labels=['Choice 1', 'Choice 2', 'Choice 3'], required=False, omit=False) Attribute.objects.create(schema=schema_gr, name='gr_key', long_name='Test Group Field', attr_type=text_type, index=0, required=False, omit=False) # test individual attrs item = PartyFactory.create(project=project, name='Test Party', type='IN', attributes={ 'key': 'text', 'key_2': ['choice_1', 'choice_2'] }) model_attrs = ('id', 'name', 'type') schema_attrs = exporter.get_schema_attrs(content_type) values = exporter.get_values(item, model_attrs, schema_attrs) assert values == { 'id': item.id, 'name': item.name, 'type': item.type, 'key': 'text', 'key_2': 'choice_1, choice_2' } # test group attrs item = PartyFactory.create(project=project, name='Test Party', type='GR', attributes={ 'key': 'text', 'gr_key': 'Test Group Field' }) model_attrs = ('id', 'name', 'type') schema_attrs = exporter.get_schema_attrs(content_type) values = exporter.get_values(item, model_attrs, schema_attrs) assert values == { 'id': item.id, 'name': item.name, 'type': item.type, 'key': 'text', 'gr_key': 'Test Group Field' }
def test_write_features(self): ensure_dirs() project = ProjectFactory.create(current_questionnaire='123abc') exporter = ShapeExporter(project) content_type = ContentType.objects.get(app_label='spatial', model='spatialunit') schema = Schema.objects.create(content_type=content_type, selectors=( project.organization.id, project.id, '123abc', )) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create(schema=schema, name='geom_type', long_name='Test field', attr_type=attr_type, index=0, required=False, omit=False) su1 = SpatialUnitFactory.create(project=project, geometry='SRID=4326;POINT (30 10)', attributes={'geom_type': 'point'}) su2 = SpatialUnitFactory.create( project=project, geometry='SRID=4326;LINESTRING (30 10, 10 30, 40 40)', attributes={'geom_type': 'linestring'}) su3 = SpatialUnitFactory.create( project=project, geometry='SRID=4326;POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))', attributes={'geom_type': 'polygon'}) su4 = SpatialUnitFactory.create( project=project, geometry='SRID=4326;' 'MULTIPOINT ((10 40), (40 30), (20 20), (30 10))', attributes={'geom_type': 'multipoint'}) su5 = SpatialUnitFactory.create( project=project, geometry='SRID=4326;' 'MULTILINESTRING ((10 10, 20 20, 10 40),' '(40 40, 30 30, 40 20, 30 10))', attributes={'geom_type': 'multilinestring'}) su6 = SpatialUnitFactory.create( project=project, geometry='SRID=4326;' 'MULTIPOLYGON (((30 20, 45 40, 10 40, 30 20)),' '((15 5, 40 10, 10 20, 5 10, 15 5)))', attributes={'geom_type': 'multipolygon'}) dst_dir = os.path.join(settings.MEDIA_ROOT, 'temp/file4') ds = exporter.create_datasource(dst_dir) filename = os.path.join(dst_dir, 'locations.csv') layers = exporter.write_features(ds, filename) assert len(layers.keys()) == 6 for layer_name, layer in layers.items(): su = SpatialUnit.objects.get(attributes={'geom_type': layer_name}) geom = su.geometry feature = layer.GetNextFeature() assert geom.equals(GEOSGeometry(feature.geometry().ExportToWkt())) assert feature.GetFieldAsString('id') == su.id ds.Destroy() with open(filename) as csvfile: csvreader = csv.reader(csvfile) for i, row in enumerate(csvreader): if i == 0: assert row == ['id', 'type', 'geom_type'] if i == 1: assert row == [su1.id, su1.type, 'point'] if i == 2: assert row == [su2.id, su2.type, 'linestring'] if i == 3: assert row == [su3.id, su3.type, 'polygon'] if i == 4: assert row == [su4.id, su4.type, 'multipoint'] if i == 5: assert row == [su5.id, su5.type, 'multilinestring'] if i == 6: assert row == [su6.id, su6.type, 'multipolygon'] # remove this so other tests pass os.remove(filename)
def setup_models(self): self.project = ProjectFactory.create()
def setup_models(self): self.project = ProjectFactory.create() self.location = SpatialUnitFactory.create(project=self.project) TenureRelationshipFactory.create(project=self.project, spatial_unit=self.location)
def setup_models(self): self.user = UserFactory.create() assign_policies(self.user) self.project = ProjectFactory.create(slug='test-project') QuestionnaireFactory.create(project=self.project) content_type = ContentType.objects.get(app_label='party', model='party') create_attrs_schema( project=self.project, dict=attr_schemas.individual_party_xform_group, content_type=content_type, ) create_attrs_schema( project=self.project, dict=attr_schemas.default_party_xform_group, content_type=content_type, ) content_type = ContentType.objects.get(app_label='party', model='tenurerelationship') create_attrs_schema( project=self.project, dict=attr_schemas.tenure_relationship_xform_group, content_type=content_type, ) self.su = SpatialUnitFactory.create(project=self.project, type='CB') self.party = PartyFactory.create(project=self.project, type='IN', attributes={ 'gender': 'm', 'homeowner': 'yes', 'dob': '1951-05-05' }) self.tenure_rel = TenureRelationshipFactory.create( spatial_unit=self.su, party=self.party, project=self.project, attributes={'notes': 'PBS is the best.'}) self.resource = ResourceFactory.create(project=self.project) self.results = get_fake_es_api_results(self.project, self.su, self.party, self.tenure_rel, self.resource) self.proj_result = self.results['hits']['hits'][0] self.su_result = self.results['hits']['hits'][1] self.party_result = self.results['hits']['hits'][2] self.tenure_rel_result = self.results['hits']['hits'][3] self.resource_result = self.results['hits']['hits'][4] self.query = 'searching' self.query_body = { 'query': parse_query(self.query), 'from': 10, 'size': 20, 'sort': { '_score': { 'order': 'desc' } }, } url = '{}/project-{}/spatial,party,resource/_search/' self.es_endpoint = url.format(api_url, self.project.id) self.es_body = json.dumps(self.query_body, sort_keys=True)
def setup_models(self): self.user = UserFactory.create() assign_policies(self.user) self.org = OrganizationFactory.create() self.prj = ProjectFactory.create( organization=self.org, add_users=[self.user])
def test_init(self): project = ProjectFactory.create() spatial_unit = SpatialUnitFactory.create(project=project) form = forms.TenureRelationshipForm(project=project, spatial_unit=spatial_unit) content_type = ContentType.objects.get( app_label='party', model='tenurerelationship') schema = Schema.objects.create( content_type=content_type, selectors=(project.organization.id, project.id, )) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create( schema=schema, name='r_name', long_name='Relationship field', attr_type=attr_type, index=0, required=False, omit=False ) content_type = ContentType.objects.get( app_label='party', model='party') schema = Schema.objects.create( content_type=content_type, selectors=(project.organization.id, project.id, )) Attribute.objects.create( schema=schema, name='p_name', long_name='Party field', attr_type=AttributeType.objects.get(name='text'), index=0, required=True, default='John' ) Attribute.objects.create( schema=schema, name='p_choice1', long_name='Party field', attr_type=AttributeType.objects.get(name='select_one'), index=1, choices=['1', '2'] ) Attribute.objects.create( schema=schema, name='p_choice2', long_name='Party field', attr_type=AttributeType.objects.get(name='select_one'), index=2, choices=['1', '2'], choice_labels=['Choice 1', 'Choice 2'] ) Attribute.objects.create( schema=schema, name='p_bool', long_name='Party field', attr_type=AttributeType.objects.get(name='boolean'), index=3, default='False' ) form = forms.TenureRelationshipForm( data={'new_item': 'on'}, project=project, spatial_unit=spatial_unit, schema_selectors=( {'name': 'organization', 'value': project.organization, 'selector': project.organization.id}, {'name': 'project', 'value': project, 'selector': project.id} )) assert form.project == project assert form.spatial_unit == spatial_unit assert isinstance(form.fields['id'].widget, SelectPartyWidget) assert isinstance(form.fields['party::p_name'], CharField) assert form.fields['party::p_name'].initial == 'John' assert form.fields['party::p_name'].required is True assert isinstance(form.fields['party::p_choice1'], ChoiceField) assert isinstance(form.fields['party::p_choice2'], ChoiceField) assert isinstance(form.fields['party::p_bool'], BooleanField) assert form.fields['party::p_bool'].initial is False assert isinstance(form.fields['relationship::r_name'], CharField) assert isinstance(form.fields['tenure_type'], ChoiceField) assert form.fields['tenure_type'].choices == ( [('', _('Please select a relationship type'))] + sorted(list(TENURE_RELATIONSHIP_TYPES)) ) assert ("All Types" not in dict(form.fields['tenure_type'].choices).values())
def test_save_new_party_with_attributes(self): project = ProjectFactory.create() spatial_unit = SpatialUnitFactory.create(project=project) content_type = ContentType.objects.get( app_label='party', model='tenurerelationship') schema = Schema.objects.create( content_type=content_type, selectors=(project.organization.id, project.id, )) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create( schema=schema, name='r_name', long_name='Relationship field', attr_type=attr_type, index=0, required=False, omit=False ) content_type = ContentType.objects.get( app_label='party', model='party') schema = Schema.objects.create( content_type=content_type, selectors=(project.organization.id, project.id, )) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create( schema=schema, name='p_name', long_name='Party field', attr_type=attr_type, index=0, required=False, omit=False ) form = forms.TenureRelationshipForm( project=project, spatial_unit=spatial_unit, data={'new_entity': 'on', 'id': '', 'name': 'The Beatles', 'party::p_name': 'Party Name', 'party_type': 'GR', 'tenure_type': 'CU', 'relationship::r_name': 'Rel Name'}, schema_selectors=( {'name': 'organization', 'value': project.organization, 'selector': project.organization.id}, {'name': 'project', 'value': project, 'selector': project.id} )) form.is_valid() form.save() assert Party.objects.count() == 1 party = Party.objects.first() assert party.name == 'The Beatles' assert party.type == 'GR' assert party.attributes.get('p_name') == 'Party Name' assert TenureRelationship.objects.count() == 1 rel = TenureRelationship.objects.first() assert rel.party == party assert rel.spatial_unit == spatial_unit assert rel.tenure_type_id == 'CU' assert rel.attributes.get('r_name') == 'Rel Name'
def setUp(self): super().setUp() self.project = ProjectFactory(name='TestProject')
def test_project_relationship_invalid(self): with pytest.raises(exceptions.ProjectRelationshipError): project = ProjectFactory() TenureRelationshipFactory.create(party__project=project, spatial_unit__project=project)
def setup_models(self): self.project = ProjectFactory.create() self.locations = SpatialUnitFactory.create_batch(2, project=self.project) SpatialUnitFactory.create()
def test_left_and_right_project_ids(self): with pytest.raises(exceptions.ProjectRelationshipError): project = ProjectFactory() TenureRelationshipFactory.create(party__project=project)
def setup_models(self): self.project = ProjectFactory.create() self.location = SpatialUnitFactory.create(project=self.project) self.attached = ResourceFactory.create(project=self.project, content_object=self.location) self.unattached = ResourceFactory.create(project=self.project)
def test_get_schema_attrs_empty(self): project = ProjectFactory.create() content_type = ContentType.objects.get(app_label='spatial', model='spatialunit') exporter = Exporter(project) assert exporter.get_schema_attrs(content_type) == {}
def setup_models(self): self.project = ProjectFactory.create() self.location = SpatialUnitFactory.create(project=self.project)
def setUp(self): super().setUp() self.project = ProjectFactory.create(current_questionnaire='123abc') self.spatial_content_type = ContentType.objects.get( app_label='spatial', model='spatialunit') sp_schema = Schema.objects.create( content_type=self.spatial_content_type, selectors=( self.project.organization.id, self.project.id, '123abc', )) attr_type_text = AttributeType.objects.get(name='text') attr_type_int = AttributeType.objects.get(name='integer') attr_type_dec = AttributeType.objects.get(name='decimal') Attribute.objects.create(schema=sp_schema, name='key', long_name='Test field', attr_type=attr_type_text, index=0, required=False, omit=False) Attribute.objects.create(schema=sp_schema, name='integer', long_name='Test integer field', attr_type=attr_type_int, index=1, required=False, omit=False) Attribute.objects.create(schema=sp_schema, name='decimal', long_name='Test decimal field', attr_type=attr_type_dec, index=2, required=False, omit=False) self.spatialunit_1 = SpatialUnitFactory.create(project=self.project, geometry='POINT (1 1)', attributes={ 'key': 'value 1', 'integer': '1', 'decimal': '1.0' }) self.spatialunit_2 = SpatialUnitFactory.create(project=self.project, geometry='POINT (2 2)', attributes={ 'key': 'value 2', 'integer': '2', 'decimal': '2.0' }) self.spatialunits = [self.spatialunit_1, self.spatialunit_2] self.spatial_attrs = ['id', 'geometry.ewkt'] self.party_content_type = ContentType.objects.get(app_label='party', model='party') pt_schema = Schema.objects.create(content_type=self.party_content_type, selectors=( self.project.organization.id, self.project.id, '123abc', )) pt_schema_in = Schema.objects.create( content_type=self.party_content_type, selectors=(self.project.organization.id, self.project.id, '123abc', 'IN')) pt_schema_gr = Schema.objects.create( content_type=self.party_content_type, selectors=(self.project.organization.id, self.project.id, '123abc', 'GR')) attr_type = AttributeType.objects.get(name='text') Attribute.objects.create(schema=pt_schema, name='default_attr', long_name='Test field', attr_type=attr_type, index=0, required=False, omit=False) Attribute.objects.create(schema=pt_schema_in, name='party_in', long_name='Test IN field', attr_type=attr_type, index=0, required=False, omit=False) Attribute.objects.create(schema=pt_schema_gr, name='party_gr', long_name='Test GR field', attr_type=attr_type, index=0, required=False, omit=False) party_in = PartyFactory.create(project=self.project, type='IN', attributes={ 'default_attr': 'Test Schema', 'party_in': 'Test IN attribute' }) party_gr = PartyFactory.create(project=self.project, type='GR', attributes={ 'default_attr': 'Another Test Schema', 'party_gr': 'Test GR attribute' }) self.parties = [party_in, party_gr] TenureRelationshipFactory.create(project=self.project, party=self.parties[0], spatial_unit=self.spatialunit_1)
def setup_models(self): self.user = UserFactory.create() assign_policies(self.user) self.prj = ProjectFactory.create(slug='test-project', access='public')
def test_project_relationship_invalid(self): with pytest.raises(exceptions.ProjectRelationshipError): project = ProjectFactory() SpatialRelationshipFactory(su1__project=project, su2__project=project)
def test_init_without_questionnaire(self): project = ProjectFactory.create() form = forms.PartyForm(project) assert hasattr(form.fields['name'], 'labels_xlang') is False assert hasattr(form.fields['type'], 'labels_xlang') is False