class TestCommandWithSchema(TestCase):
    def setUp(self):
        self.schema = Schema.objects.filter(
            version=TEST_SCHEMA_VERSION).first()
        if not self.schema:
            # add schema file - make sure to create a copy since the version will be deleted if
            # the schema is deleted
            sf = os.path.join(os.path.dirname(__file__), 'data',
                              'test_schema.xsd')
            file = open(sf, 'rb')
            simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

            self.schema = Schema(name='Version {}'.format(TEST_SCHEMA_VERSION),
                                 version=TEST_SCHEMA_VERSION,
                                 schema_file=simple_uploaded_file)
            self.schema.save(
            )  # Calling save also processes the schema and generates the template

    def test_create_use_case_command(self):
        print('TESTING CREATE USE CASE COMMAND')

        out = StringIO()
        call_command('create_use_case',
                     schema_version=TEST_SCHEMA_VERSION,
                     stdout=out)

        # assert that a use case was created
        use_cases = UseCase.objects.all().count()
        print("USE CASES: {}".format(use_cases))
        self.assertGreater(use_cases, 0)

    def test_bedes_command(self):
        # The schema must exist before this command is called.
        print('TESTING BEDES COMMAND')

        # create the CSV files
        out = StringIO()
        call_command('bedes',
                     schema_version=TEST_SCHEMA_VERSION,
                     bedes_version='v2.2',
                     stdout=out)

        # add to database
        call_command('bedes',
                     schema_version=TEST_SCHEMA_VERSION,
                     bedes_version='v2.2',
                     save_to_db=True,
                     stdout=out)

        # check that there are items in bedes models
        bterms = BedesTerm.objects.all().count()
        benums = BedesEnumeration.objects.all().count()
        print("BEDES TERMS: {}, BEDES ENUMS: {}".format(bterms, benums))
        self.assertGreater(bterms, 0)
        self.assertGreater(benums, 0)

    def tearDown(self):
        # clean-up files on disk
        if self.schema and self.schema.id is not None:
            self.schema.delete()
Example #2
0
    def setUp(self):
        sf = os.path.join(os.path.dirname(__file__), 'data', 'test_schema.xsd')
        file = open(sf, 'rb')
        simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

        self.schema = Schema(name='Version {}'.format(TEST_SCHEMA_VERSION),
                             version=TEST_SCHEMA_VERSION,
                             schema_file=simple_uploaded_file)
        self.schema.save(
        )  # Calling save also processes the schema and generates the template
class TestUseCase(TestCase):
    def setUp(self):
        self.schema = Schema.objects.filter(version=TEST_SCHEMA_VERSION).first()
        if not self.schema:
            # add schema file - make sure to create a copy since the version will be deleted if
            # the schema is deleted
            sf = os.path.join(os.path.dirname(__file__), 'data', 'test_schema.xsd')
            file = open(sf, 'rb')
            simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

            self.schema = Schema(
                name='Version {}'.format(TEST_SCHEMA_VERSION),
                version=TEST_SCHEMA_VERSION,
                schema_file=simple_uploaded_file
            )
            self.schema.save()  # Calling save also processes the schema and generates the template

        # create 1 use case without a use case file
        self.usecase = UseCase(
            name='Test Use Case',
            schema=self.schema
        )
        self.usecase.save()  # Calling save also processes the schema and generates the template

    def add_usecase(self):
        # add file and save
        usf = os.path.join(os.path.dirname(__file__), 'data', 'test_use_case.sch')
        file = open(usf, 'rb')
        simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

        # save to model
        self.usecase.import_file = simple_uploaded_file
        self.usecase.save()

    def delete_usecase(self):
        self.saved_file_path = self.usecase.import_file.path
        self.usecase.delete()

    def test_add_usecase_file_then_delete(self):
        self.add_usecase()
        # then check that file has a path
        self.assertTrue(self.usecase.import_file.path != '')

        print('usecase saved filename: {}'.format(self.usecase.import_file.path))

        self.delete_usecase()
        self.assertFalse(os.path.exists(self.saved_file_path))

    def tearDown(self):
        # clean-up files on disk
        if self.schema and self.schema.id is not None:
            self.schema.delete()
    def setUp(self):
        self.schema = Schema.objects.filter(version=TEST_SCHEMA_VERSION).first()
        if not self.schema:
            # add schema file - make sure to create a copy since the version will be deleted if
            # the schema is deleted
            sf = os.path.join(os.path.dirname(__file__), 'data', 'test_schema.xsd')
            file = open(sf, 'rb')
            simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

            self.schema = Schema(
                name='Version {}'.format(TEST_SCHEMA_VERSION),
                version=TEST_SCHEMA_VERSION,
                schema_file=simple_uploaded_file
            )
            self.schema.save()  # Calling save also processes the schema and generates the template
Example #5
0
    def handle(self, *args, **options):
        """
        Load the BuildingSync file.

        :param args:
        :param options:
        :return:
        """
        self.stdout.write('Importing schema %s' % options['schema_version'])
        if not options['overwrite']:
            if Schema.objects.filter(
                    version=options['schema_version']).exists():
                self.stdout.write('Schema already exists in the database: %s' %
                                  options['schema_version'])
                exit(0)

        schema = Schema.objects.filter(
            version=options['schema_version']).first()
        if schema:
            schema.delete()

        # schema file - make sure to create a copy since the version will be deleted if
        # the schema is deleted
        sf = 'bsyncviewer/lib/buildingsync_schemas/BuildingSync_v%s.xsd' % options[
            'schema_version']
        schema_file = 'bsyncviewer/media/uploaded_schemas/BuildingSync_v%s.xsd' % options[
            'schema_version']
        if os.path.exists(schema_file):
            os.remove(schema_file)
        if not os.path.exists(os.path.dirname(schema_file)):
            os.makedirs(os.path.dirname(schema_file))
        copyfile(sf, schema_file)
        schema = Schema(name='Version %s' % options['schema_version'],
                        version=options['schema_version'],
                        schema_file='uploaded_schemas/BuildingSync_v%s.xsd' %
                        options['schema_version'])
        schema.save()  # Calling save also processes the schema

        # Print out some of the data for validation purposes
        for attribute in schema.attributes.all().order_by('id'):
            print(attribute)
            # if attribute.enumeration_classes.first():
            #     for enum in attribute.enumeration_classes.first().enumerations.all().order_by('index'):
            #         print("****************** enumeration: %s" % enum)

        self.stdout.write(
            'Imported %s fields and %s enumerations' %
            (schema.attributes.count(), schema.enumerations.count()))
Example #6
0
class TestSchema(TestCase):
    def setUp(self):
        sf = os.path.join(os.path.dirname(__file__), 'data', 'test_schema.xsd')
        file = open(sf, 'rb')
        simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

        self.schema = Schema(name='Version {}'.format(TEST_SCHEMA_VERSION),
                             version=TEST_SCHEMA_VERSION,
                             schema_file=simple_uploaded_file)
        self.schema.save(
        )  # Calling save also processes the schema and generates the template

    def test_schema_parsed(self):
        # check that post_save worked: schema_parsed should be True and there should be attributes related to schema in db
        self.assertTrue(self.schema.schema_parsed)
        attributes = self.schema.attributes
        self.assertGreater(attributes.count(), 0)

    def test_enumerations(self):
        # check a couple of the attributes to make sure have enumerations
        test_path = 'BuildingSync.Facilities.Facility.Sites.Site.ClimateZoneType.ASHRAE.ClimateZone'

        attribute = self.schema.attributes.filter(path=test_path).first()
        self.assertIsNotNone(attribute)
        self.assertEqual(attribute.enumeration_classes.count(), 1)
        self.assertEqual(
            attribute.enumeration_classes.first().enumerations.count(), 17)
        self.assertEqual(
            attribute.enumeration_classes.first().enumerations.first().name,
            '1A')

    def test_schema_js_tree(self):
        # test the retrieval of the schema as a jstree for dictionary view
        js_tree = get_schema_jstree_data(TEST_SCHEMA_VERSION)

        # assert that js_tree is a list, not-empty
        self.assertTrue(isinstance(js_tree, list))
        self.assertGreater(len(js_tree), 0)

        # ensure can be dumped to JSON
        json.dumps(js_tree)

    def test_cleanup(self):
        # test that physical files are cleaned up on disk

        schema_file_path = self.schema.schema_file.path

        # delete schema
        self.schema.delete()

        print('schema filepath: {}'.format(schema_file_path))

        # assert that physical files were also deleted
        self.assertFalse(os.path.isfile(schema_file_path))

    def tearDown(self):
        # clean-up files on disk
        if self.schema and self.schema.id is not None:
            self.schema.delete()
class TestValidator(TestCase):
    def setUp(self):
        self.schema = Schema.objects.filter(version=TEST_SCHEMA_VERSION).first()
        if not self.schema:
            # add schema file - make sure to create a copy since the version will be deleted if
            # the schema is deleted
            sf = os.path.join(os.path.dirname(__file__), 'data', 'test_schema.xsd')
            file = open(sf, 'rb')
            simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

            self.schema = Schema(
                name='Version {}'.format(TEST_SCHEMA_VERSION),
                version=TEST_SCHEMA_VERSION,
                schema_file=simple_uploaded_file
            )
            self.schema.save()  # Calling save also processes the schema and generates the template

    def test_init_forms(self):
        # test form init
        LoadXMLFile()
        LoadXMLExample()

    # TODO: test uploading a file through the form
    # def test_file_form_valid_data(self):
    #     form_data = {
    #         'schema_version': DEFAULT_SCHEMA_VERSION,
    #         'form_type': 'file'
    #     }
    #     form = LoadXMLExample(data=form_data)
    #     print("FORM: {}".format(form))
    #     print("VALID? {}".format(form.is_valid()))
    #     self.assertTrue(form.is_valid())

    def test_file_form_no_data(self):
        form_data = {
        }
        form = LoadXMLFile(data=form_data)
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors, {
            'schema_version': ['This field is required.'],
            'file': ['This field is required.'],
            'form_type': ['This field is required.']
        })

    def test_example_form_no_data(self):
        form_data = {
        }
        form = LoadXMLExample(data=form_data)
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors, {
            'schema_version': ['This field is required.'],
            'file_name': ['This field is required.'],
            'form_type': ['This field is required.']
        })

    def test_example_form_valid_data(self):
        file_name = os.path.join(os.path.join(os.path.dirname(__file__), 'data', 'test_valid_schema.xml'))

        form_data = {
            'schema_version': TEST_SCHEMA_VERSION,
            'form_type': 'example',
            'file_name': file_name
        }

        client = Client()
        response = client.post('/validator', form_data)
        self.assertEqual(response.status_code, 200)

    def test_validator_workflow(self):
        filepath = os.path.join(os.path.join(os.path.dirname(__file__), 'data', 'test_valid_schema.xml'))
        f = open(filepath, 'r')
        workflow = ValidationWorkflow(f, filepath, TEST_SCHEMA_VERSION)
        validation_results = workflow.validate_all()
        print("VAL: {}".format(validation_results))
        self.assertIn('schema', validation_results)
        self.assertIn('use_cases', validation_results)

    def tearDown(self):
        # clean-up files on disk
        if self.schema and self.schema.id is not None:
            self.schema.delete()
Example #8
0
class TestApi(APITestCase):
    def setUp(self):
        self.schema = Schema.objects.filter(
            version=TEST_SCHEMA_VERSION).first()
        if not self.schema:
            # add schema file - make sure to create a copy since the version will be deleted if
            # the schema is deleted
            sf = os.path.join(os.path.dirname(__file__), 'data',
                              'test_schema.xsd')
            file = open(sf, 'rb')
            simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

            self.schema = Schema(name='Version {}'.format(TEST_SCHEMA_VERSION),
                                 version=TEST_SCHEMA_VERSION,
                                 schema_file=simple_uploaded_file)
            self.schema.save(
            )  # Calling save also processes the schema and generates the template

        print("SETUP COMPLETE")

    def test_validator_api(self):
        print("START OF TEST_VALIDATOR_API")

        head, tail = os.path.split(os.path.dirname(__file__))
        filepath = os.path.join(
            os.path.join(os.path.dirname(__file__), 'data',
                         'test_valid_schema.xml'))
        f = open(filepath, 'rb')
        simple_uploaded_file = SimpleUploadedFile(f.name, f.read())

        data = {
            'schema_version': TEST_SCHEMA_VERSION,
            'file': simple_uploaded_file
        }

        url = reverse('validate_api')
        print("URL: {}".format(url))
        response = self.client.post(url, data, format='multipart')

        print("RESPONSE STATUS CODE: {}".format(response.status_code))
        print("RESPONSE CONTENT: {}".format(response.data))
        # assert that the call worked
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        # assert that the schema validates
        valid_schema = response.data['validation_results']['schema']['valid']
        print("VALID SCHEMA? {}".format(valid_schema))
        self.assertTrue(valid_schema)

    def test_validator_zip_api(self):
        print("START OF TEST_VALIDATOR_ZIP_API")

        head, tail = os.path.split(os.path.dirname(__file__))
        filepath = os.path.join(
            os.path.join(os.path.dirname(__file__), 'data',
                         'example_files.zip'))
        f = open(filepath, 'rb')
        simple_uploaded_file = SimpleUploadedFile(f.name, f.read())

        data = {
            'schema_version': TEST_SCHEMA_VERSION,
            'file': simple_uploaded_file
        }

        url = reverse('validate_api')
        print("URL: {}".format(url))
        response = self.client.post(url, data, format='multipart')

        print("RESPONSE STATUS CODE: {}".format(response.status_code))
        print("RESPONSE CONTENT: {}".format(response.data))
        # assert that the call worked
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        # assert that the schema validates
        valid_schema = response.data['all_files_valid']
        print("VALID SCHEMA? {}".format(valid_schema))
        self.assertTrue(valid_schema)

    def tearDown(self):
        # clean-up files on disk
        print("IN TEAR DOWN NOW")
        if self.schema and self.schema.id is not None:
            self.schema.delete()
Example #9
0
class BsyncviewerViewTests(TestCase):
    def test_index_ok(self):
        response = self.client.get(reverse('index'))
        print('Testing Index page OK')
        self.assertEqual(response.status_code, 200)

    def test_validator_ok(self):
        response = self.client.get(reverse('validator'))
        print('Testing Validator page OK')
        self.assertEqual(response.status_code, 200)

    def test_use_cases_ok(self):
        response = self.client.get(reverse('cases'))
        print('Testing Cases page OK')
        self.assertEqual(response.status_code, 200)

    # The default redirect is to 1.0.0 but we are not loading that schema anymore.
    # def test_dictionary_redirect(self):
    #     self.add_schema()
    #     response = self.client.get(reverse('dictionary'))
    #     print('Testing Dictionary page redirect')
    #     redirect_url = '/dictionary/{}/'.format('0.0.1')
    #     self.assertRedirects(response, redirect_url)
    #
    #     # clean-up files on disk
    #     self.schema.delete()

    # this should redirect to the default schema version
    def test_dictionary_404_when_no_schema(self):
        response = self.client.get(reverse('dictionary'))
        print('Testing Dictionary page redirect')
        redirect_url = '/dictionary/{}/'.format(
            settings.DEFAULT_SCHEMA_VERSION)
        self.assertRedirects(response, redirect_url, target_status_code=404)

    def test_bedes_ajax_call(self):
        # need schema and bedes imported
        self.add_schema()
        self.add_bedes_mapping()

        # get 1st bedes enumeration
        benum = BedesEnumeration.objects.filter(term='Cold')
        print('first benum: {}'.format(benum[:1].values()))
        benum = benum[0]
        # get related bedes term
        bterm = BedesTerm.objects.filter(content_uuid=benum.related_term_uuid)
        print('bterm: {}'.format(bterm[:1].values()))
        bterm = bterm[0]
        # get attribute
        mapping = BedesMapping.objects.filter(bedesTerm_id=bterm.pk)[0]
        print('mapping: {}, bedestermid: {}, attributeid: {}'.format(
            mapping.id, mapping.bedesTerm_id, mapping.attribute_id))

        attrb = Attribute.objects.get(id=mapping.attribute_id)
        print('attribute: {}'.format(attrb))

        client = Client()
        response = client.get('/ajax/enum/',
                              {'element_id': mapping.attribute_id},
                              content_type='application/json',
                              HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        print("RESPONSE: {}".format(response.status_code))
        code_str = str(response.status_code)
        self.assertEqual(code_str, '200')
        print("RESPONSE CONTENT: {}".format(response.content))
        self.assertContains(response, 'bedes_term')
        self.assertContains(response, 'has_enum')
        self.assertContains(response, 'enums')

        # clean-up files on disk
        self.schema.delete()

    def add_schema(self):
        self.schema = Schema.objects.filter(
            version=TEST_SCHEMA_VERSION).first()
        if not self.schema:
            # add schema file - make sure to create a copy since the version will be deleted if
            # the schema is deleted
            sf = os.path.join(os.path.dirname(__file__), 'data',
                              'test_schema.xsd')
            file = open(sf, 'rb')
            simple_uploaded_file = SimpleUploadedFile(file.name, file.read())

            self.schema = Schema(name='Version {}'.format(TEST_SCHEMA_VERSION),
                                 version=TEST_SCHEMA_VERSION,
                                 schema_file=simple_uploaded_file)
            self.schema.save(
            )  # Calling save also processes the schema and generates the template

    def add_bedes_mapping(self):
        # create the CSV files
        out = StringIO()
        print("VERSION: {}".format(TEST_SCHEMA_VERSION))
        call_command('bedes',
                     schema_version=TEST_SCHEMA_VERSION,
                     bedes_version='v2.2',
                     stdout=out)

        # add to database
        call_command('bedes',
                     schema_version=TEST_SCHEMA_VERSION,
                     bedes_version='v2.2',
                     save_to_db=True,
                     stdout=out)