def test_build_tree(self, m_bs): m_bs.return_value = { 'registry': self.registry, 'request': self.request } sys.argv[1:] = ['--deps', 'pyramid_amdjs.ini'] self.registry[ID_AMD_MODULE] = { 'test': { 'path': 'pyramid_amdjs:tests/dir/test.js' } } self.registry[ID_AMD_SPEC] = {'test': {'test': {}}} out = NativeIO() stdout = sys.stdout sys.stdout = out amd.main() sys.stdout = stdout val = out.getvalue() self.assertIn('* Spec: test', val) self.assertIn('jca', val) self.assertIn('test', val)
def setUp(self): import tempfile from pyramid.compat import NativeIO self.dirname = tempfile.mkdtemp() self.out = NativeIO() self.fixturetuple = ('pyramid.tests.test_scaffolds', 'fixture_scaffold') self.src_content = """\ These are not the droids that you are looking for.""" self.dest_content = """\ These are the droids for whom you are looking; now you have found them.""" self.src_fn = os.path.join(self.dirname, 'mypackage', '__init__.py') self.dest_fn = os.path.join(self.dirname, 'mypackage', '__init__.py') # query_interactive is only normally executed when the destination # is discovered to be already occupied by existing files, so ... # create the required occupancy. from pyramid.scaffolds.copydir import copy_dir copy_dir(self.fixturetuple, self.dirname, {'package': 'mypackage'}, 0, False, template_renderer=dummy_template_renderer)
def test_extract(self): from pyramid_amdjs.handlebars import extract_i18n f = NativeIO('<div>{{#i18n}}Test \n message{{/i18n}}</div>') d = extract_i18n(f, [], [], []) self.assertEqual(d[0], (5, None, text_type('Test \n message'), []))
def from_string(self, string_representation, resource=None): """ Extracts resource data from the given string and converts them to a new resource or updates the given resource from it. """ stream = NativeIO(string_representation) return self.from_stream(stream, resource=resource)
def test_fields_text(self): request = self.make_request() field = self._makeOne('test') field = field.bind(request, '', 'content', {}) field.update() self.assertIs(field.extract(), ptah.form.null) class FileStorage: def __init__(self, fp, filename, mt, s): self.file = fp self.filename = filename self.type = mt self.length = s fs = FileStorage(NativeIO(), 'test.jpg', 'image/jpeg', 1024) field = self._makeOne('test') field = field.bind(request, '', 'content', {'test': fs}) field.update() res = field.extract() self.assertIs(type(res), dict) self.assertEqual(res['filename'], 'test.jpg')
def setUp(self): import tempfile from pyramid.compat import NativeIO self.dirname = tempfile.mkdtemp() self.out = NativeIO() self.fixturetuple = ('pyramid.tests.test_scaffolds', 'fixture_scaffold')
def to_string(self, obj): """ Converts the given resource to a string representation and returns it. """ stream = NativeIO() self.to_stream(obj, stream) return text_(stream.getvalue(), encoding=self.encoding)
def data_from_string(self, text): """ Converts the given text representation to resource data. :returns: object implementing :class:`everest.representers.interfaces.IExplicitDataElement` """ stream = NativeIO(text) return self.data_from_stream(stream)
def Api(request): """ Rest API interface """ response = request.response # authentication by token token = request.environ.get('HTTP_X_AUTH_TOKEN') if token: secret = ptah.get_settings(ptah.CFG_ID_PTAH, request.registry)['secret'] try: timestamp, userid, tokens, user_data = parse_ticket( secret, '%s!' % token, '0.0.0.0') except BadTicket: userid = None if userid: ptah.auth_service.set_userid(userid) # search service and action service = request.matchdict['service'] subpath = request.matchdict['subpath'] if subpath: action = subpath[0] arguments = subpath[1:] if ':' in action: action, arg = action.split(':', 1) arguments = (arg,) + arguments else: action = 'apidoc' arguments = () request.environ['SCRIPT_NAME'] = '/__rest__/%s' % service response.headerslist = {'Content-Type': 'application/json'} # execute action for specific service try: result = config.get_cfg_storage(ID_REST)[service]( request, action, *arguments) except WSGIHTTPException as exc: response.status = exc.status result = {'message': str(exc)} except Exception as exc: response.status = 500 out = NativeIO() traceback.print_exc(file=out) result = {'message': str(exc), 'traceback': out.getvalue()} if isinstance(result, Response): return result response.text = text_( dumps(result, indent=True, default=dthandler), 'utf-8') return response
def get_traceback(): """ Fetches the last traceback from :var:`sys.exc_info` and returns it as a formatted string. :returns: formatted traceback (string) """ buf = NativeIO() traceback.print_exc(file=buf) return buf.getvalue()
def __check_ini_file(cls): if cls.__ini_parser is None: cls.__ini_parser = cls.__make_parser() if cls.ini_file_path is None: # Initialize with empty ini file. strm = NativeIO('[DEFAULT]') cls.__ini_parser.readfp(strm) else: cls.__ini_parser.read(cls.ini_file_path) return cls.__ini_parser
def print_tb(self): if self.isexc and self.exc_value: out = NativeIO() traceback.print_exception(self.exc_type, self.exc_value, self.exc_traceback, file=out) return out.getvalue() else: return self.exc
def test_command_method_options(self): from pyramid.compat import NativeIO command = self._makeOne(['', '--method=OPTIONS', 'development.ini', '/'], [('Content-Type', 'text/html; charset=UTF-8')]) stdin = NativeIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'OPTIONS') self.assertEqual(self._path_info, '/') self.assertEqual(self._out, ['abc'])
def _create_xl20_worklist(self, rc, params, app): params['type'] = 'XL20' params['include_dummy_output'] = 'true' res = app.get("%sworklists.zip" % resource_to_url(rc), params=params, headers=dict(accept=ZipMime.mime_type_string), status=HTTPOk.code) assert not res is None # Extract the dummy output worklist from the returned ZIP file. zip_map = read_zip_archive(NativeIO(res.body)) return zip_map['%s_dummy_xl20_output.tpo' % rc.label]
def _create_processing_worklist(self, rc, params, app): params['type'] = 'PIPETTING' res = app.get( "%sworklists.zip" % resource_to_url(rc), params=params, headers=dict(accept=ZipMime.mime_type_string), # status=HTTPOk.code ) assert not res is None zip_map = read_zip_archive(NativeIO(res.body)) return zip_map
def test_truncating_formatter(self): buf = NativeIO() logger = logging.Logger('test', logging.DEBUG) hdlr = StreamHandler(buf) hdlr.setFormatter(TruncatingFormatter()) logger.addHandler(hdlr) logger.debug('%s', 'X' * 99, extra=dict(output_limit=100)) self.assert_equal(len(buf.getvalue().strip()), 99) buf.seek(0) buf.truncate() logger.debug('%s', 'X' * 101, extra=dict(output_limit=100)) self.assert_equal(len(buf.getvalue().strip()), 100)
def test_command_method_post(self): from pyramid.compat import NativeIO command = self._makeOne(['', '--method=POST', 'development.ini', '/']) stdin = NativeIO() command.stdin = stdin command.run() self.assertEqual(self._environ['CONTENT_LENGTH'], '-1') self.assertEqual(self._environ['wsgi.input'], stdin) self.assertEqual(self._path_info, '/') self.assertEqual(self._spec, 'development.ini') self.assertEqual(self._app_name, None) self.assertEqual(self._out, ['abc'])
def test_command_method_options(self): from pyramid.compat import NativeIO command = self._makeOne( ['', '--method=OPTIONS', 'development.ini', '/']) stdin = NativeIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'OPTIONS') self.assertEqual(self._path_info, '/') self.assertEqual(self._spec, 'development.ini') self.assertEqual(self._app_name, None) self.assertEqual(self._out, ['abc'])
def data_to_string(self, data_element): """ Converts the given data element into a string representation. :param data_element: object implementing :class:`everest.representers.interfaces.IExplicitDataElement` :returns: string representation (using the MIME content type configured for this representer) """ stream = NativeIO() self.data_to_stream(data_element, stream) return stream.getvalue()
def test_validate_max_size(self): request = self.make_request() field = self._makeOne('test', max_size=1) field = field.bind(request, '', 'content', {}) fp = NativeIO(' ') with self.assertRaises(ptah.form.Invalid) as cm: field.validate({'fp': fp}) self.assertEqual('Maximum file size exceeded.', cm.exception.msg)
def test_command_method_patch(self): from pyramid.compat import NativeIO command = self._makeOne(['', '--method=PATCH', 'development.ini', '/'], [('Content-Type', 'text/html; charset=UTF-8')]) stdin = NativeIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'PATCH') self.assertEqual(self._environ['CONTENT_LENGTH'], '-1') self.assertEqual(self._environ['wsgi.input'], stdin) self.assertEqual(self._path_info, '/') self.assertEqual(self._out, ['abc'])
def test_list_models(self): @ptah.tinfo('custom', title='Custom model', description='Custom model description') class CustomModel(object): """ Custom module description """ title = 'Custom Module' self.init_ptah() sys.argv[1:] = ['--list-models', 'ptah.ini'] stdout = sys.stdout out = NativeIO() sys.stdout = out manage.main(False) sys.stdout = stdout val = out.getvalue() self.assertIn('* type:custom: Custom model (disabled: False)', val) self.assertIn('Custom model description', val) self.assertIn('class: CustomModel', val) self.assertIn('module: test_manage', val) # disable cfg = ptah.get_settings(ptah.CFG_ID_PTAH) cfg['disable_models'] = ('type:custom', ) out = NativeIO() sys.stdout = out manage.main(False) sys.stdout = stdout val = out.getvalue() self.assertIn('* type:custom: Custom model (disabled: True)', val)
def test_command_method_propfind(self): from pyramid.compat import NativeIO command = self._makeOne( ['', '--method=PROPFIND', 'development.ini', '/'], [('Content-Type', 'text/html; charset=UTF-8')]) stdin = NativeIO() command.stdin = stdin command.run() self.assertEqual(self._environ['REQUEST_METHOD'], 'PROPFIND') self.assertEqual(self._path_info, '/') self.assertEqual(self._spec, 'development.ini') self.assertEqual(self._app_name, None) self.assertEqual(self._out, ['abc'])
def run(self): # print defaults if self.options.printcfg: data = config.get_cfg_storage(SETTINGS_OB_ID).export(True) parser = configparser.ConfigParser(dict_type=OrderedDict) for key, val in sorted(data.items()): parser.set(configparser.DEFAULTSECT, key, val.replace('%', '%%')) fp = NativeIO() try: parser.write(fp) finally: pass print (fp.getvalue()) return if self.options.all: section = '' else: section = self.options.section # print description groups = sorted(config.get_cfg_storage(ID_SETTINGS_GROUP).items()) for name, group in groups: if section and name != section: continue print ('') title = group.__title__ or name print (grpTitleWrap.fill(title)) if group.__description__: print (grpDescriptionWrap.fill( group.__description__)) print ('') for node in group.__fields__.values(): default = '<required>' if node.required else node.default print (nameWrap.fill( ('%s.%s: %s (%s: %s)' % ( name, node.name, node.title, node.__class__.__name__, default)))) print (nameTitleWrap.fill(node.description)) print ('')
def logstream(self, monkeypatch): """ Patch the root logger to log to an in-memory stream. """ import pyramid_log logstream = NativeIO() root = logging.getLogger() monkeypatch.setattr(root, 'handlers', []) handler = logging.StreamHandler(logstream) fmt = ("%(asctime)s " "%(request.method|-)s %(request.path_qs|-)s : " "%(message)s") formatter = pyramid_log.Formatter(fmt, datefmt="<DATE>") handler.setFormatter(formatter) root.addHandler(handler) return logstream
def test_populate_no_params(self): sys.argv[:] = ['ptah-populate', 'ptah.ini'] stdout = sys.stdout out = NativeIO() sys.stdout = out populate.main() sys.stdout = stdout val = out.getvalue() self.assertIn( 'usage: ptah-populate [-h] [-l] [-a] config [step [step ...]]', val)
def test_manage_no_params(self): self.init_ptah() sys.argv[:] = ['ptah-manage', 'ptah.ini'] stdout = sys.stdout out = NativeIO() sys.stdout = out manage.main(False) sys.stdout = stdout val = out.getvalue() self.assertIn('[-h] [--list-modules] [--list-models] config', val)
def test_list_modules(self): @ptah.manage.module('custom') class CustomModule(ptah.manage.PtahModule): """ Custom module description """ title = 'Custom Module' self.init_ptah() sys.argv[1:] = ['--list-modules', 'ptah.ini'] stdout = sys.stdout out = NativeIO() sys.stdout = out manage.main(False) sys.stdout = stdout val = out.getvalue() self.assertIn('* custom: Custom Module (disabled: False)', val) self.assertIn('Custom module description', val) # disable cfg = ptah.get_settings(ptah.CFG_ID_PTAH) cfg['disable_modules'] = ('custom', ) out = NativeIO() sys.stdout = out manage.main(False) sys.stdout = stdout val = out.getvalue() self.assertIn('* custom: Custom Module (disabled: True)', val)
def data_element_tree_to_string(data_element): """ Creates a string representation of the given data element tree. """ # FIXME: rewrite this as a visitor to use the data element tree traverser. def __dump(data_el, stream, offset): name = data_el.__class__.__name__ stream.write("%s%s" % (' ' * offset, name)) offset += 2 ifcs = provided_by(data_el) if ICollectionDataElement in ifcs: stream.write("[") first_member = True for member_data_el in data_el.get_members(): if first_member: stream.write('%s' % os.linesep + ' ' * offset) first_member = False else: stream.write(',%s' % os.linesep + ' ' * offset) __dump(member_data_el, stream, offset) stream.write("]") else: stream.write("(") if ILinkedDataElement in ifcs: stream.write("url=%s, kind=%s, relation=%s" % (data_el.get_url(), data_el.get_kind(), data_el.get_relation())) else: first_attr = True for attr_name, attr_value in iteritems_(data_el.data): if first_attr: first_attr = False else: stream.write(',%s' % os.linesep + ' ' * (offset + len(name) + 1)) if attr_value is None: continue if not IResourceDataElement in provided_by(attr_value): stream.write("%s=%s" % (attr_name, attr_value)) else: stream.write("%s=" % attr_name) __dump(attr_value, stream, offset) stream.write(')') stream = NativeIO() __dump(data_element, stream, 0) return stream.getvalue()
def to_strings(self, resource): """ Dumps the all resources reachable from the given resource to a map of string representations using the specified content_type (defaults to CSV). :returns: dictionary mapping resource member classes to string representations """ collections = self.__collect(resource) # Build a map of representations. rpr_map = OrderedDict() for (mb_cls, coll) in iteritems_(collections): strm = NativeIO('w') dump_resource(coll, strm, content_type=self.__content_type) rpr_map[mb_cls] = strm.getvalue() return rpr_map