def insert_data(self): """Insert a set of Templates and Template Version Managers. Returns: """ # Make a connexion with a mock database xsd = ('<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">' '<xs:element name="tag"></xs:element></xs:schema>') self.user1_template = Template(filename="template1.xsd", content=xsd, hash="hash1", user="******").save() self.user2_template = Template(filename="template2.xsd", content=xsd, hash="hash2", user="******").save() self.global_template = Template(filename="global_template.xsd", content=xsd, hash="global hash", user=None).save() self.user1_tvm = TemplateVersionManager( title="template 1", user="******", versions=[ str(self.user1_template.id), ], current=str(self.user1_template.id), is_disabled=False, disabled_versions=[], ).save() self.user2_tvm = TemplateVersionManager( title="template 2", user="******", versions=[str(self.user2_template.id)], current=str(self.user2_template.id), is_disabled=False, disabled_versions=[], ).save() self.global_tvm = TemplateVersionManager( title="global template", user=None, versions=[str(self.global_template.id)], current=str(self.global_template.id), is_disabled=False, disabled_versions=[], ).save() self.template_vm_collection = [ self.user1_tvm, self.user2_tvm, self.global_tvm ]
def insert_registry_schema(xsd_filename, xsd_content): # Check if schema is valid is_schema_valid(xsd_content) template = Template( filename=xsd_filename, hash=get_hash(xsd_content), content=xsd_content ).save() template_version_manager = TemplateVersionManager(title=xsd_filename) # save the template in database try: from core_main_app.components.version_manager import api as version_manager_api # insert the initial template in the version manager template_version_manager.insert(template) template_version_manager.set_current_version(template) # insert the version manager in database template_version_manager.save_version_manager() # get template display name display_name = get_latest_version_name(template_version_manager) # update saved template template.display_name = display_name template.save() # return version manager return template_version_manager except Exception as e: template.delete() raise e
def _save_template(request, assets, context): """Save a template. Args: request: assets: context: Returns: """ # get the schema name name = request.POST['name'] # get the file from the form xsd_file = request.FILES['upload_file'] # read the content of the file xsd_data = read_xsd_file(xsd_file) try: template = Template(filename=xsd_file.name, content=xsd_data) template_version_manager = TemplateVersionManager(title=name) template_version_manager_api.insert(template_version_manager, template) return HttpResponseRedirect(reverse("admin:core_main_app_templates")) except exceptions.XSDError, xsd_error: return handle_xsd_errors(request, assets, context, xsd_error, xsd_data, xsd_file.name)
def _add_template(): """Add the registry template. Returns: """ xsd_filepath = REGISTRY_XSD_FILEPATH xsd_filename = REGISTRY_XSD_FILENAME if xsd_filename == "": raise Exception( "Please configure the REGISTRY_XSD_FILENAME setting in your project." ) if xsd_filepath == "": raise Exception( "Please configure the REGISTRY_XSD_FILEPATH setting in your project." ) try: version_manager_api.get_active_global_version_manager_by_title( xsd_filename) except exceptions.DoesNotExist: default_xsd_path = finders.find(xsd_filepath) xsd_data = read_file_content(default_xsd_path) template = Template(filename=xsd_filename, content=xsd_data) template_version_manager = TemplateVersionManager(title=xsd_filename) template_version_manager_api.insert(template_version_manager, template) except Exception as e: logger.error("Impossible to add the template: {0}".format(str(e)))
def get_all(_cls=True): """ Return all Template Version Managers. Returns: """ return TemplateVersionManager.get_all_version_manager(_cls)
def get_global_version_managers(_cls=True): """Get all global version managers of a template. Returns: _cls: """ return TemplateVersionManager.get_global_version_managers(_cls)
def get_active_global_version_manager(_cls=True): """ Return all active Version Managers with user set to None. Returns: """ return TemplateVersionManager.get_active_global_version_manager(_cls)
def _save_template(request, assets, context): """Save a template. Args: request: assets: context: Returns: """ # get the schema name name = request.POST['name'] # get the file from the form xsd_file = request.FILES['upload_file'] # read the content of the file xsd_data = read_xsd_file(xsd_file) try: template = Template(filename=xsd_file.name, content=xsd_data) template_version_manager = TemplateVersionManager(title=name) template_version_manager_api.insert(template_version_manager, template) return HttpResponseRedirect(reverse("admin:core_main_app_templates")) except exceptions.XSDError as xsd_error: return handle_xsd_errors(request, assets, context, xsd_error, xsd_data, xsd_file.name) except exceptions.NotUniqueError: context['errors'] = html_escape( "A template with the same name already exists. Please choose another name." ) return _upload_template_response(request, assets, context) except Exception as e: context['errors'] = html_escape(str(e)) return _upload_template_response(request, assets, context)
def resolve_dependencies(request): """Resolve import/includes to avoid local references. Args: request: Returns: """ try: # Get the parameters name = request.POST.get('name', None) version_manager_id = request.POST.get('version_manager_id', '') filename = request.POST['filename'] xsd_content = request.POST['xsd_content'] schema_locations = request.POST.getlist('schemaLocations[]') dependencies = request.POST.getlist('dependencies[]') # create new object template = Template(filename=filename, content=_get_xsd_content_from_html(xsd_content)) init_template_with_dependencies( template, _get_dependencies_dict(schema_locations, dependencies)) # get the version manager or create a new one if version_manager_id != '': template_version_manager = version_manager_api.get( version_manager_id) else: template_version_manager = TemplateVersionManager(title=name) template_version_manager_api.insert(template_version_manager, template) except Exception, e: return HttpResponseBadRequest(e.message)
def get_all_by_user_id(request, _cls=True): """Return all Template Version Managers with given user id. Returns: """ return TemplateVersionManager.get_all_version_manager_by_user_id( str(request.user.id), _cls)
def get_all_version_manager_except_user_id(user_id, _cls=True): """ Return all Version Managers of all users except user with given user id. Returns: """ return TemplateVersionManager.get_all_version_manager_except_user_id( user_id, _cls)
def get_all_by_user_id(user_id, _cls=True): """ Return all Template Version Managers with given user id. Returns: """ return TemplateVersionManager.get_all_version_manager_by_user_id( user_id, _cls)
def create(self, validated_data): """ Create. Args: validated_data: Returns: """ return TemplateVersionManager(**validated_data)
def insert_data(self): """Insert a set of Templates and Template Version Managers. Returns: """ # Make a connexion with a mock database self.template_1_1 = Template( filename="template1_1.xsd", content="content1_1", hash="hash1_1" ).save() self.template_1_2 = Template( filename="template1_2.xsd", content="content1_2", hash="hash1_2" ).save() self.template_1_3 = Template( filename="template1_3.xsd", content="content1_3", hash="hash1_3" ).save() self.template_2_1 = Template( filename="template2_1.xsd", content="content2_1", hash="hash2_1" ).save() self.template_vm_1 = TemplateVersionManager( title="template 1", user=None, versions=[ str(self.template_1_1.id), str(self.template_1_2.id), str(self.template_1_3.id), ], current=str(self.template_1_3.id), is_disabled=False, disabled_versions=[str(self.template_1_2.id)], ).save() self.template_vm_2 = TemplateVersionManager( title="template 2", user="******", versions=[str(self.template_2_1.id)], current=str(self.template_2_1.id), is_disabled=False, disabled_versions=[], ).save() self.template_vm_collection = [self.template_vm_1, self.template_vm_2]
def get_by_id(template_version_manager_id): """Get a template version manager by its id. Args: template_version_manager_id: Id. Returns: """ return TemplateVersionManager.get_by_id(template_version_manager_id)
def get_all_by_version_ids(version_ids): """Get all template version managers by a list of version ids. Args: version_ids: list of version ids. Returns: List of template version managers. """ return TemplateVersionManager.get_all_by_version_ids(version_ids)
def get_by_version_id(version_id): """Get the template version manager containing the given version id. Args: version_id: version id. Returns: template version manager. """ return TemplateVersionManager.get_by_version_id(version_id)
def test_get_returns_http_200_when_data_exists(self, mock_get_by_id): # Arrange mock_user = create_mock_user("1", is_superuser=True) mock_get_by_id.return_value = TemplateVersionManager() # Mock response = RequestMock.do_request_get( views.TemplateVersionManagerDetail.as_view(), mock_user, param={"pk": "id"} ) # Assert self.assertEqual(response.status_code, status.HTTP_200_OK)
def get_global_version_managers(request, _cls=True): """Get all global version managers of a template. Args: request: _cls: Returns: """ return TemplateVersionManager.get_global_version_managers(_cls)
def test_anonymous_returns_http_403( self, template_version_manager_get_all_global_version_managers): template_version_manager_get_all_global_version_managers.return_value = ( TemplateVersionManager(user=None)) response = RequestMock.do_request_get( template_version_manager_views.GlobalTemplateVersionManagerList. as_view(), None, ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_authenticated_returns_http_200(self, version_manager_get_by_id, version_manager_restore): version_manager_restore.return_value = {} version_manager_get_by_id.return_value = TemplateVersionManager(user='******') mock_user = create_mock_user('1') response = RequestMock.do_request_patch( template_version_manager_views.RestoreTemplateVersionManager.as_view(), mock_user, param={'pk': self.fake_id} ) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_staff_returns_http_200(self, version_manager_disable, version_manager_get_by_id): version_manager_get_by_id.return_value = TemplateVersionManager(user='******') version_manager_disable.return_value = {} mock_user = create_mock_user('1', is_staff=True) response = RequestMock.do_request_patch( template_version_manager_views.DisableTemplateVersionManager.as_view(), mock_user, param={'pk': self.fake_id} ) self.assertEqual(response.status_code, status.HTTP_200_OK)
def mock_template_version_manager(version=""): with open( join( DUMP_OAI_PMH_TEST_PATH, "template_version_manager{0}.json".format(version), )) as f: data = f.read() data_json = json.loads(data) list_template_version_manager = [ TemplateVersionManager(**x) for x in data_json ] return list_template_version_manager
def save_template(request): """Save the current template in the database. Args: request: Returns: """ try: template_name = request.POST['templateName'] xsd_string = request.session['newXmlTemplateCompose'] response_dict = {} try: # Build XSD tree xsd_tree = XSDTree.build_tree(xsd_string) # validate the schema error = main_xml_utils.validate_xml_schema(xsd_tree) if error is not None: return _error_response('This is not a valid XML schema. ' + error) except Exception, e: return _error_response('This is not a valid XML schema. ' + e.message) # get list of dependencies dependencies = _get_dependencies_ids( request.session["includedTypesCompose"]) try: # create template version manager template_version_manager = TemplateVersionManager( title=template_name, user=str(request.user.id)) # create template template = Template(filename=template_name, content=xsd_string, dependencies=dependencies) # save template in database template_version_manager_api.insert(template_version_manager, template) except exceptions.NotUniqueError: return HttpResponseBadRequest( "A template with the same name already exists. Please choose another name." ) except Exception, e: return _error_response(e.message)
def _create_template_version_manager(title="", is_disabled=False, user_id=""): """ Returns a templates version manager :param title: :return: """ return TemplateVersionManager( id=ObjectId(), title=title, versions=[], user=user_id, is_disabled=is_disabled, disabled_versions=[], _cls=TemplateVersionManager.class_name )
def insert_templates(self): saved_templates = [] saved_template_version = [] list_templates = OaiPmhMock.mock_template() for template in list_templates: # Create template version manager template_version_manager = TemplateVersionManager( title='default_chemical_element_type') template_version_manager_api.insert(template_version_manager, template) saved_template_version.append(template_version_manager) saved_templates.append(template.save()) self.templates = saved_templates self.template_version = saved_template_version
def test_authenticated_returns_http_200(self, version_manager_disable, version_manager_get_by_id): version_manager_get_by_id.return_value = TemplateVersionManager( user="******") version_manager_disable.return_value = {} mock_user = create_mock_user("1") response = RequestMock.do_request_patch( template_version_manager_views.DisableTemplateVersionManager. as_view(), mock_user, param={"pk": self.fake_id}, ) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_staff_returns_http_200(self, version_manager_get_by_id, version_manager_restore): version_manager_restore.return_value = {} version_manager_get_by_id.return_value = TemplateVersionManager( user="******") mock_user = create_mock_user("1", is_staff=True) response = RequestMock.do_request_patch( template_version_manager_views.RestoreTemplateVersionManager. as_view(), mock_user, param={"pk": self.fake_id}, ) self.assertEqual(response.status_code, status.HTTP_200_OK)
def resolve_dependencies(request): """Resolve import/includes to avoid local references. Args: request: Returns: """ try: # Get the parameters name = request.POST.get("name", None) version_manager_id = request.POST.get("version_manager_id", "") filename = request.POST["filename"] xsd_content = request.POST["xsd_content"] schema_locations = request.POST.getlist("schemaLocations[]") dependencies = request.POST.getlist("dependencies[]") # create new object template = Template( filename=filename, content=_get_xsd_content_from_html(xsd_content) ) init_template_with_dependencies( template, _get_dependencies_dict(schema_locations, dependencies), request=request, ) # get the version manager or create a new one if version_manager_id != "": template_version_manager = version_manager_api.get( version_manager_id, request=request ) else: template_version_manager = TemplateVersionManager(title=name) template_version_manager_api.insert( template_version_manager, template, request=request ) except Exception as e: return HttpResponseBadRequest(escape(str(e))) return HttpResponse(json.dumps({}), content_type="application/javascript")
def _set_xsd_template(xsd_filename, xsd_data): """Register XSD template to Django. Args: xsd_filename: xsd_data: Returns: """ try: template = Template(filename=xsd_filename, content=xsd_data) template_version_manager = TemplateVersionManager(title=xsd_filename) template_version_manager_api.insert(template_version_manager, template) logger.info("XSD template:" + xsd_filename + " registered as a template.") except exceptions.CoreError as e: logger.info(xsd_filename + " didn't registered as a template :" + str(e)) except exceptions.NotUniqueError as e: logger.info(xsd_filename + " didn't registered as a template :" + str(e)) except Exception as e: logger.info(xsd_filename + " didn't registered as a template :" + str(e))