def setUp(self):
     self.maxDiff = None
     user_details = {
         'username': '******',
         'password': '******',
     }
     self.user = User.objects.create_superuser(email='*****@*****.**',
                                               **user_details)
     self.org, _, _ = create_organization(self.user)
     self.assessment_factory = FakeGreenAssessmentFactory(
         organization=self.org)
     self.green_assessment = self.assessment_factory.get_green_assessment(
         name="Green Test Score",
         award_body="Green TS Inc",
         recognition_type=GreenAssessment.SCORE,
         validity_duration=(365 * 5))
     self.url_factory = FakeGreenAssessmentURLFactory()
     self.gap_factory = FakeGreenAssessmentPropertyFactory(
         organization=self.org, user=self.user)
     self.start_date = datetime.date.today() - datetime.timedelta(2 * 365)
     self.status_date = datetime.date.today() - datetime.timedelta(7)
     self.target_date = datetime.date.today() - datetime.timedelta(7)
     self.gap = self.gap_factory.get_green_assessment_property(
         assessment=self.green_assessment,
         organization=self.org,
         user=self.user,
         with_url=3,
         metric=5,
         date=self.start_date,
         status='Pending',
         source='Assessor',
         status_date=self.status_date,
         version='1',
         eligibility=True)
     self.urls = [url.url for url in self.gap.urls.all()]
 def setUp(self):
     self.maxDiff = None
     user_details = {
         'username': '******',
         'password': '******',
     }
     self.user = User.objects.create_superuser(email='*****@*****.**',
                                               **user_details)
     self.org, _, _ = create_organization(self.user)
     self.property_view_factory = FakePropertyViewFactory(
         organization=self.org, user=self.user)
     self.ga_factory = FakeGreenAssessmentFactory(organization=self.org)
     self.gap_factory = FakeGreenAssessmentPropertyFactory(
         organization=self.org, user=self.user)
     self.assessment = self.ga_factory.get_green_assessment()
     self.property_view = self.property_view_factory.get_property_view()
     self.data = {
         'source': 'test',
         'status': 'complete',
         'status_date': '2017-01-01',
         'metric': 5,
         'version': '0.1',
         'date': '2016-01-01',
         'eligibility': True,
         'assessment': self.assessment,
         'view': self.property_view,
     }
     self.urls = ['http://example.com', 'http://example.org']
 def setUp(self):
     self.maxDiff = None
     user_details = {
         'username': '******',
         'password': '******',
     }
     self.user = User.objects.create_superuser(email='*****@*****.**',
                                               **user_details)
     self.org = Organization.objects.create()
     OrganizationUser.objects.create(user=self.user, organization=self.org)
     self.audit_log_factory = FakePropertyAuditLogFactory(
         organization=self.org, user=self.user)
     self.property_factory = FakePropertyFactory(organization=self.org)
     self.property_state_factory = FakePropertyStateFactory(
         organization=self.org)
     self.property_view_factory = FakePropertyViewFactory(
         organization=self.org, user=self.user)
     self.ga_factory = FakeGreenAssessmentFactory(organization=self.org)
     self.gap_factory = FakeGreenAssessmentPropertyFactory(
         organization=self.org, user=self.user)
     self.label_factory = FakeStatusLabelFactory(organization=self.org)
     self.assessment = self.ga_factory.get_green_assessment()
     self.property_view = self.property_view_factory.get_property_view()
     self.gap_data = {
         'source': 'test',
         'status': 'complete',
         'status_date': datetime.date(2017, 0o1, 0o1),
         'metric': 5,
         'version': '0.1',
         'date': datetime.date(2016, 0o1, 0o1),
         'eligibility': True,
         'assessment': self.assessment,
         'view': self.property_view,
     }
     self.urls = ['http://example.com', 'http://example.org']
 def setUp(self):
     self.maxDiff = None
     user_details = {
         'username': '******',
         'password': '******',
     }
     self.user = User.objects.create_superuser(email='*****@*****.**',
                                               **user_details)
     self.org = Organization.objects.create()
     OrganizationUser.objects.create(user=self.user, organization=self.org)
     self.audit_log_factory = FakePropertyAuditLogFactory(
         organization=self.org, user=self.user)
     self.cycle_factory = FakeCycleFactory(organization=self.org,
                                           user=self.user)
     self.property_state_factory = FakePropertyStateFactory(
         organization=self.org)
     self.property_view_factory = FakePropertyViewFactory(
         organization=self.org, user=self.user)
     self.ga_factory = FakeGreenAssessmentFactory(organization=self.org)
     self.gap_factory = FakeGreenAssessmentPropertyFactory(
         organization=self.org, user=self.user)
     self.taxlot_property_factory = FakeTaxLotPropertyFactory(
         organization=self.org, user=self.user)
     self.taxlot_state_factory = FakeTaxLotStateFactory(
         organization=self.org)
     self.taxlot_view_factory = FakeTaxLotViewFactory(organization=self.org,
                                                      user=self.user)
     self.assessment = self.ga_factory.get_green_assessment()
     self.cycle = self.cycle_factory.get_cycle()
     self.property_state = self.property_state_factory.get_property_state()
     self.property_view = self.property_view_factory.get_property_view(
         state=self.property_state, cycle=self.cycle)
     self.taxlot_state = self.taxlot_state_factory.get_taxlot_state()
     self.taxlot_view = self.taxlot_view_factory.get_taxlot_view(
         state=self.taxlot_state, cycle=self.cycle)
     self.audit_log = self.audit_log_factory.get_property_audit_log(
         state=self.property_state,
         view=self.property_view,
         record_type=AUDIT_USER_EDIT,
         description=json.dumps(['a', 'b']))
     self.audit_log2 = self.audit_log_factory.get_property_audit_log(
         view=self.property_view)
     self.gap_data = {
         'source': 'test',
         'status': 'complete',
         'status_date': datetime.date(2017, 0o1, 0o1),
         'metric': 5,
         'version': '0.1',
         'date': datetime.date(2016, 0o1, 0o1),
         'eligibility': True,
         'assessment': self.assessment,
         'view': self.property_view,
     }
     self.urls = ['http://example.com', 'http://example.org']
     self.gap = self.gap_factory.get_green_assessment_property(
         **self.gap_data)
     self.serializer = PropertyViewAsStateSerializer(
         instance=self.property_view)
class GreenAssessmentTests(DeleteModelsTestCase):
    """Tests for certification/Green Assessment models and methods"""

    # pylint: disable=too-many-instance-attributes

    def setUp(self):
        self.maxDiff = None
        user_details = {
            'username': '******',
            'password': '******',
        }
        self.user = User.objects.create_superuser(email='*****@*****.**',
                                                  **user_details)
        self.org, _, _ = create_organization(self.user)
        self.assessment_factory = FakeGreenAssessmentFactory(
            organization=self.org)
        self.green_assessment = self.assessment_factory.get_green_assessment(
            name="Green Test Score",
            award_body="Green TS Inc",
            recognition_type=GreenAssessment.SCORE,
            validity_duration=(365 * 5))
        self.url_factory = FakeGreenAssessmentURLFactory()
        self.gap_factory = FakeGreenAssessmentPropertyFactory(
            organization=self.org, user=self.user)
        self.start_date = datetime.date.today() - datetime.timedelta(2 * 365)
        self.status_date = datetime.date.today() - datetime.timedelta(7)
        self.target_date = datetime.date.today() - datetime.timedelta(7)
        self.gap = self.gap_factory.get_green_assessment_property(
            assessment=self.green_assessment,
            organization=self.org,
            user=self.user,
            with_url=3,
            metric=5,
            date=self.start_date,
            status='Pending',
            source='Assessor',
            status_date=self.status_date,
            version='1',
            eligibility=True)
        self.urls = [url.url for url in self.gap.urls.all()]

    def test_unicode_magic_methods(self):
        """Test unicode repr methods"""
        expected = 'Green TS Inc, Green Test Score, Score'
        self.assertEqual(expected, str(self.green_assessment))

        expected = 'Green TS Inc, Green Test Score: 5'
        self.assertEqual(expected, str(self.gap))

    def test_gap_properties(self):
        """Test properties on GreenAssessmentProperty."""
        self.assertEqual('Green Test Score', self.gap.name)
        self.assertEqual('Green TS Inc', self.gap.body)
        self.assertEqual('SCR', self.gap.recognition_type)
        self.assertEqual('Score', self.gap.recognition_description)
        self.assertEqual(self.start_date.year, self.gap.year)
        self.assertEqual(self.green_assessment.organization,
                         self.gap.organization)

    def test_url_properties(self):
        """Test properties on GreenAssessmentURL."""
        url = self.url_factory.get_url(property_assessment=self.gap)
        expected = self.gap.organization
        organization = url.organization
        self.assertEqual(expected, organization)

    def test_score(self):
        """Test score/rating/metric properties"""
        # test score/metric
        self.assertEqual(5, self.gap.score)
        self.assertEqual(5, self.gap.metric)
        self.assertIsInstance(self.gap.metric, int)
        self.assertIsInstance(self.gap.score, int)
        self.green_assessment.is_integer_score = False
        self.assertIsInstance(self.gap.metric, float)
        self.assertIsInstance(self.gap.score, float)
        self.gap.score = 4
        self.assertEqual(4.0, self.gap.score)
        with self.assertRaises(ValidationError) as conm:
            self.gap.rating = '5 stars'
        exception = conm.exception
        self.assertEqual("['Green Test Score uses a metric (numeric score)']",
                         str(exception))
        self.gap.assessment.is_numeric_score = False
        self.gap.rating = '5 stars'
        self.assertEqual('5 stars', self.gap.rating)
        # must now return rating
        self.assertEqual('5 stars', self.gap.score)
        with self.assertRaises(ValidationError) as conm:
            self.gap.metric = 5
        exception = conm.exception
        self.assertEqual(
            "['Green Test Score uses a rating (non numeric score)']",
            str(exception))

    def test_expiration(self):
        """Test expiration_date and is_valid properties"""
        expected_date = self.start_date + datetime.timedelta(365 * 5)
        self.assertEqual(expected_date, self.gap.expiration_date)
        self.assertTrue(self.gap.is_valid)

        # test setting/retrieving _expiration_date
        new_expiration = datetime.date.today() + datetime.timedelta(5 * 365)
        self.gap.expiration_date = new_expiration
        self.assertEqual(new_expiration, self.gap.expiration_date)
        self.assertTrue(self.gap.is_valid)

        # test past expiration date
        new_expiration = datetime.date.today() - datetime.timedelta(365)
        self.gap.expiration_date = new_expiration
        self.assertFalse(self.gap.is_valid)

    def test_to_bedes(self):
        """Test to_bedes_dict method."""
        expected = {
            'Assessment Program': 'Green Test Score',
            'Assessment Program Organization': 'Green TS Inc',
            'Assessment Recognition Type': 'Score',
            'Assessment Recognition Status': 'Pending',
            'Assessment Recognition Status Date': self.status_date,
            'Assessment Recognition Target Date': None,
            'Assessment Value': 5,
            'Assessment Version': '1',
            'Assessment Year': self.start_date.year,
            'Assessment Eligibility': True,
            'Assessment Level': None,
            'Assessment Program URL': self.urls,
        }
        self.assertDictEqual(expected, self.gap.to_bedes_dict())

    def test_to_reso(self):
        """Test to_reso_dict method."""
        expected = {
            'GreenBuildingVerificationType': 'Green Test Score',
            'GreenVerificationBody': 'Green TS Inc',
            'GreenVerificationDate': self.start_date,
            'GreenVerificationSource': 'Assessor',
            'GreenVerificationStatus': 'Pending',
            'GreenVerificationMetric': 5,
            'GreenVerificationRating': None,
            'GreenVerificationVersion': '1',
            'GreenVerificationYear': self.start_date.year,
            'GreenVerificationURL': self.urls,
        }
        self.assertDictEqual(expected, self.gap.to_reso_dict())

    def test_to_reso_sub_name(self):
        """Test to_reso_dict method with substitution."""
        expected = {
            'GreenBuildingVerificationType': 'Green Test Score',
            'GreenVerificationGreenTestScoreBody': 'Green TS Inc',
            'GreenVerificationGreenTestScoreDate': self.start_date,
            'GreenVerificationGreenTestScoreSource': 'Assessor',
            'GreenVerificationGreenTestScoreStatus': 'Pending',
            'GreenVerificationGreenTestScoreMetric': 5,
            'GreenVerificationGreenTestScoreRating': None,
            'GreenVerificationGreenTestScoreVersion': '1',
            'GreenVerificationGreenTestScoreYear': self.start_date.year,
            'GreenVerificationGreenTestScoreURL': self.urls,
        }
        self.assertDictEqual(expected, self.gap.to_reso_dict(sub_name=True))
class TestGreenAssessmentPropertySerializer(DeleteModelsTestCase):
    def setUp(self):
        self.maxDiff = None
        user_details = {
            'username': '******',
            'password': '******',
        }
        self.user = User.objects.create_superuser(email='*****@*****.**',
                                                  **user_details)
        self.org, _, _ = create_organization(self.user)
        self.property_view_factory = FakePropertyViewFactory(
            organization=self.org, user=self.user)
        self.ga_factory = FakeGreenAssessmentFactory(organization=self.org)
        self.gap_factory = FakeGreenAssessmentPropertyFactory(
            organization=self.org, user=self.user)
        self.assessment = self.ga_factory.get_green_assessment()
        self.property_view = self.property_view_factory.get_property_view()
        self.data = {
            'source': 'test',
            'status': 'complete',
            'status_date': '2017-01-01',
            'metric': 5,
            'version': '0.1',
            'date': '2016-01-01',
            'eligibility': True,
            'assessment': self.assessment,
            'view': self.property_view,
        }
        self.urls = ['http://example.com', 'http://example.org']

    @mock.patch('seed.serializers.certification.GreenAssessmentURL')
    def test_create(self, mock_url_model):
        """Test (overridden) create method."""
        serializer = GreenAssessmentPropertySerializer()
        data = self.data.copy()
        data['urls'] = self.urls
        instance = serializer.create(data)
        mock_url_model.objects.bulk_create.assert_called_with([
            mock_url_model(property_assessment=instance,
                           url=url[0],
                           description=url[1]) for url in self.urls
        ])

    @mock.patch('seed.serializers.certification.GreenAssessmentURL')
    def test_update(self, mock_url_model):
        """Test (overridden) update method."""
        data = self.data.copy()
        data['urls'] = self.urls[:1]
        gap = self.gap_factory.get_green_assessment_property(**data)
        serializer = GreenAssessmentPropertySerializer()
        data['urls'] = self.urls[1:]
        instance = serializer.update(gap, data)
        mock_url_model.objects.filter.assert_called_with(
            property_assessment=instance)
        mock_url_model.assert_called_with(url='http://example.org',
                                          property_assessment=gap)

    def test_validate(self):
        """Test (overriden) validate method"""
        serializer = GreenAssessmentPropertySerializer()
        # add context
        mock_request = mock.MagicMock()
        mock_request.user = self.user
        serializer.context = {'request': mock_request}

        # assert raises error if rating and metric supplied
        data = self.data.copy()
        data['rating'] = 'Gold Star'
        with self.assertRaises(ValidationError) as conm:
            serializer.validate(data)
        exception = conm.exception
        expected = "['Only one of metric or rating can be supplied.']"
        self.assertEqual(expected, str(exception))

        # assert raises error if metric is expected
        del data['metric']
        data['rating'] = '5'
        with self.assertRaises(ValidationError) as conm:
            serializer.validate(data)
        exception = conm.exception
        expected = "['{} uses a metric (numeric score).']".format(
            self.assessment.name)
        self.assertEqual(expected, str(exception))

        # assert raises error if metric is of wrong type
        del data['rating']
        data['metric'] = '5 stars'
        with self.assertRaises(ValidationError) as conm:
            serializer.validate(data)
        exception = conm.exception
        expected = "['Metric must be a number.']"
        self.assertEqual(expected, str(exception))

        # assert raises error if rating expected
        self.assessment.is_numeric_score = False
        data['metric'] = 5
        with self.assertRaises(ValidationError) as conm:
            serializer.validate(data)
        exception = conm.exception
        expected = "['{} uses a rating (non-numeric score).']".format(
            self.assessment.name)

        # assert raises error if rating is of wrong type
        del data['metric']
        data['rating'] = 5
        with self.assertRaises(ValidationError) as conm:
            serializer.validate(data)
        exception = conm.exception
        expected = "['Rating must be a string.']"
        self.assertEqual(expected, str(exception))

        # assert converts ints to floats
        self.assessment.is_numeric_score = True
        del data['rating']
        data['metric'] = 5
        result = serializer.validate(data)
        self.assertEqual(result, data)

        # assert raises error if integer expected
        data['metric'] = 3.5
        with self.assertRaises(ValidationError) as conm:
            serializer.validate(data)
        exception = conm.exception
        expected = "['Metric must be an integer.']"
        self.assertEqual(expected, str(exception))

        # assert raises error if assessment missing
        del data['assessment']
        with self.assertRaises(ValidationError) as conm:
            serializer.validate(data)
        exception = conm.exception
        expected = "['Could not find assessment.']"
        self.assertEqual(expected, str(exception))
Beispiel #7
0
class TestPropertySerializers(DeleteModelsTestCase):
    def setUp(self):
        self.maxDiff = None
        user_details = {
            'username': '******',
            'password': '******',
        }
        self.user = User.objects.create_superuser(email='*****@*****.**',
                                                  **user_details)
        self.org, _, _ = create_organization(self.user)
        self.audit_log_factory = FakePropertyAuditLogFactory(
            organization=self.org, user=self.user)
        self.property_factory = FakePropertyFactory(organization=self.org)
        self.property_state_factory = FakePropertyStateFactory(
            organization=self.org)
        self.property_view_factory = FakePropertyViewFactory(
            organization=self.org, user=self.user)
        self.ga_factory = FakeGreenAssessmentFactory(organization=self.org)
        self.gap_factory = FakeGreenAssessmentPropertyFactory(
            organization=self.org, user=self.user)
        self.label_factory = FakeStatusLabelFactory(organization=self.org)
        self.assessment = self.ga_factory.get_green_assessment()
        self.property_view = self.property_view_factory.get_property_view()
        self.gap_data = {
            'source': 'test',
            'status': 'complete',
            'status_date': datetime.date(2017, 0o1, 0o1),
            'metric': 5,
            'version': '0.1',
            'date': datetime.date(2016, 0o1, 0o1),
            'eligibility': True,
            'assessment': self.assessment,
            'view': self.property_view,
        }
        self.urls = ['http://example.com', 'http://example.org']

    def test_audit_log_serializer(self):
        """Test to_representation method."""

        # test with AUDIT_USER_CREATE
        audit_log = self.audit_log_factory.get_property_audit_log()
        result = PropertyAuditLogReadOnlySerializer(audit_log).data
        self.assertEqual(result['description'], 'test audit log')
        self.assertEqual(result['date_edited'], audit_log.created.ctime())
        self.assertEqual(result['source'], 'UserCreate')
        self.assertIsNone(result['changed_fields'])
        self.assertEqual(result['state']['city'], 'Boring')

        # test with AUDIT_USER_EDIT
        changed_fields = ['a', 'b', 'c']
        audit_log = self.audit_log_factory.get_property_audit_log(
            record_type=AUDIT_USER_EDIT,
            description=json.dumps(changed_fields))
        result = PropertyAuditLogReadOnlySerializer(audit_log).data
        self.assertEqual(result['description'], 'User edit')
        self.assertEqual(result['source'], 'UserEdit')
        self.assertEqual(result['changed_fields'], changed_fields)

    def test_property_view_list_serializer(self):
        """Test to_representation method."""
        property_view_1 = self.property_view_factory.get_property_view()
        property_view_2 = self.property_view_factory.get_property_view()
        gap1_data = self.gap_data.copy()
        gap2_data = self.gap_data.copy()
        gap1_data['view'] = property_view_1
        gap2_data['view'] = property_view_2
        gap2_data['metric'] = 4
        self.gap_factory.get_green_assessment_property(**gap1_data)
        self.gap_factory.get_green_assessment_property(**gap2_data)
        serializer = PropertyViewListSerializer(child=PropertyViewSerializer())
        result = serializer.to_representation(
            [property_view_1, property_view_2])
        self.assertEqual(result[0]['cycle']['id'], property_view_1.cycle_id)
        self.assertEqual(result[1]['cycle']['id'], property_view_2.cycle_id)
        self.assertEqual(result[0]['state']['id'], property_view_1.state_id)
        self.assertEqual(result[1]['state']['id'], property_view_2.state_id)
        self.assertEqual(result[0]['certifications'][0]['score'], 5)
        self.assertEqual(result[1]['certifications'][0]['score'], 4)
        self.assertEqual(result[0]['certifications'][0]['assessment']['name'],
                         self.assessment.name)
        self.assertEqual(result[1]['certifications'][0]['assessment']['name'],
                         self.assessment.name)

        # with queryset
        serializer = PropertyViewListSerializer(child=PropertyViewSerializer())
        queryset = PropertyView.objects.filter(
            id__in=[property_view_1.id, property_view_2.id]).order_by('id')
        result = serializer.to_representation(queryset)
        self.assertEqual(result[0]['cycle']['id'], property_view_1.cycle_id)
        self.assertEqual(result[1]['cycle']['id'], property_view_2.cycle_id)
        self.assertEqual(result[0]['state']['id'], property_view_1.state_id)
        self.assertEqual(result[1]['state']['id'], property_view_2.state_id)
        self.assertEqual(result[0]['certifications'][0]['score'], 5)
        self.assertEqual(result[1]['certifications'][0]['score'], 4)
        self.assertEqual(result[0]['certifications'][0]['assessment']['name'],
                         self.assessment.name)
        self.assertEqual(result[1]['certifications'][0]['assessment']['name'],
                         self.assessment.name)

    def test_property_list_serializer(self):
        """Test PropertyListSerializer.to_representation"""
        # TODO test to representation
        property1 = self.property_factory.get_property()
        property2 = self.property_factory.get_property()

        expected = [
            OrderedDict([
                ('id', property1.id),
                ('campus', False),
                ('parent_property', None),
            ]),
            OrderedDict([
                ('id', property2.id),
                ('campus', False),
                ('parent_property', None),
            ]),
        ]

        serializer = PropertyListSerializer(child=PropertyMinimalSerializer())
        result = serializer.to_representation([property1, property2])
        self.assertEqual(expected, result)
Beispiel #8
0
class TestPropertyViewAsStateSerializers(DeleteModelsTestCase):
    def setUp(self):
        self.maxDiff = None
        user_details = {
            'username': '******',
            'password': '******',
        }
        self.user = User.objects.create_superuser(email='*****@*****.**',
                                                  **user_details)
        self.org, _, _ = create_organization(self.user)
        self.audit_log_factory = FakePropertyAuditLogFactory(
            organization=self.org, user=self.user)
        self.cycle_factory = FakeCycleFactory(organization=self.org,
                                              user=self.user)
        self.property_state_factory = FakePropertyStateFactory(
            organization=self.org)
        self.property_view_factory = FakePropertyViewFactory(
            organization=self.org, user=self.user)
        self.ga_factory = FakeGreenAssessmentFactory(organization=self.org)
        self.gap_factory = FakeGreenAssessmentPropertyFactory(
            organization=self.org, user=self.user)
        self.taxlot_property_factory = FakeTaxLotPropertyFactory(
            organization=self.org, user=self.user)
        self.taxlot_state_factory = FakeTaxLotStateFactory(
            organization=self.org)
        self.taxlot_view_factory = FakeTaxLotViewFactory(organization=self.org,
                                                         user=self.user)
        self.assessment = self.ga_factory.get_green_assessment()
        self.cycle = self.cycle_factory.get_cycle()
        self.property_state = self.property_state_factory.get_property_state()
        self.property_view = self.property_view_factory.get_property_view(
            state=self.property_state, cycle=self.cycle)
        self.taxlot_state = self.taxlot_state_factory.get_taxlot_state()
        self.taxlot_view = self.taxlot_view_factory.get_taxlot_view(
            state=self.taxlot_state, cycle=self.cycle)
        self.audit_log = self.audit_log_factory.get_property_audit_log(
            state=self.property_state,
            view=self.property_view,
            record_type=AUDIT_USER_EDIT,
            description=json.dumps(['a', 'b']))
        self.audit_log2 = self.audit_log_factory.get_property_audit_log(
            view=self.property_view)
        self.gap_data = {
            'source': 'test',
            'status': 'complete',
            'status_date': datetime.date(2017, 0o1, 0o1),
            'metric': 5,
            'version': '0.1',
            'date': datetime.date(2016, 0o1, 0o1),
            'eligibility': True,
            'assessment': self.assessment,
            'view': self.property_view,
        }
        self.urls = ['http://example.com', 'http://example.org']
        self.gap = self.gap_factory.get_green_assessment_property(
            **self.gap_data)
        self.serializer = PropertyViewAsStateSerializer(
            instance=self.property_view)

    def test_init(self):
        """Test __init__."""
        expected = PropertyAuditLogReadOnlySerializer(self.audit_log).data

        # for now convert the site_eui to a magnitude to get the test to pass
        # this really needs to be at another level
        data = self.serializer.current
        # data['state']['site_eui'] = data['state']['site_eui'].magnitude
        self.assertEqual(data, expected)

    def test_get_certifications(self):
        """Test get_certifications"""
        expected = [GreenAssessmentPropertyReadOnlySerializer(self.gap).data]
        self.assertEqual(
            self.serializer.get_certifications(self.property_view), expected)

    def test_get_changed_fields(self):
        """Test get_changed_fields"""
        expected = ['a', 'b']
        self.assertEqual(self.serializer.get_changed_fields(None), expected)

    def test_get_date_edited(self):
        """Test get_date_edited"""
        expected = self.audit_log.created.ctime()
        self.assertEqual(self.serializer.get_date_edited(None), expected)

    def test_get_filename(self):
        """Test get_filename"""
        expected = self.audit_log.import_filename
        self.assertEqual(self.serializer.get_filename(None), expected)

    def test_get_history(self):
        """Test get_history"""
        obj = mock.MagicMock()
        obj.state = self.property_state

        data = self.serializer.get_history(obj)
        # Really need to figure out how to get the serializer to save the magnitude correctly.
        # data[0]['state']['site_eui'] = data[0]['state']['site_eui'].magnitude

        expected = [PropertyAuditLogReadOnlySerializer(self.audit_log2).data]
        self.assertEqual(data, expected)

    def test_get_state(self):
        obj = mock.MagicMock()
        obj.state = self.property_state

    def test_get_source(self):
        """Test get_source"""
        expected = self.audit_log.get_record_type_display()
        self.assertEqual(self.serializer.get_source(None), expected)

    def test_get_taxlots(self):
        """Test get_taxlots"""
        self.taxlot_property_factory.get_taxlot_property(
            cycle=self.cycle,
            property_view=self.property_view,
            taxlot_view=self.taxlot_view)
        result = self.serializer.get_taxlots(self.property_view)
        self.assertEqual(result[0]['state']['id'], self.taxlot_state.id)

    @mock.patch('seed.serializers.properties.PropertyView')
    @mock.patch('seed.serializers.properties.PropertyStateWritableSerializer')
    def test_create(self, mock_serializer, mock_pview):
        """Test create"""
        mock_serializer.return_value.is_valid.return_value = True
        mock_serializer.return_value.save.return_value = self.property_state
        mock_pview.objects.create.return_value = self.property_view
        data = {'org_id': 1, 'cycle': 2, 'state': {'test': 3}, 'property': 4}

        serializer = PropertyViewAsStateSerializer()
        serializer.create(data)
        mock_serializer.assert_called_with(data={'test': 3})
        self.assertTrue(mock_serializer.return_value.save.called)
        mock_pview.objects.create.assert_called_with(state=self.property_state,
                                                     cycle_id=2,
                                                     property_id=4,
                                                     org_id=1)

    @mock.patch('seed.serializers.properties.PropertyStateWritableSerializer')
    def test_update_put(self, mock_serializer):
        """Test update with PUT"""
        mock_serializer.return_value.is_valid.return_value = True
        mock_serializer.return_value.save.return_value = self.property_state
        mock_request = mock.MagicMock()
        data = {'org_id': 1, 'cycle': 2, 'state': {'test': 3}, 'property': 4}

        serializer = PropertyViewAsStateSerializer(
            context={'request': mock_request})
        mock_request.METHOD = 'PUT'
        serializer.update(self.property_view, data)
        mock_serializer.assert_called_with(data={'test': 3})
        self.assertTrue(mock_serializer.return_value.save.called)

    @mock.patch('seed.serializers.properties.PropertyStateWritableSerializer')
    def test_update_patch(self, mock_serializer):
        """Test update with PATCH"""
        mock_serializer.return_value.is_valid.return_value = True
        mock_serializer.return_value.save.return_value = self.property_state
        mock_request = mock.MagicMock()
        mock_request.method = 'PATCH'
        data = {'org_id': 1, 'cycle': 2, 'state': {'test': 3}, 'property': 4}
        serializer = PropertyViewAsStateSerializer(
            context={'request': mock_request})
        serializer.update(self.property_view, data)
        mock_serializer.assert_called_with(self.property_state,
                                           data={'test': 3})
        self.assertTrue(mock_serializer.return_value.save.called)