def from_wsgi( schema_path: str, app: Any, *, base_url: Optional[str] = None, data_generation_methods: DataGenerationMethodInput = DEFAULT_DATA_GENERATION_METHODS, code_sample_style: str = CodeSampleStyle.default().name, **kwargs: Any, ) -> GraphQLSchema: """Load GraphQL schema from a WSGI app. :param str schema_path: An in-app relative URL to the schema. :param app: A WSGI app instance. :param Optional[str] base_url: Base URL to send requests to. :return: GraphQLSchema """ require_relative_url(schema_path) setup_headers(kwargs) kwargs.setdefault("json", {"query": INTROSPECTION_QUERY}) client = Client(app, WSGIResponse) response = client.post(schema_path, **kwargs) HTTPError.check_response(response, schema_path) return from_dict( raw_schema=response.json["data"], location=schema_path, base_url=base_url, app=app, data_generation_methods=data_generation_methods, code_sample_style=code_sample_style, )
def run(self, args): from IPython.Shell import IPShellEmbed from werkzeug import Client, EnvironBuilder from dextrose.context import Context from dextrose.http import Response app = load_application(args.package, args.environment) environ_builder = EnvironBuilder() environ = environ_builder.get_environ() request = environ_builder.get_request() client = Client(app, Response) with Context(app, environ, request, {}) as context: banner = "Dextrose IPython shell\n%s" % args.package shell = IPShellEmbed( banner=banner, argv=[ '-prompt_in1', '%s> ' % args.package, '-prompt_in2', '%s... ' % (' ' * (len(args.package) - 3)), '-prompt_out', '=> ' ]) shell(global_ns={}, local_ns={ 'app': app, 'environ': environ, 'client': client, 'context': context })
def __call__(self, result=None): """Overriden to create ``self.client`` attribute, an instance of :class:`werkzeug.Client`, which can be used to send virtual requests to the test application. """ self.test_app = test_app() self.client = Client(self.test_app, Response) super(TestCase, self).__call__(result)
def get_test_client(self): """Creates a test client for this application. :returns: A ``werkzeug.Client`` with the WSGI application wrapped for tests. """ from werkzeug import Client return Client(self, self.response_class, use_cookies=True)
def get_test_client(self): """Creates a test client for this application. :return: A ``werkzeug.Client``, which is a :class:`Tipfy` wrapped for tests. """ from werkzeug import Client return Client(self, self.response_class, use_cookies=True)
def setUp(self): from google.appengine.api import memcache memcache.flush_all() s = LazySettings(settings_module='kay.tests.live_settings_settings') app = get_application(settings=s) self.client = Client(app, BaseResponse) live_settings.set("setting.1", "on") live_settings.set("setting.2", "off")
def test_responder(): """Responder decorator""" def foo(environ, start_response): return BaseResponse('Test') client = Client(responder(foo), BaseResponse) response = client.get('/') assert response.status_code == 200 assert response.data == 'Test'
def test_post_without_redirect(self): form = { 'title': 'タイトル1', 'handle': 'ハンドル名1', 'message': 'メッセージ1', } sut = Client(app, Response) actual = sut.post('/', data=form) assert actual.status_code == 303 assert actual.headers['content-type'] == 'text/html; charset=UTF-8' # bottleでredirect()を使った場合、bodyは''になる assert actual.get_data(as_text=True) == ''
def test_cookie(self): form = { 'title': 'タイトル3', 'handle': 'ハンドル名3', 'message': 'メッセージ3', } sut = Client(app, Response) actual = sut.post('/', data=form, follow_redirects=True) print(type(sut.cookie_jar)) #=> <class 'werkzeug.test._TestCookieJar'> actual_cookie = self.get_cookie_value(sut, 'handle') assert actual_cookie == 'ハンドル名3'
def setUp(self): from solace import database, settings, templating from solace.application import application self.__old_settings = dict(settings.__dict__) settings.revert_to_default() settings.DATABASE_URI = 'sqlite:///' + TEST_DATABASE settings.TRACK_QUERIES = True settings.DATABASE_ECHO = False settings.MAIL_LOG_FILE = tempfile.NamedTemporaryFile() database.refresh_engine() database.init() self.client = Client(application, TestResponse) self.is_logged_in = False
def test_multipart(): """Tests multipart parsing against data collected from webbrowsers""" resources = join(dirname(__file__), 'multipart') client = Client(form_data_consumer, Response) repository = [ ('firefox3-2png1txt', '---------------------------186454651713519341951581030105', [ (u'anchor.png', 'file1', 'image/png', 'file1.png'), (u'application_edit.png', 'file2', 'image/png', 'file2.png') ], u'example text'), ('firefox3-2pnglongtext', '---------------------------14904044739787191031754711748', [ (u'accept.png', 'file1', 'image/png', 'file1.png'), (u'add.png', 'file2', 'image/png', 'file2.png') ], u'--long text\r\n--with boundary\r\n--lookalikes--'), ('opera8-2png1txt', '----------zEO9jQKmLc2Cq88c23Dx19', [ (u'arrow_branch.png', 'file1', 'image/png', 'file1.png'), (u'award_star_bronze_1.png', 'file2', 'image/png', 'file2.png') ], u'blafasel öäü'), ('webkit3-2png1txt', '----WebKitFormBoundaryjdSFhcARk8fyGNy6', [ (u'gtk-apply.png', 'file1', 'image/png', 'file1.png'), (u'gtk-no.png', 'file2', 'image/png', 'file2.png') ], u'this is another text with ümläüts'), ('ie6-2png1txt', '---------------------------7d91b03a20128', [ (u'file1.png', 'file1', 'image/x-png', 'file1.png'), (u'file2.png', 'file2', 'image/x-png', 'file2.png') ], u'ie6 sucks :-/') ] for name, boundary, files, text in repository: folder = join(resources, name) data = get_contents(join(folder, 'request.txt')) for filename, field, content_type, fsname in files: response = client.post( '/?object=' + field, data=data, content_type='multipart/form-data; boundary="%s"' % boundary, content_length=len(data)) lines = response.data.split('\n', 3) assert lines[0] == repr(filename) assert lines[1] == repr(field) assert lines[2] == repr(content_type) assert lines[3] == get_contents(join(folder, fsname)) response = client.post( '/?object=text', data=data, content_type='multipart/form-data; boundary="%s"' % boundary, content_length=len(data)) assert response.data == repr(text)
def test_ie7_unc_path(): client = Client(form_data_consumer, Response) data_file = join(dirname(__file__), 'multipart', 'ie7_full_path_request.txt') data = get_contents(data_file) boundary = '---------------------------7da36d1b4a0164' response = client.post('/?object=cb_file_upload_multiple', data=data, content_type='multipart/form-data; boundary="%s"' % boundary, content_length=len(data)) lines = response.data.split('\n', 3) assert lines[0] == repr( u'Sellersburg Town Council Meeting 02-22-2010doc.doc'), lines[0]
def test_get(self): # http://werkzeug.pocoo.org/docs/0.11/test/#werkzeug.test.Client sut = Client(app, Response) actual = sut.get('/') # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.status_code assert actual.status_code == 200 # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.headers assert actual.headers.get('Content-Type') == 'text/html; charset=UTF-8' # デフォルトではバイト文字列になるので、as_text=Trueで文字列化する # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.get_data # ただし、バグがあるので、utf-8以外の文字コードは扱えない(現時点でもcloseしていない) # http://blog.amedama.jp/entry/2016/06/11/225137 # https://github.com/pallets/werkzeug/issues/947 body = actual.get_data(as_text=True) assert 'テスト掲示板' in body
def test_post_with_redirect(self): form = { 'title': 'タイトル2', 'handle': 'ハンドル名2', 'message': 'メッセージ2', } sut = Client(app, Response) # Werkzeugのドキュメントには見当たらなかったが、Flaskと同じようにしたら動作 # http://flask.pocoo.org/docs/0.12/testing/#logging-in-and-out actual = sut.post('/', data=form, follow_redirects=True) assert actual.status_code == 200 assert actual.headers['content-type'] == 'text/html; charset=UTF-8' body = actual.get_data(as_text=True) assert 'テスト掲示板' in body assert 'タイトル2' in body assert 'ハンドル名2' in body assert 'メッセージ2' in body
def command(self): options = self.options c = Client(self.wsgiapp, BaseResponse) if self.args: url = self.args[0] else: url = '/' resp = c.get(url) if options.show_headers and not options.silent: print(resp.status) print(resp.headers) if options.show_body and not options.silent: for respstr in resp.response: if isinstance(respstr, six.binary_type): respstr = respstr.decode() print(respstr)
def from_wsgi(schema_path: str, app: Any, base_url: Optional[str] = None, **kwargs: Any) -> GraphQLSchema: """Load GraphQL schema from a WSGI app. :param str schema_path: An in-app relative URL to the schema. :param app: A WSGI app instance. :param Optional[str] base_url: Base URL to send requests to. :return: GraphQLSchema """ setup_headers(kwargs) kwargs.setdefault("json", {"query": INTROSPECTION_QUERY}) client = Client(app, WSGIResponse) response = client.post(schema_path, **kwargs) HTTPError.check_response(response, schema_path) return from_dict(raw_schema=response.json["data"], location=schema_path, base_url=base_url, app=app)
def setUp(self): apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap() stub = datastore_file_stub.DatastoreFileStub('test', '/dev/null', '/dev/null') apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub) apiproxy_stub_map.apiproxy.RegisterStub( 'user', user_service_stub.UserServiceStub()) apiproxy_stub_map.apiproxy.RegisterStub( 'memcache', memcache_stub.MemcacheServiceStub()) apiproxy_stub_map.apiproxy.RegisterStub( 'urlfetch', urlfetch_stub.URLFetchServiceStub()) s = LazySettings(settings_module='kay.tests.settings') app = get_application(settings=s) self.client = Client(app, BaseResponse) if apiproxy_stub_map.apiproxy\ ._APIProxyStubMap__stub_map.has_key('capability_service'): del(apiproxy_stub_map.apiproxy\ ._APIProxyStubMap__stub_map['capability_service'])
def test(self): """A test client for this application""" from werkzeug import Client return Client(self, self.response_class, use_cookies=True)
def setup_class(cls): cls.app = make_wsgi('Testruns') cls.client = Client(cls.app, BaseResponse)
def test_ie_fixes(): """Test IE fixes.""" @fixers.InternetExplorerFix @Request.application def application(request): response = Response('binary data here', mimetype='application/vnd.ms-excel') response.headers['Vary'] = 'Cookie' response.headers[ 'Content-Disposition'] = 'attachment; filename=foo.xls' return response c = Client(application, Response) response = c.get('/', headers=[ ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)') ]) # IE gets no vary assert response.data == 'binary data here' assert 'vary' not in response.headers assert response.headers[ 'content-disposition'] == 'attachment; filename=foo.xls' assert response.headers['content-type'] == 'application/vnd.ms-excel' # other browsers do c = Client(application, Response) response = c.get('/') assert response.data == 'binary data here' assert 'vary' in response.headers cc = ResponseCacheControl() cc.no_cache = True @fixers.InternetExplorerFix @Request.application def application(request): response = Response('binary data here', mimetype='application/vnd.ms-excel') response.headers['Pragma'] = ', '.join(pragma) response.headers['Cache-Control'] = cc.to_header() response.headers[ 'Content-Disposition'] = 'attachment; filename=foo.xls' return response # IE has no pragma or cache control pragma = ('no-cache', ) c = Client(application, Response) response = c.get('/', headers=[ ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)') ]) assert response.data == 'binary data here' assert 'pragma' not in response.headers assert 'cache-control' not in response.headers assert response.headers[ 'content-disposition'] == 'attachment; filename=foo.xls' # IE has simplified pragma pragma = ('no-cache', 'x-foo') cc.proxy_revalidate = True response = c.get('/', headers=[ ('User-Agent', 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)') ]) assert response.data == 'binary data here' assert response.headers['pragma'] == 'x-foo' assert response.headers['cache-control'] == 'proxy-revalidate' assert response.headers[ 'content-disposition'] == 'attachment; filename=foo.xls' # regular browsers get everything response = c.get('/') assert response.data == 'binary data here' assert response.headers['pragma'] == 'no-cache, x-foo' cc = parse_cache_control_header(response.headers['cache-control'], cls=ResponseCacheControl) assert cc.no_cache assert cc.proxy_revalidate assert response.headers[ 'content-disposition'] == 'attachment; filename=foo.xls'
def setUp(self): s = LazySettings(settings_module='kay.tests.settings') app = get_application(settings=s) self.client = Client(app, BaseResponse)
process = psutil.Process(os.getpid()) with open('./log.txt', 'w+') as fd: mem = process.memory_info().rss app = Flask(__name__) with time_it('create 60000 routes with flask', fd=fd): for i in range(60000): def route(): return str(i) route.__name__ = copy.copy(str(i)) app.route('/<name>/' + str(i))(route) c = Client(app.wsgi_app, Response) with time_it('call route from flask', fd=fd): res = c.get('/hakim/30000') print(res.data) # assert res.data == b'900 route' new_mem = process.memory_info().rss print(new_mem - mem) mem = new_mem router = Router() with time_it('create 60000 routes wsgitools router', fd=fd): for i in range(60000): route_desc = copy.copy(str(i) + ' route')
def test_client(self): """为这个程序创建一个测试客户端。""" from werkzeug import Client return Client(self, self.response_class, use_cookies=True)
def setUp(self): from google.appengine.api import memcache memcache.flush_all() s = LazySettings(settings_module='kay.tests.appstats_settings') app = get_application(settings=s) self.client = Client(app, BaseResponse)
def test_client(self): """Creates a test client for this application. For information about unit testing head over to :ref:`testing`. """ from werkzeug import Client return Client(self, self.response_class, use_cookies=True)
def setUp(self): self.app = make_wsgi2('Testruns') self.client = Client(self.app, BaseResponse)