Esempio n. 1
0
 def test_autocreate_mapping(self, collection, class_configurator):
     # This registers a representer (factory) and creates a mapping for
     # the collection.
     coll_rpr = as_representer(collection, CsvMime)
     mb = next(iter(collection))
     # This auto-creates a mapping for the member.
     coll_rpr.resource_to_data(mb)
     rpr_reg = class_configurator.get_registered_utility(IRepresenterRegistry)
     mp_reg = rpr_reg.get_mapping_registry(CsvMime)
     mp_before = mp_reg.find_mapping(type(mb))
     # This registers a representer (factory) for the member and finds
     # the previously created mapping for the member.
     as_representer(mb, CsvMime)
     mp_after = mp_reg.find_mapping(type(mb))
     assert mp_before is mp_after
Esempio n. 2
0
 def _upload_metadata(self, xls_filename, scenario, app):
     # First, create a new metadata entity and POST it.
     emd_coll = create_staging_collection(IExperimentMetadata)
     emd = ExperimentMetadata('unit_test_metadata',
                              next(iter(get_root_aggregate(ISubproject))),
                              1, get_experiment_metadata_type(scenario))
     mb_emd = emd_coll.create_member(emd)
     rpr = as_representer(mb_emd, XmlMime)
     emd_rpr = rpr.to_string(mb_emd)
     res = app.post("/%s" % emd_coll.__name__,
                    params=emd_rpr,
                    content_type=XmlMime.mime_type_string,
                    status=HTTPCreated.code)
     self.__session.commit()
     mb_url = res.headers['Location']
     # Now, PUT the excel meta data file.
     self.__session.begin_nested()
     with open(xls_filename, 'rb') as xls_file:
         res = app.put(mb_url,
                       params=xls_file.read(),
                       content_type=XlsMime.mime_type_string)
     # If the file had warnings, we have to repeat the PUT.
     if res.status.endswith(HTTPTemporaryRedirect.title):
         self.__session.rollback()
         # 307 Redirect: Repeat with warnings disabled.
         with open(xls_filename, 'rb') as xls_file:
             res = app.put(res.headers['Location'],
                           params=xls_file.read(),
                           content_type=XlsMime.mime_type_string,
                           status=HTTPOk.code)
     self.__session.commit()
     assert res.status.endswith(HTTPOk.title)
     return mb_url
 def test_update_nested_collection_from_data(self):
     # Set up member that has one child.
     root_coll = get_root_collection(IMyEntity)
     ent = MyEntity(id=1)
     child0 = MyEntityChild(id=0)
     ent.children.append(child0)
     mb = root_coll.create_member(ent)
     # Set up another member with two children with different IDs.
     stg_coll = create_staging_collection(IMyEntity)
     upd_ent = MyEntity(id=1)
     child1 = MyEntityChild(id=1)
     child1.parent = upd_ent
     child2 = MyEntityChild(id=2)
     child2.parent = upd_ent
     upd_ent.children.append(child1)
     upd_ent.children.append(child2)
     upd_mb = stg_coll.create_member(upd_ent)
     rpr = as_representer(mb, CsvMime)
     attribute_options = {('children',):{IGNORE_OPTION:False,
                                         WRITE_AS_LINK_OPTION:False}, }
     rpr.configure(attribute_options=attribute_options)
     de = rpr.data_from_resource(upd_mb)
     #
     mb.update(de)
     self.assert_equal(set([mb.id for mb in mb.children]), set([1, 2]))
Esempio n. 4
0
 def test_autocreate_mapping(self, collection, class_configurator):
     # This registers a representer (factory) and creates a mapping for
     # the collection.
     coll_rpr = as_representer(collection, CsvMime)
     mb = next(iter(collection))
     # This auto-creates a mapping for the member.
     coll_rpr.resource_to_data(mb)
     rpr_reg = class_configurator.get_registered_utility(
         IRepresenterRegistry)
     mp_reg = rpr_reg.get_mapping_registry(CsvMime)
     mp_before = mp_reg.find_mapping(type(mb))
     # This registers a representer (factory) for the member and finds
     # the previously created mapping for the member.
     as_representer(mb, CsvMime)
     mp_after = mp_reg.find_mapping(type(mb))
     assert mp_before is mp_after
Esempio n. 5
0
 def test_autocreate_mapping(self):
     coll = create_collection()
     # This registers a representer (factory) and creates a mapping for
     # the collection.
     coll_rpr = as_representer(coll, CsvMime)
     mb = iter(coll).next()
     # This auto-creates a mapping for the member.
     coll_rpr.data_from_resource(mb)
     rpr_reg = self.config.get_registered_utility(IRepresenterRegistry)
     mp_reg = rpr_reg.get_mapping_registry(CsvMime)
     mp_before = mp_reg.find_mapping(type(mb))
     # This registers a representer (factory) for the member and finds
     # the previously created mapping for the member.
     as_representer(mb, CsvMime)
     mp_after = mp_reg.find_mapping(type(mb))
     self.assert_true(mp_before is mp_after)
Esempio n. 6
0
 def test_update_nested_collection_from_data(self, resource_repo):
     # Set up member that has one child.
     coll = resource_repo.get_collection(IMyEntity)
     ent = MyEntity(id=1)
     child0 = MyEntityChild(id=0)
     ent.children.append(child0)
     mb = coll.create_member(ent)
     # Set up another member with two children with different IDs.
     tmp_coll = create_staging_collection(IMyEntity)
     upd_ent = MyEntity(id=1)
     child1 = MyEntityChild(id=1)
     child1.parent = upd_ent
     child2 = MyEntityChild(id=2)
     child2.parent = upd_ent
     upd_ent.children.append(child1)
     upd_ent.children.append(child2)
     upd_mb = tmp_coll.create_member(upd_ent)
     rpr = as_representer(mb, CsvMime)
     attribute_options = {('children',):{IGNORE_OPTION:False,
                                         WRITE_AS_LINK_OPTION:False}, }
     with rpr.with_updated_configuration(attribute_options=
                                                 attribute_options):
         de = rpr.resource_to_data(upd_mb)
         mb.update(de)
         assert set([mb.id for mb in mb.children]) == set([1, 2])
Esempio n. 7
0
 def test_autocreate_mapping(self):
     coll = create_collection()
     # This registers a representer (factory) and creates a mapping for
     # the collection.
     coll_rpr = as_representer(coll, CsvMime)
     mb = iter(coll).next()
     # This auto-creates a mapping for the member.
     coll_rpr.data_from_resource(mb)
     rpr_reg = self.config.get_registered_utility(IRepresenterRegistry)
     mp_reg = rpr_reg.get_mapping_registry(CsvMime)
     mp_before = mp_reg.find_mapping(type(mb))
     # This registers a representer (factory) for the member and finds
     # the previously created mapping for the member.
     as_representer(mb, CsvMime)
     mp_after = mp_reg.find_mapping(type(mb))
     self.assert_true(mp_before is mp_after)
Esempio n. 8
0
 def test_configure_with_full_zcml(self):
     reg = self._registry
     # Check adapters.
     ent = FooEntity()
     member = object.__new__(FooMember)
     coll = object.__new__(FooCollection)
     # Make sure no adapters are in the registry.
     self.assert_is_none(
         reg.queryAdapter(coll, IMemberResource, name='member-class'))
     self.assert_is_none(
         reg.queryAdapter(member,
                          ICollectionResource,
                          name='collection-class'))
     self.assert_is_none(
         reg.queryAdapter(member, IEntity, name='entity-class'))
     self.assert_is_none(reg.queryAdapter(ent, IMemberResource))
     self.assert_is_none(
         reg.queryAdapter(coll, IRepresenter,
                          name=CsvMime.mime_type_string))
     # Load the configuration.
     config = Configurator(registry=reg, package=package)
     config.load_zcml('everest.tests.simple_app:configure.zcml')
     self.__check(reg, member, ent, coll)
     rpr = as_representer(coll, CsvMime)
     self.assert_true(isinstance(rpr, Representer))
Esempio n. 9
0
 def test_invalid_xml(self):
     coll = object.__new__(get_collection_class(IMyEntity))
     rpr = as_representer(coll, XmlMime)
     with self.assert_raises(SyntaxError) as cm:
         rpr.from_string('<?xml version="1.0" encoding="UTF-8"?><murks/>')
     exc_msg = 'Could not parse XML document for schema'
     self.assert_not_equal(cm.exception.message.find(exc_msg), -1)
Esempio n. 10
0
 def _upload_metadata(self, xls_filename, scenario, app):
     # First, create a new metadata entity and POST it.
     emd_coll = create_staging_collection(IExperimentMetadata)
     emd = ExperimentMetadata('unit_test_metadata',
                              next(iter(get_root_aggregate(ISubproject))),
                              1,
                              get_experiment_metadata_type(scenario)
                              )
     mb_emd = emd_coll.create_member(emd)
     rpr = as_representer(mb_emd, XmlMime)
     emd_rpr = rpr.to_string(mb_emd)
     res = app.post("/%s" % emd_coll.__name__,
                    params=emd_rpr,
                    content_type=XmlMime.mime_type_string,
                    status=HTTPCreated.code)
     self.__session.commit()
     mb_url = res.headers['Location']
     # Now, PUT the excel meta data file.
     self.__session.begin_nested()
     with open(xls_filename, 'rb') as xls_file:
         res = app.put(mb_url,
                       params=xls_file.read(),
                       content_type=XlsMime.mime_type_string)
     # If the file had warnings, we have to repeat the PUT.
     if res.status.endswith(HTTPTemporaryRedirect.title):
         self.__session.rollback()
         # 307 Redirect: Repeat with warnings disabled.
         with open(xls_filename, 'rb') as xls_file:
             res = app.put(res.headers['Location'],
                           params=xls_file.read(),
                           content_type=XlsMime.mime_type_string,
                           status=HTTPOk.code)
     self.__session.commit()
     assert res.status.endswith(HTTPOk.title)
     return mb_url
Esempio n. 11
0
 def test_update_nested_collection_from_data(self, resource_repo):
     # Set up member that has one child.
     coll = resource_repo.get_collection(IMyEntity)
     ent = MyEntity(id=1)
     child0 = MyEntityChild(id=0)
     ent.children.append(child0)
     mb = coll.create_member(ent)
     # Set up another member with two children with different IDs.
     tmp_coll = create_staging_collection(IMyEntity)
     upd_ent = MyEntity(id=1)
     child1 = MyEntityChild(id=1)
     child1.parent = upd_ent
     child2 = MyEntityChild(id=2)
     child2.parent = upd_ent
     upd_ent.children.append(child1)
     upd_ent.children.append(child2)
     upd_mb = tmp_coll.create_member(upd_ent)
     rpr = as_representer(mb, CsvMime)
     attribute_options = {
         ('children', ): {
             IGNORE_OPTION: False,
             WRITE_AS_LINK_OPTION: False
         },
     }
     with rpr.with_updated_configuration(
             attribute_options=attribute_options):
         de = rpr.resource_to_data(upd_mb)
         mb.update(de)
         assert set([mb.id for mb in mb.children]) == set([1, 2])
Esempio n. 12
0
 def test_invalid_xml(self):
     coll = object.__new__(get_collection_class(IMyEntity))
     rpr = as_representer(coll, XmlMime)
     with self.assert_raises(SyntaxError) as cm:
         rpr.from_string('<?xml version="1.0" encoding="UTF-8"?><murks/>')
     exc_msg = 'Could not parse XML document for schema'
     self.assert_not_equal(cm.exception.message.find(exc_msg), -1)
Esempio n. 13
0
 def _get_response_representer(self):
     """
     Creates a representer for this view.
     
     :raises: :class:`pyramid.httpexceptions.HTTPNotAcceptable` if the
       MIME content type(s) the client specified can not be handled by 
       the view.
     :returns: :class:`everest.representers.base.ResourceRepresenter`
     """
     view_name = self.request.view_name
     if view_name != '':
         mime_type = get_registered_mime_type_for_name(view_name)
         rpr = as_representer(self.context, mime_type)
     else:
         mime_type = None
         acc = None
         for acc in self.request.accept:
             if acc == '*/*':
                 # The client does not care; use the default.
                 mime_type = self.__get_default_response_mime_type()
                 break
             try:
                 mime_type = \
                         get_registered_mime_type_for_string(acc.lower())
             except KeyError:
                 pass
             else:
                 break
         if mime_type is None:
             if not acc is None:
                 # The client specified a MIME type we can not handle; this
                 # is a 406 exxception. We supply allowed MIME content
                 # types in the body of the response.
                 headers = \
                     [('Location', self.request.path_url),
                      ('Content-Type', TextPlainMime.mime_type_string),
                      ]
                 mime_strings = get_registered_mime_strings()
                 exc = HTTPNotAcceptable(
                     'Requested MIME content type(s) '
                     'not acceptable.',
                     body=','.join(mime_strings),
                     headers=headers)
                 raise exc
             mime_type = self.__get_default_response_mime_type()
         rpr = as_representer(self.context, mime_type)
     return rpr
Esempio n. 14
0
    def _get_response_representer(self):
        """
        Creates a representer for this view.

        :returns: :class:`everest.representers.base.ResourceRepresenter`
        """
        mime_type = self._get_response_mime_type()
        return as_representer(self.context, mime_type)
Esempio n. 15
0
 def __call__(self, value, system):
     context = value.get('context', system.get('context'))
     if not self._validate(context):
         raise ValueError('Invalid representation.')
     self._prepare_response(system)
     # Assemble response.
     rpr = as_representer(context, self._content_type)
     return rpr.to_bytes(context)
Esempio n. 16
0
 def __call__(self, value, system):
     context = value.get('context', system.get('context'))
     if not self._validate(context):
         raise ValueError('Invalid representation.')
     self._prepare_response(system)
     # Assemble response.
     rpr = as_representer(context, self._content_type)
     return rpr.to_bytes(context)
Esempio n. 17
0
 def _get_request_representer(self):
     try:
         mime_type = \
           get_registered_mime_type_for_string(self.request.content_type)
     except KeyError:
         # The client requested a content type we do not support (415).
         raise HTTPUnsupportedMediaType()
     return as_representer(self.context, mime_type)
Esempio n. 18
0
 def __call__(self, value, system):
     context = value.get("context", system.get("context"))
     if not self._validate(context):
         raise ValueError("Invalid representation.")
     self._prepare_response(system)
     # Assemble response.
     rpr = as_representer(context, self._content_type)
     return rpr.to_string(context)
Esempio n. 19
0
 def _get_request_representer(self):
     try:
         mime_type = \
           get_registered_mime_type_for_string(self.request.content_type)
     except KeyError:
         # The client requested a content type we do not support (415).
         raise HTTPUnsupportedMediaType()
     return as_representer(self.context, mime_type)
Esempio n. 20
0
 def _get_response_representer(self):
     """
     Creates a representer for this view.
     
     :raises: :class:`pyramid.httpexceptions.HTTPNotAcceptable` if the
       MIME content type(s) the client specified can not be handled by 
       the view.
     :returns: :class:`everest.representers.base.ResourceRepresenter`
     """
     view_name = self.request.view_name
     if view_name != '':
         mime_type = get_registered_mime_type_for_name(view_name)
         rpr = as_representer(self.context, mime_type)
     else:
         mime_type = None
         acc = None
         for acc in self.request.accept:
             if acc == '*/*':
                 # The client does not care; use the default.
                 mime_type = self.__get_default_response_mime_type()
                 break
             try:
                 mime_type = \
                         get_registered_mime_type_for_string(acc.lower())
             except KeyError:
                 pass
             else:
                 break
         if mime_type is None:
             if not acc is None:
                 # The client specified a MIME type we can not handle; this
                 # is a 406 exxception. We supply allowed MIME content
                 # types in the body of the response.
                 headers = \
                     [('Location', self.request.path_url),
                      ('Content-Type', TextPlainMime.mime_type_string),
                      ]
                 mime_strings = get_registered_mime_strings()
                 exc = HTTPNotAcceptable('Requested MIME content type(s) '
                                         'not acceptable.',
                                         body=','.join(mime_strings),
                                         headers=headers)
                 raise exc
             mime_type = self.__get_default_response_mime_type()
         rpr = as_representer(self.context, mime_type)
     return rpr
Esempio n. 21
0
def load_into_collection_from_stream(collection, stream, content_type):
    """
    Loads resources from the given resource data stream (of the specified MIME
    content type) into the given collection resource.
    """
    rpr = as_representer(collection, content_type)
    with stream:
        data_el = rpr.data_from_stream(stream)
    rpr.resource_from_data(data_el, resource=collection)
Esempio n. 22
0
def dump_resource(resource, stream, content_type=None):
    """
    Dumps the given resource to the given stream using the specified MIME
    content type (defaults to CSV).
    """
    if content_type is None:
        content_type = CsvMime
    rpr = as_representer(resource, content_type)
    rpr.to_stream(resource, stream)
Esempio n. 23
0
def load_collection_from_stream(collection_class, stream, content_type):
    """
    Loads resources from the given stream into the given collection resource.
    """
    coll = object.__new__(collection_class)
    rpr = as_representer(coll, content_type)
    with stream:
        data_el = rpr.data_from_stream(stream)
    return rpr.resource_from_data(data_el)
Esempio n. 24
0
def load_into_collection_from_stream(collection, stream, content_type):
    """
    Loads resources from the given resource data stream (of the specified MIME
    content type) into the given collection resource.
    """
    rpr = as_representer(collection, content_type)
    with stream:
        data_el = rpr.data_from_stream(stream)
    rpr.resource_from_data(data_el, resource=collection)
Esempio n. 25
0
def load_collection_from_stream(collection_class, stream, content_type):
    """
    Loads resources from the given stream into the given collection resource.
    """
    coll = object.__new__(collection_class)
    rpr = as_representer(coll, content_type)
    with stream:
        data_el = rpr.data_from_stream(stream)
    return rpr.resource_from_data(data_el)
Esempio n. 26
0
def dump_resource(resource, stream, content_type=None):
    """
    Dumps the given resource to the given stream using the specified MIME
    content type (defaults to CSV).
    """
    if content_type is None:
        content_type = CsvMime
    rpr = as_representer(resource, content_type)
    rpr.to_stream(resource, stream)
Esempio n. 27
0
 def test_configure_rpr_with_zcml(self):
     coll = create_collection()
     rpr = as_representer(coll, CsvMime)
     rpr_str = rpr.to_string(coll)
     lines = rpr_str.split(os.linesep)
     chld_field_idx = lines[0].split(',').index('"children"')
     row_data = lines[1].split(',')
     # Collection should be a link.
     self.assert_not_equal(
         row_data[chld_field_idx].find('my-entities/0/children/'), -1)
Esempio n. 28
0
 def test_post(self, app_mocked_request, rest_cmd):
     cnt_tpe = JsonMime
     post_data = as_representer(rest_cmd, cnt_tpe).to_string(rest_cmd)
     sh_cmd_def_coll = get_root_collection(IShellCommandDefinition)
     assert len(list(sh_cmd_def_coll)) == 0
     app_mocked_request.post(self.commands_path,
                             params=post_data,
                             content_type=cnt_tpe.mime_type_string,
                             status=HTTPCreated.code)
     assert len(list(sh_cmd_def_coll)) == 1
Esempio n. 29
0
 def test_configure_rpr_with_zcml(self):
     coll = create_collection()
     rpr = as_representer(coll, CsvMime)
     rpr_str = rpr.to_string(coll)
     lines = rpr_str.split(os.linesep)
     chld_field_idx = lines[0].split(',').index('"children"')
     row_data = lines[1].split(',')
     # Collection should be a link.
     self.assert_not_equal(
             row_data[chld_field_idx].find('my-entities/0/children/'), -1)
Esempio n. 30
0
 def test_update_collection_from_data_with_id_raises_error(self):
     coll = create_collection()
     rpr = as_representer(coll, CsvMime)
     upd_coll = create_staging_collection(IMyEntity)
     ent = MyEntity(id=2)
     upd_coll.create_member(ent)
     de = rpr.data_from_resource(upd_coll)
     with self.assert_raises(ValueError) as cm:
         coll.update_from_data(de)
     exc_msg = 'New member data should not provide an ID attribute.'
     self.assert_equal(cm.exception.message, exc_msg)
Esempio n. 31
0
    def _get_response_representer(self, resource):
        """
        Creates a representer for this view.

        :param resource: Resource to obtain a representer for.
        :type resource: Object implementing
          :class:`evererst.interfaces.IResource`.
        :returns: :class:`everest.representers.base.ResourceRepresenter`
        """
        mime_type = self._get_response_mime_type()
        return as_representer(resource, mime_type)
Esempio n. 32
0
 def test_update_collection_from_data_with_id_raises_error(self):
     coll = create_collection()
     rpr = as_representer(coll, CsvMime)
     upd_coll = create_staging_collection(IMyEntity)
     ent = MyEntity(id=2)
     upd_coll.create_member(ent)
     de = rpr.data_from_resource(upd_coll)
     with self.assert_raises(ValueError) as cm:
         coll.update_from_data(de)
     exc_msg = 'New member data should not provide an ID attribute.'
     self.assert_equal(cm.exception.message, exc_msg)
Esempio n. 33
0
 def __make_accept_iso_request_patch_representation(self, iso_request):
     new_owner = 'thelma, stockmanagement'
     isor = iso_request.get_entity()
     old_owner = isor.owner
     isor.owner = new_owner
     rpr = as_representer(iso_request, XmlMime)
     with self.__get_patch_context(iso_request, ('owner',)):
         rpr_str = rpr.to_string(iso_request)
     isor.owner = old_owner
     assert isor.owner == old_owner
     return rpr_str
Esempio n. 34
0
 def __make_accept_iso_request_patch_representation(self, iso_request):
     new_owner = 'thelma, stockmanagement'
     isor = iso_request.get_entity()
     old_owner = isor.owner
     isor.owner = new_owner
     rpr = as_representer(iso_request, XmlMime)
     with self.__get_patch_context(iso_request, ('owner', )):
         rpr_str = rpr.to_string(iso_request)
     isor.owner = old_owner
     assert isor.owner == old_owner
     return rpr_str
Esempio n. 35
0
    def _get_response_representer(self, resource):
        """
        Creates a representer for this view.

        :param resource: Resource to obtain a representer for.
        :type resource: Object implementing
          :class:`evererst.interfaces.IResource`.
        :returns: :class:`everest.representers.base.ResourceRepresenter`
        """
        mime_type = self._get_response_mime_type()
        return as_representer(resource, mime_type)
Esempio n. 36
0
 def __make_transfer_to_patch_representation(self, iso_request, attribute):
     # This creates a representation with all isos or iso
     isor_ent = iso_request.get_entity()
     # FIXME: The status should be part of the ISO_STATUS const group.
     for ent in getattr(isor_ent, attribute):
         ent.status = 'PIPETTING'
     rpr = as_representer(iso_request, XmlMime)
     patch_ctxt = self.__get_patch_context(
         iso_request, (attribute, (attribute, 'status'), (attribute, 'id')))
     with patch_ctxt:
         rpr_str = rpr.to_string(iso_request)
     return rpr_str
 def test_non_existing_attribute_fails(self):
     root_coll = get_root_collection(IMyEntity)
     ent = MyEntity(id=1)
     mb = root_coll.create_member(ent)
     rpr = as_representer(mb, CsvMime)
     attr_name = 'invalid'
     attribute_options = {(attr_name,):{IGNORE_OPTION:False,
                                        WRITE_AS_LINK_OPTION:True}}
     with self.assert_raises(AttributeError) as cm:
         rpr.configure(attribute_options=attribute_options)
     msg = 'Trying to configure non-existing resource attribute "%s"' \
           % attr_name
     self.assert_equal(str(cm.exception)[:len(msg)], msg)
Esempio n. 38
0
 def _data_callback(cls, value, options):
     # Set the default for the report directory.
     if options.report_directory is None:
         options.report_directory = os.path.dirname(value)
     coll_cls = get_collection_class(cls.registration_resource)
     rpr = as_representer(object.__new__(coll_cls), JsonMime)
     reg_items = rpr.from_stream(open(value, 'rU'))
     # FIXME: This should be treated properly in everest.
     if IMemberResource in provided_by(reg_items):
         ents = [reg_items.get_entity()]
     else:
         ents = [rc.get_entity() for rc in reg_items]
     return ents
Esempio n. 39
0
 def _data_callback(cls, value, options):
     # Set the default for the report directory.
     if options.report_directory is None:
         options.report_directory = os.path.dirname(value)
     coll_cls = get_collection_class(cls.registration_resource)
     rpr = as_representer(object.__new__(coll_cls), JsonMime)
     reg_items = rpr.from_stream(open(value, 'rU'))
     # FIXME: This should be treated properly in everest.
     if IMemberResource in provided_by(reg_items):
         ents = [reg_items.get_entity()]
     else:
         ents = [rc.get_entity() for rc in reg_items]
     return ents
Esempio n. 40
0
 def test_non_existing_attribute_fails(self, resource_repo):
     coll = resource_repo.get_collection(IMyEntity)
     ent = MyEntity(id=1)
     mb = coll.create_member(ent)
     rpr = as_representer(mb, CsvMime)
     attr_name = 'invalid'
     attribute_options = {(attr_name,):{IGNORE_OPTION:False,
                                        WRITE_AS_LINK_OPTION:True}}
     with pytest.raises(AttributeError) as cm:
         with rpr.with_updated_configuration():
             rpr.configure(attribute_options=attribute_options)
     msg = 'Trying to configure non-existing resource attribute "%s"' \
           % attr_name
     assert str(cm.value)[:len(msg)] == msg
Esempio n. 41
0
    def _get_request_representer(self):
        """
        Returns a representer for the content type specified in the request.

        :raises HTTPUnsupportedMediaType: If the specified content type is
          not supported.
        """
        try:
            mime_type = \
              get_registered_mime_type_for_string(self.request.content_type)
        except KeyError:
            # The client sent a content type we do not support (415).
            raise HTTPUnsupportedMediaType()
        return as_representer(self.context, mime_type)
Esempio n. 42
0
 def test_update_nested_member_from_data(self):
     # Set up member that does not have a parent.
     ent = MyEntity(id=1)
     mb = MyEntityMember.create_from_entity(ent)
     # Set up second member with same ID that does have a parent.
     parent = MyEntityParent(id=0)
     upd_ent = MyEntity(id=1, parent=parent)
     upd_mb = MyEntityMember.create_from_entity(upd_ent)
     rpr = as_representer(mb, CsvMime)
     attribute_options = {('parent',):{WRITE_AS_LINK_OPTION:False}, }
     rpr.configure(attribute_options=attribute_options)
     de = rpr.data_from_resource(upd_mb)
     mb.update_from_data(de)
     self.assert_equal(mb.parent.id, parent.id)
Esempio n. 43
0
    def _get_request_representer(self):
        """
        Returns a representer for the content type specified in the request.

        :raises HTTPUnsupportedMediaType: If the specified content type is
          not supported.
        """
        try:
            mime_type = \
              get_registered_mime_type_for_string(self.request.content_type)
        except KeyError:
            # The client sent a content type we do not support (415).
            raise HTTPUnsupportedMediaType()
        return as_representer(self.context, mime_type)
 def test_xml_roundtrip(self):
     coll = create_collection()
     rpr = as_representer(coll, XmlMime)
     attribute_options = \
             {('text_rc',):{IGNORE_OPTION:True},
              ('parent_text',):{IGNORE_OPTION:True},
              ('children',):{IGNORE_OPTION:False,
                             WRITE_AS_LINK_OPTION:True},
              }
     rpr.configure(attribute_options=attribute_options)
     data = rpr.data_from_resource(coll)
     self.assert_equal(len(data), 2)
     rpr_str = rpr.string_from_data(data)
     reloaded_coll = rpr.from_string(rpr_str)
     self.assert_equal(len(reloaded_coll), 2)
Esempio n. 45
0
 def __make_generate_isos_patch_representation(self, iso_request):
     isor = iso_request.get_entity()
     # FIXME: The status should be part of the ISO_STATUS const group.
     iso = LabIso('NEW ISO',
                  0,
                  RackLayout(shape=get_96_rack_shape()),
                  iso_request=isor,
                  status='NEW')
     isor.isos.append(iso)
     rpr = as_representer(iso_request, XmlMime)
     patch_ctxt = self.__get_patch_context(iso_request,
                                           ('isos', ('isos', 'status')))
     with patch_ctxt:
         rpr_str = rpr.to_string(iso_request)
     return rpr_str
Esempio n. 46
0
 def __make_generate_isos_patch_representation(self, iso_request):
     isor = iso_request.get_entity()
     # FIXME: The status should be part of the ISO_STATUS const group.
     iso = LabIso('NEW ISO',
                  0,
                  RackLayout(shape=get_96_rack_shape()),
                  iso_request=isor,
                  status='NEW')
     isor.isos.append(iso)
     rpr = as_representer(iso_request, XmlMime)
     patch_ctxt = self.__get_patch_context(iso_request,
                                           ('isos', ('isos', 'status')))
     with patch_ctxt:
         rpr_str = rpr.to_string(iso_request)
     return rpr_str
Esempio n. 47
0
 def test_xml_roundtrip(self):
     coll = create_collection()
     rpr = as_representer(coll, XmlMime)
     attribute_options = \
             {('nested_parent',):{IGNORE_OPTION:True},
              ('text_rc',):{IGNORE_OPTION:True},
              ('parent_text',):{IGNORE_OPTION:True},
              ('children',):{IGNORE_OPTION:False,
                             WRITE_AS_LINK_OPTION:True},
              }
     rpr.configure(attribute_options=attribute_options)
     data = rpr.data_from_resource(coll)
     self.assert_equal(len(data), 2)
     rpr_str = rpr.representation_from_data(data)
     reloaded_coll = rpr.from_string(rpr_str)
     self.assert_equal(len(reloaded_coll), 2)
Esempio n. 48
0
 def __make_transfer_to_patch_representation(self, iso_request,
                                             attribute):
     # This creates a representation with all isos or iso
     isor_ent = iso_request.get_entity()
     # FIXME: The status should be part of the ISO_STATUS const group.
     for ent in getattr(isor_ent, attribute):
         ent.status = 'PIPETTING'
     rpr = as_representer(iso_request, XmlMime)
     patch_ctxt = self.__get_patch_context(iso_request,
                                           (attribute,
                                            (attribute, 'status'),
                                            (attribute, 'id')
                                            )
                                           )
     with patch_ctxt:
         rpr_str = rpr.to_string(iso_request)
     return rpr_str
Esempio n. 49
0
 def test_update_nested_member_from_data(self, resource_repo):
     # Set up member that does not have a parent.
     coll = resource_repo.get_collection(IMyEntity)
     ent = MyEntity(id=1)
     mb = coll.create_member(ent)
     # Set up second member with same ID that does have a parent.
     tmp_coll = create_staging_collection(IMyEntity)
     parent = MyEntityParent(id=0)
     upd_ent = MyEntity(id=1, parent=parent)
     upd_mb = tmp_coll.create_member(upd_ent)
     rpr = as_representer(mb, CsvMime)
     attribute_options = {('parent', ): {WRITE_AS_LINK_OPTION: False}}
     with rpr.with_updated_configuration(
             attribute_options=attribute_options):
         de = rpr.resource_to_data(upd_mb)
         mb.update(de)
         assert mb.parent.id == parent.id
Esempio n. 50
0
 def test_update_nested_member_from_data(self, resource_repo):
     # Set up member that does not have a parent.
     coll = resource_repo.get_collection(IMyEntity)
     ent = MyEntity(id=1)
     mb = coll.create_member(ent)
     # Set up second member with same ID that does have a parent.
     tmp_coll = create_staging_collection(IMyEntity)
     parent = MyEntityParent(id=0)
     upd_ent = MyEntity(id=1, parent=parent)
     upd_mb = tmp_coll.create_member(upd_ent)
     rpr = as_representer(mb, CsvMime)
     attribute_options = {('parent',):{WRITE_AS_LINK_OPTION:False}}
     with rpr.with_updated_configuration(attribute_options=
                                             attribute_options):
         de = rpr.resource_to_data(upd_mb)
         mb.update(de)
         assert mb.parent.id == parent.id
Esempio n. 51
0
 def test_non_existing_attribute_fails(self, resource_repo):
     coll = resource_repo.get_collection(IMyEntity)
     ent = MyEntity(id=1)
     mb = coll.create_member(ent)
     rpr = as_representer(mb, CsvMime)
     attr_name = 'invalid'
     attribute_options = {
         (attr_name, ): {
             IGNORE_OPTION: False,
             WRITE_AS_LINK_OPTION: True
         }
     }
     with pytest.raises(AttributeError) as cm:
         with rpr.with_updated_configuration():
             rpr.configure(attribute_options=attribute_options)
     msg = 'Trying to configure non-existing resource attribute "%s"' \
           % attr_name
     assert str(cm.value)[:len(msg)] == msg
Esempio n. 52
0
 def test_update_nested_member_from_data(self):
     # Set up member that does not have a parent.
     ent = MyEntity(id=1)
     mb = MyEntityMember.create_from_entity(ent)
     # Set up second member with same ID that does have a parent.
     parent = MyEntityParent(id=0)
     upd_ent = MyEntity(id=1, parent=parent)
     upd_mb = MyEntityMember.create_from_entity(upd_ent)
     rpr = as_representer(mb, CsvMime)
     attribute_options = {
         ('parent', ): {
             WRITE_AS_LINK_OPTION: False
         },
     }
     rpr.configure(attribute_options=attribute_options)
     de = rpr.data_from_resource(upd_mb)
     mb.update_from_data(de)
     self.assert_equal(mb.parent.id, parent.id)
Esempio n. 53
0
 def test_configure_with_full_zcml(self):
     reg = self._registry
     # Check adapters.
     ent = FooEntity()
     member = object.__new__(FooMember)
     coll = object.__new__(FooCollection)
     # Make sure no adapters are in the registry.
     self.assert_is_none(reg.queryAdapter(coll, IMemberResource,
                                       name='member-class'))
     self.assert_is_none(reg.queryAdapter(member, ICollectionResource,
                                       name='collection-class'))
     self.assert_is_none(reg.queryAdapter(member, IEntity,
                                       name='entity-class'))
     self.assert_is_none(reg.queryAdapter(ent, IMemberResource))
     self.assert_is_none(reg.queryAdapter(coll, IRepresenter,
                                       name=CsvMime.mime_type_string))
     # Load the configuration.
     config = Configurator(registry=reg, package=package)
     config.load_zcml('everest.tests.simple_app:configure.zcml')
     self.__check(reg, member, ent, coll)
     rpr = as_representer(coll, CsvMime)
     self.assert_true(isinstance(rpr, Representer))
Esempio n. 54
0
def member_representer(request, member): # pylint: disable=W0621
    cnt_type = request.cls.content_type
    return as_representer(member, cnt_type)
Esempio n. 55
0
 def _test(rc):
     rpr = as_representer(rc, AtomMime)
     rpr_str = rpr.to_string(rc)
     self.assert_not_equal(
         rpr_str.find('<feed xmlns:ent="http://xml.test.org/tests"'),
         -1)
Esempio n. 56
0
 def test_atom_member(self):
     mb = iter(create_collection()).next()
     rpr = as_representer(mb, AtomMime)
     rpr_str = rpr.to_string(mb)
     self.assert_not_equal(
         rpr_str.find('<entry xmlns:ent="http://xml.test.org/tests"'), -1)
Esempio n. 57
0
def representer(request, collection):  # pylint: disable=W0621
    cnt_type = request.cls.content_type
    return as_representer(collection, cnt_type)
Esempio n. 58
0
def member_representer(request, member):  # pylint: disable=W0621
    cnt_type = request.cls.content_type
    return as_representer(member, cnt_type)
Esempio n. 59
0
def member_representer(request, member):
    cnt_type = request.cls.content_type
    return as_representer(member, cnt_type)
Esempio n. 60
0
def representer(request, collection):
    cnt_type = request.cls.content_type
    return as_representer(collection, cnt_type)