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 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_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)
class Test_copy_dir(unittest.TestCase): 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 tearDown(self): import shutil shutil.rmtree(self.dirname, ignore_errors=True) self.out.close() def _callFUT(self, *arg, **kw): kw['out_'] = self.out from pyramid.scaffolds.copydir import copy_dir return copy_dir(*arg, **kw) def test_copy_source_as_pkg_resource(self): vars = {'package':'mypackage'} self._callFUT(self.fixturetuple, self.dirname, vars, 1, False, template_renderer=dummy_template_renderer) result = self.out.getvalue() self.assertTrue('Creating %s/mypackage/' % self.dirname in result) self.assertTrue( 'Copying fixture_scaffold/+package+/__init__.py_tmpl to' in result) source = pkg_resources.resource_filename( 'pyramid.tests.test_scaffolds', 'fixture_scaffold/+package+/__init__.py_tmpl') target = os.path.join(self.dirname, 'mypackage', '__init__.py') with open(target, 'r') as f: tcontent = f.read() with open(source, 'r') as f: scontent = f.read() self.assertEqual(scontent, tcontent) def test_copy_source_as_dirname(self): vars = {'package':'mypackage'} source = pkg_resources.resource_filename(*self.fixturetuple) self._callFUT(source, self.dirname, vars, 1, False, template_renderer=dummy_template_renderer) result = self.out.getvalue() self.assertTrue('Creating %s/mypackage/' % self.dirname in result) self.assertTrue('Copying __init__.py_tmpl to' in result) source = pkg_resources.resource_filename( 'pyramid.tests.test_scaffolds', 'fixture_scaffold/+package+/__init__.py_tmpl') target = os.path.join(self.dirname, 'mypackage', '__init__.py') with open(target, 'r') as f: tcontent = f.read() with open(source, 'r') as f: scontent = f.read() self.assertEqual(scontent, tcontent)
def to_string(self, obj): """ Converts the given resource to a string representation and returns it. """ stream = NativeIO() self.to_stream(obj, stream) return stream.getvalue()
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 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)
class TestPServeCommand(unittest.TestCase): def setUp(self): from pyramid.compat import NativeIO self.out_ = NativeIO() def out(self, msg): self.out_.write(msg) def _get_server(*args, **kwargs): def server(app): return '' return server def _getTargetClass(self): from pyramid.scripts.pserve import PServeCommand return PServeCommand def _makeOne(self, *args): effargs = ['pserve'] effargs.extend(args) cmd = self._getTargetClass()(effargs) cmd.out = self.out return cmd def test_run_no_args(self): inst = self._makeOne() result = inst.run() self.assertEqual(result, 2) self.assertEqual(self.out_.getvalue(), 'You must give a config file') def test_get_options_no_command(self): inst = self._makeOne() inst.args = ['foo', 'a=1', 'b=2'] result = inst.get_options() self.assertEqual(result, {'a': '1', 'b': '2'}) def test_parse_vars_good(self): from pyramid.tests.test_scripts.dummy import DummyApp inst = self._makeOne('development.ini', 'a=1', 'b=2') inst.loadserver = self._get_server app = DummyApp() def get_app(*args, **kwargs): app.global_conf = kwargs.get('global_conf', None) inst.loadapp = get_app inst.run() self.assertEqual(app.global_conf, {'a': '1', 'b': '2'}) def test_parse_vars_bad(self): inst = self._makeOne('development.ini', 'a') inst.loadserver = self._get_server self.assertRaises(ValueError, inst.run)
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 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 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 string_from_data(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 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(), key = lambda item: item[1].__title__) for name, group in groups: if section and name != section: continue print ('') title = group.__title__ or name print (grpTitleWrap.fill('{0} ({1})'.format(title, name))) 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 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 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 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 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 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 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 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 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_no_params(self, m_bs): m_bs.return_value = { 'registry': self.registry, 'request': self.request} sys.argv[:] = ['amdjs', 'pyramid_amdjs.ini'] stdout = sys.stdout out = NativeIO() sys.stdout = out amd.main() sys.stdout = stdout val = out.getvalue() self.assertIn('[-h] [-b] [-m] [--deps] [--no-min] config', 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 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
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 test_no_params(self, m_bs): m_bs.return_value = { 'registry': self.registry, 'request': self.request } sys.argv[:] = ['amdjs', 'pyramid_amdjs.ini'] stdout = sys.stdout out = NativeIO() sys.stdout = out amd.main() sys.stdout = stdout val = out.getvalue() self.assertIn('[-h] [-b] [-m] [--deps] [--no-min] config', val)
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 __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 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 _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 _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 extract(self): value = self.params.get(self.name, null) if hasattr(value, "file"): value.file.seek(0) return {"fp": value.file, "filename": value.filename, "mimetype": value.type, "size": value.length} elif value: if not PY3 and isinstance(value, text_type): value = value.encode("latin1") fp = NativeIO(value) fp.filename = self.params.get("%s-filename" % self.name, "") return { "fp": fp, "filename": self.params.get("%s-filename" % self.name, ""), "mimetype": self.params.get("%s-mimetype" % self.name, ""), "size": len(value), } return null
def extract(self): value = self.params.get(self.name, null) if hasattr(value, 'file'): value.file.seek(0) return { 'fp': value.file, 'filename': value.filename, 'mimetype': value.type, 'size': value.length} elif value: fp = NativeIO(value) fp.filename = self.params.get('%s-filename'%self.name, '') return { 'fp': fp, 'filename': self.params.get('%s-filename'%self.name, ''), 'mimetype': self.params.get('%s-mimetype'%self.name, ''), 'size': len(value)} return null
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 test_list_modules(self, m_bs): m_bs.return_value = { 'registry': self.registry, 'request': self.request} self.config.add_amd_js( 'test', 'pyramid_amdjs:tests/dir/test.js', 'Test module') sys.argv[1:] = ['-m', 'pyramid_amdjs.ini'] stdout = sys.stdout out = NativeIO() sys.stdout = out amd.main() sys.stdout = stdout val = out.getvalue() self.assertIn('* test: pyramid_amdjs:tests/dir/test.js', val) self.assertIn('Test module', val)
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 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_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_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_populate_list(self): def step(registry): """ """ self.config.ptah_populate_step('custom-step', title='Custom step', active=False, factory=step) sys.argv[:] = ['ptah-populate', 'ptah.ini', '-l'] stdout = sys.stdout out = NativeIO() sys.stdout = out populate.main() sys.stdout = stdout val = out.getvalue() self.assertIn('* custom-step: Custom step (inactive)', val)
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 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_populate_list(self): def step(registry): """ """ self.config.ptah_populate_step( 'custom-step', title='Custom step', active=False, factory=step) sys.argv[:] = ['ptah-populate', 'ptah.ini', '-l'] stdout = sys.stdout out = NativeIO() sys.stdout = out populate.main() sys.stdout = stdout val = out.getvalue() self.assertIn('* custom-step: Custom step (inactive)', 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 extract(self, default=null): value = self.params.get(self.name, default) if hasattr(value, 'file'): return { 'fp': value.file, 'filename': value.filename, 'mimetype': value.type, 'size': value.length} elif value: if not PY3 and isinstance(value, text_type): value = value.encode('latin1') fp = NativeIO(value) fp.filename = self.params.get('%s-filename'%self.name, '') return { 'fp': fp, 'filename': self.params.get('%s-filename'%self.name, ''), 'mimetype': self.params.get('%s-mimetype'%self.name, ''), 'size': len(value)} return default
class TestPServeCommand(unittest.TestCase): def setUp(self): from pyramid.compat import NativeIO self.out_ = NativeIO() def out(self, msg): self.out_.write(msg) def _getTargetClass(self): from pyramid.scripts.pserve import PServeCommand return PServeCommand def _makeOne(self, *args): effargs = ['pserve'] effargs.extend(args) cmd = self._getTargetClass()(effargs) cmd.out = self.out return cmd def test_run_no_args(self): inst = self._makeOne() result = inst.run() self.assertEqual(result, 2) self.assertEqual(self.out_.getvalue(), 'You must give a config file') def test_run_stop_daemon_no_such_pid_file(self): path = os.path.join(os.path.dirname(__file__), 'wontexist.pid') inst = self._makeOne('--stop-daemon', '--pid-file=%s' % path) inst.run() self.assertEqual(self.out_.getvalue(),'No PID file exists in %s' % path) def test_run_stop_daemon_bad_pid_file(self): path = __file__ inst = self._makeOne('--stop-daemon', '--pid-file=%s' % path) inst.run() self.assertEqual( self.out_.getvalue(),'Not a valid PID file in %s' % path) def test_run_stop_daemon_invalid_pid_in_file(self): fn = tempfile.mktemp() with open(fn, 'wb') as tmp: tmp.write(b'9999999') tmp.close() inst = self._makeOne('--stop-daemon', '--pid-file=%s' % fn) inst.run() self.assertEqual(self.out_.getvalue(), 'PID in %s is not valid (deleting)' % fn) def test_parse_vars_good(self): vars = ['a=1', 'b=2'] inst = self._makeOne('development.ini') result = inst.parse_vars(vars) self.assertEqual(result, {'a': '1', 'b': '2'}) def test_parse_vars_bad(self): vars = ['a'] inst = self._makeOne('development.ini') self.assertRaises(ValueError, inst.parse_vars, vars)
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)
class TestPServeCommand(unittest.TestCase): def setUp(self): from pyramid.compat import NativeIO self.out_ = NativeIO() self.pid_file = None def tearDown(self): if self.pid_file and os.path.exists(self.pid_file): os.remove(self.pid_file) def out(self, msg): self.out_.write(msg) def _get_server(*args, **kwargs): def server(app): return '' return server def _getTargetClass(self): from pyramid.scripts.pserve import PServeCommand return PServeCommand def _makeOne(self, *args): effargs = ['pserve'] effargs.extend(args) cmd = self._getTargetClass()(effargs) cmd.out = self.out return cmd def _makeOneWithPidFile(self, pid): self.pid_file = tempfile.mktemp() inst = self._makeOne() with open(self.pid_file, 'w') as f: f.write(str(pid)) return inst def test_remove_pid_file_verbose(self): inst = self._makeOneWithPidFile(os.getpid()) inst._remove_pid_file(os.getpid(), self.pid_file, verbosity=1) self._assert_pid_file_removed(verbose=True) def test_remove_pid_file_not_verbose(self): inst = self._makeOneWithPidFile(os.getpid()) inst._remove_pid_file(os.getpid(), self.pid_file, verbosity=0) self._assert_pid_file_removed(verbose=False) def test_remove_pid_not_a_number(self): inst = self._makeOneWithPidFile('not a number') inst._remove_pid_file(os.getpid(), self.pid_file, verbosity=1) self._assert_pid_file_removed(verbose=True) def test_remove_pid_current_pid_is_not_written_pid(self): inst = self._makeOneWithPidFile(os.getpid()) inst._remove_pid_file('99999', self.pid_file, verbosity=1) self._assert_pid_file_not_removed('') def test_remove_pid_current_pid_is_not_pid_in_file(self): inst = self._makeOneWithPidFile('99999') inst._remove_pid_file(os.getpid(), self.pid_file, verbosity=1) msg = 'PID file %s contains 99999, not expected PID %s' self._assert_pid_file_not_removed(msg % (self.pid_file, os.getpid())) def test_remove_pid_no_pid_file(self): inst = self._makeOne() self.pid_file = 'some unknown path' inst._remove_pid_file(os.getpid(), self.pid_file, verbosity=1) self._assert_pid_file_removed(verbose=False) def test_remove_pid_file_unlink_exception(self): inst = self._makeOneWithPidFile(os.getpid()) self._remove_pid_unlink_exception(inst) msg = [ 'Removing PID file %s' % (self.pid_file), 'Cannot remove PID file: (Some OSError - unlink)', 'Stale PID removed'] self._assert_pid_file_not_removed(msg=''.join(msg)) with open(self.pid_file) as f: self.assertEqual(f.read(), '') def test_remove_pid_file_stale_pid_write_exception(self): inst = self._makeOneWithPidFile(os.getpid()) self._remove_pid_unlink_and_write_exceptions(inst) msg = [ 'Removing PID file %s' % (self.pid_file), 'Cannot remove PID file: (Some OSError - unlink)', 'Stale PID left in file: %s ' % (self.pid_file), '(Some OSError - open)'] self._assert_pid_file_not_removed(msg=''.join(msg)) with open(self.pid_file) as f: self.assertEqual(int(f.read()), os.getpid()) def test_record_pid_verbose(self): self._assert_record_pid(verbosity=2, msg='Writing PID %d to %s') def test_record_pid_not_verbose(self): self._assert_record_pid(verbosity=1, msg='') def _remove_pid_unlink_exception(self, inst): old_unlink = os.unlink def fake_unlink(filename): raise OSError('Some OSError - unlink') try: os.unlink = fake_unlink inst._remove_pid_file(os.getpid(), self.pid_file, verbosity=1) finally: os.unlink = old_unlink def _remove_pid_unlink_and_write_exceptions(self, inst): old_unlink = os.unlink def fake_unlink(filename): raise OSError('Some OSError - unlink') run_already = [] old_open = __builtin__.open def fake_open(*args): if not run_already: run_already.append(True) return old_open(*args) raise OSError('Some OSError - open') try: os.unlink = fake_unlink __builtin__.open = fake_open inst._remove_pid_file(os.getpid(), self.pid_file, verbosity=1) finally: os.unlink = old_unlink __builtin__.open = old_open def _assert_pid_file_removed(self, verbose=False): self.assertFalse(os.path.exists(self.pid_file)) msg = 'Removing PID file %s' % (self.pid_file) if verbose else '' self.assertEqual(self.out_.getvalue(), msg) def _assert_pid_file_not_removed(self, msg): self.assertTrue(os.path.exists(self.pid_file)) self.assertEqual(self.out_.getvalue(), msg) def _assert_record_pid(self, verbosity, msg): old_atexit = atexit.register def fake_atexit(*args): pass self.pid_file = tempfile.mktemp() pid = os.getpid() inst = self._makeOne() inst.options.verbose = verbosity try: atexit.register = fake_atexit inst.record_pid(self.pid_file) finally: atexit.register = old_atexit msg = msg % (pid, self.pid_file) if msg else '' self.assertEqual(self.out_.getvalue(), msg) with open(self.pid_file) as f: self.assertEqual(int(f.read()), pid) def test_run_no_args(self): inst = self._makeOne() result = inst.run() self.assertEqual(result, 2) self.assertEqual(self.out_.getvalue(), 'You must give a config file') def test_run_stop_daemon_no_such_pid_file(self): path = os.path.join(os.path.dirname(__file__), 'wontexist.pid') inst = self._makeOne('--stop-daemon', '--pid-file=%s' % path) inst.run() msg = 'No PID file exists in %s' % path self.assertEqual(self.out_.getvalue(), msg) def test_run_stop_daemon_bad_pid_file(self): path = __file__ inst = self._makeOne('--stop-daemon', '--pid-file=%s' % path) inst.run() msg = 'Not a valid PID file in %s' % path self.assertEqual(self.out_.getvalue(), msg) def test_run_stop_daemon_invalid_pid_in_file(self): fn = tempfile.mktemp() with open(fn, 'wb') as tmp: tmp.write(b'9999999') tmp.close() inst = self._makeOne('--stop-daemon', '--pid-file=%s' % fn) inst.run() msg = 'PID in %s is not valid (deleting)' % fn self.assertEqual(self.out_.getvalue(), msg) def test_get_options_with_command(self): inst = self._makeOne() inst.args = ['foo', 'stop', 'a=1', 'b=2'] result = inst.get_options() self.assertEqual(result, {'a': '1', 'b': '2'}) def test_get_options_no_command(self): inst = self._makeOne() inst.args = ['foo', 'a=1', 'b=2'] result = inst.get_options() self.assertEqual(result, {'a': '1', 'b': '2'}) def test_parse_vars_good(self): from pyramid.tests.test_scripts.dummy import DummyApp inst = self._makeOne('development.ini', 'a=1', 'b=2') inst.loadserver = self._get_server app = DummyApp() def get_app(*args, **kwargs): app.global_conf = kwargs.get('global_conf', None) inst.loadapp = get_app inst.run() self.assertEqual(app.global_conf, {'a': '1', 'b': '2'}) def test_parse_vars_bad(self): inst = self._makeOne('development.ini', 'a') inst.loadserver = self._get_server self.assertRaises(ValueError, inst.run)
def setUp(self): from pyramid.compat import NativeIO self.out_ = NativeIO() self.pid_file = None
class Test_copy_dir(unittest.TestCase): 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 tearDown(self): import shutil shutil.rmtree(self.dirname, ignore_errors=True) self.out.close() def _callFUT(self, *arg, **kw): kw['out_'] = self.out from pyramid.scaffolds.copydir import copy_dir return copy_dir(*arg, **kw) def test_copy_source_as_pkg_resource(self): vars = {'package':'mypackage'} self._callFUT(self.fixturetuple, self.dirname, vars, 1, False, template_renderer=dummy_template_renderer) result = self.out.getvalue() self.assertTrue('Creating %s/mypackage/' % self.dirname in result) self.assertTrue( 'Copying fixture_scaffold/+package+/__init__.py_tmpl to' in result) source = pkg_resources.resource_filename( 'pyramid.tests.test_scaffolds', 'fixture_scaffold/+package+/__init__.py_tmpl') target = os.path.join(self.dirname, 'mypackage', '__init__.py') with open(target, 'r') as f: tcontent = f.read() with open(source, 'r') as f: scontent = f.read() self.assertEqual(scontent, tcontent) def test_copy_source_as_dirname(self): vars = {'package':'mypackage'} source = pkg_resources.resource_filename(*self.fixturetuple) self._callFUT(source, self.dirname, vars, 1, False, template_renderer=dummy_template_renderer) result = self.out.getvalue() self.assertTrue('Creating %s/mypackage/' % self.dirname in result) self.assertTrue('Copying __init__.py_tmpl to' in result) source = pkg_resources.resource_filename( 'pyramid.tests.test_scaffolds', 'fixture_scaffold/+package+/__init__.py_tmpl') target = os.path.join(self.dirname, 'mypackage', '__init__.py') with open(target, 'r') as f: tcontent = f.read() with open(source, 'r') as f: scontent = f.read() self.assertEqual(scontent, tcontent) def test_content_is_same_message(self): vars = {'package':'mypackage'} source = pkg_resources.resource_filename(*self.fixturetuple) self._callFUT(source, self.dirname, vars, 2, False, template_renderer=dummy_template_renderer) self._callFUT(source, self.dirname, vars, 2, False, template_renderer=dummy_template_renderer) result = self.out.getvalue() self.assertTrue('%s already exists (same content)' % \ os.path.join(self.dirname, 'mypackage', '__init__.py') in result) def test_direxists_message(self): vars = {'package':'mypackage'} source = pkg_resources.resource_filename(*self.fixturetuple) # if not os.path.exists(self.dirname): # os.mkdir(self.dirname) self._callFUT(source, self.dirname, vars, 2, False, template_renderer=dummy_template_renderer) result = self.out.getvalue() self.assertTrue('Directory %s exists' % self.dirname in result, result) def test_overwrite_false(self): vars = {'package':'mypackage'} source = pkg_resources.resource_filename(*self.fixturetuple) self._callFUT(source, self.dirname, vars, 1, False, overwrite=False, template_renderer=dummy_template_renderer) target = os.path.join(self.dirname, 'mypackage', '__init__.py') with open(target, 'w') as f: f.write('These are not the words you are looking for.') self._callFUT(source, self.dirname, vars, 1, False, overwrite=False, template_renderer=dummy_template_renderer) def test_detect_SkipTemplate(self): vars = {'package':'mypackage'} source = pkg_resources.resource_filename(*self.fixturetuple) def dummy_template_renderer(*args, **kwargs): from pyramid.scaffolds.copydir import SkipTemplate raise SkipTemplate self._callFUT(source, self.dirname, vars, 1, False, template_renderer=dummy_template_renderer) def test_query_interactive(self): from pyramid.scaffolds import copydir vars = {'package':'mypackage'} source = pkg_resources.resource_filename(*self.fixturetuple) self._callFUT(source, self.dirname, vars, 1, False, overwrite=False, template_renderer=dummy_template_renderer) target = os.path.join(self.dirname, 'mypackage', '__init__.py') with open(target, 'w') as f: f.write('These are not the words you are looking for.') # We need query_interactive to return False in order to force # execution of a branch original_code_object = copydir.query_interactive copydir.query_interactive = lambda *args, **kwargs: False self._callFUT(source, self.dirname, vars, 1, False, interactive=True, overwrite=False, template_renderer=dummy_template_renderer) copydir.query_interactive = original_code_object
def setUp(self): from pyramid.compat import NativeIO self.out_ = NativeIO()
class Test_query_interactive(unittest.TestCase): 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 tearDown(self): import shutil shutil.rmtree(self.dirname, ignore_errors=True) self.out.close() def _callFUT(self, *arg, **kw): from pyramid.scaffolds.copydir import query_interactive return query_interactive(*arg, **kw) def test_query_interactive_0y(self): from pyramid.scaffolds import copydir copydir.input_ = RawInputMockObject("y") self._callFUT(self.src_fn, self.dest_fn, self.src_content, self.dest_content, simulate=False, out_=self.out) self.assertTrue("Replace" in self.out.getvalue()) def test_query_interactive_1n(self): from pyramid.scaffolds import copydir copydir.input_ = RawInputMockObject("n") self._callFUT(self.src_fn, self.dest_fn, self.src_content, '\n'.join(self.dest_content.split('\n')[:-1]), simulate=False, out_=self.out) self.assertTrue("Replace" in self.out.getvalue()) def test_query_interactive_2b(self): from pyramid.scaffolds import copydir copydir.input_ = RawInputMockObject("b") with open(os.path.join( self.dirname, 'mypackage', '__init__.py.bak'), 'w') as fp: fp.write("") fp.close() self._callFUT(self.src_fn, self.dest_fn, self.dest_content, self.src_content, simulate=False, out_=self.out) self.assertTrue("Backing up" in self.out.getvalue()) def test_query_interactive_3d(self): from pyramid.scaffolds import copydir copydir.input_ = RawInputMockObject("d") self._callFUT(self.src_fn, self.dest_fn, self.dest_content, self.src_content, simulate=False, out_=self.out) output = self.out.getvalue() # The useful text in self.out gets wiped out on the second # call to raw_input, otherwise the test could be made # more usefully precise... # print("3d", output) # self.assertTrue("@@" in output, output) self.assertTrue("Replace" in output) def test_query_interactive_4dc(self): from pyramid.scaffolds import copydir copydir.input_ = RawInputMockObject("dc") self._callFUT(self.src_fn, self.dest_fn, self.dest_content, self.src_content, simulate=False, out_=self.out) output = self.out.getvalue() # The useful text in self.out gets wiped out on the second # call to raw_input, otherwise, the test could be made # more usefully precise... # print("4dc", output) # self.assertTrue("***" in output, output) self.assertTrue("Replace" in output) def test_query_interactive_5allbad(self): from pyramid.scaffolds import copydir copydir.input_ = RawInputMockObject("all z") self._callFUT(self.src_fn, self.dest_fn, self.src_content, self.dest_content, simulate=False, out_=self.out) output = self.out.getvalue() # The useful text in self.out gets wiped out on the second # call to raw_input, otherwise the test could be made # more usefully precise... # print("5allbad", output) # self.assertTrue("Responses" in output, output) self.assertTrue("Replace" in output) def test_query_interactive_6all(self): from pyramid.scaffolds import copydir copydir.input_ = RawInputMockObject("all b") self._callFUT(self.src_fn, self.dest_fn, self.src_content, self.dest_content, simulate=False, out_=self.out) output = self.out.getvalue() # The useful text in self.out gets wiped out on the second # call to raw_input, otherwise the test could be made # more usefully precise... # print("6all", output) # self.assertTrue("Responses" in output, output) self.assertTrue("Replace" in output)