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, )
class TestWSLoader(unittest.TestCase): def setUp(self): app = wsloader.WSLoader(confdir = os.getcwd() + '/conf/') self.client = Client(app, BaseResponse) def test_service_check(self): response = self.client.get("/greeter/service_check") print response.data self.assertEqual(response.status_code, 200) self.assertEqual(response.data, "OK") def test_defaults(self): response = self.client.get("/greeter/say_hello") self.assertEqual(response.status_code, 200) body = json.loads(response.data) self.assertEqual(body['response'], "Hello World!") def test_aliased_class(self): response = self.client.get('/helloworld/say_hello?greeting="Hola"&to_whom="Amigos!"') try: body = json.loads(response.data) except Exception, e: print e print response.data return self.assertEqual(body['response'], "Hola Amigos!")
class TestUserFunctional(unittest.TestCase): def setUp(self): self.app = make_wsgi('Testruns') self.client = Client(self.app, BaseResponse) def tearDown(self): self.client = None self.app = None def test_attr(self): r = self.client.get('/usertests/setfoo') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'foo set') r = self.client.get('/usertests/getfoo') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'barbaz') def test_auth(self): r = self.client.get('/usertests/setauth') self.assertEqual(r.status, '200 OK') r = self.client.get('/usertests/getauth') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'True') def test_perm(self): r = self.client.get('/usertests/addperm') self.assertEqual(r.status, '200 OK') r = self.client.get('/usertests/getperms') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'TrueFalseTrue') def test_clear(self): r = self.client.get('/usertests/clear') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'FalseFalseNone') def test_message(self): r = self.client.get('/usertests/setmsg') self.assertEqual(r.status, '200 OK') r = self.client.get('/usertests/getmsg') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'test: my message') r = self.client.get('/usertests/nomsg') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'0')
class SessionMiddlewareTestCase(GAETestBase): KIND_NAME_UNSWAPPED = False USE_PRODUCTION_STUBS = True CLEANUP_USED_KIND = True def setUp(self): s = LazySettings(settings_module='kay.tests.settings') app = get_application(settings=s) self.client = Client(app, BaseResponse) def tearDown(self): pass def test_countup(self): response = self.client.get('/countup') self.assertEqual(response.status_code, 200) self.assertEqual(response.data, '1') response = self.client.get('/countup') self.assertEqual(response.data, '2') response = self.client.get('/countup') self.assertEqual(response.data, '3') response = self.client.get('/countup') self.assertEqual(response.data, '4') response = self.client.get('/countup') self.assertEqual(response.data, '5')
class TestSession(unittest.TestCase): def setUp(self): self.app = make_wsgi('Testruns') self.client = Client(self.app, BaseResponse) def tearDown(self): self.client = None self.app = None def test_session_persist(self): r = self.client.get('/sessiontests/setfoo') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'foo set') r = self.client.get('/sessiontests/getfoo') self.assertEqual(r.status, '200 OK') self.assertEqual(r.data, b'bar') def test_session_regen_id(self): ta = TestApp(self.app) r = ta.get('/sessiontests/setfoo', status=200) assert r.session['foo'] == 'bar' sid = r.session.id assert sid in r.headers['Set-Cookie'] r = ta.get('/sessiontests/regenid', status=200) assert r.session.id != sid assert r.session.id in r.headers['Set-Cookie'] r = ta.get('/sessiontests/getfoo', status=200) assert r.body == b'bar'
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_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 cookie_handler(client: werkzeug.Client, cookies: Optional[Cookies]) -> Generator[None, None, None]: """Set cookies required for a call.""" if not cookies: yield else: for key, value in cookies.items(): client.set_cookie("localhost", key, value) yield for key in cookies: client.delete_cookie("localhost", key)
class TasksViewTest(unittest.TestCase): def setUp(self): self.c = Client(views.handler, BaseResponse) # clear state views.TASKS = {} views.clients = {} views.subscriptions = {} def test_POST(self): t = models.Task(name='Task1') r = self.c.post(path='/tasks/', headers={'Content-Type':tubes.JSON}, data=t.to_json_str()) # check response self.assertEquals(r.status_code, 201) task = json.loads(r.data) self.assertEquals(task['name'], 'Task1') self.assertTrue('/tasks/0' in r.headers.get('Location')) # back-end task = views.TASKS['0'] self.assertTrue(task != None) self.assertEquals(task.name, 'Task1') def test_PUT(self): views.TASKS['0'] = models.Task() r = self.c.put(path='/tasks/0', headers={'Content-Type':tubes.JSON}, data=models.Task(name='Task_0').to_json_str()) self.assertEquals(r.status_code, 200) # check response task = json.loads(r.data) self.assertEquals(task['name'], 'Task_0') # back-end task = views.TASKS['0'] self.assertEquals(task.name, 'Task_0') def test_DELETE(self): views.TASKS['0'] = models.Task() r = self.c.delete(path='/tasks/0') self.assertEquals(r.status_code, 204) self.assertTrue(views.TASKS.get('0') == None) def test_GET_tasks(self): views.TASKS['0'] = models.Task(name='foo') r = self.c.get(path='/tasks/') self.assertTrue('foo' in r.data) def test_GET_task(self): views.TASKS['0'] = models.Task(name='foo') r = self.c.get(path='/tasks/0') self.assertTrue('foo' in r.data)
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) == ''
class MaintenanceCheckTestCase(unittest.TestCase): 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 tearDown(self): pass def test_success(self): """Test with normal CapabilityServiceStub""" apiproxy_stub_map.apiproxy.RegisterStub( 'capability_service', capability_stub.CapabilityServiceStub()) response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_failure(self): """Test with DisabledCapabilityServiceStub """ apiproxy_stub_map.apiproxy.RegisterStub( 'capability_service', mocked_capability_stub.DisabledCapabilityServiceStub()) response = self.client.get('/') self.assertEqual(response.status_code, 302) self.assertEqual(response.headers['Location'], 'http://localhost/maintenance_page') response = self.client.get('/index2') self.assertEqual(response.status_code, 302) self.assertEqual(response.headers['Location'], 'http://localhost/no_decorator') response = self.client.get('/no_decorator') self.assertEqual(response.status_code, 200)
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 wrapper(self): client = Client(Application(), BaseResponse) response = client.get(url, headers={'Accept': accept}) eq_(response.status_code, status_code) if template: assert response.template ==template f(self, response, response.context, PyQuery(response.data)) # Validate after other tests so we know everything else works. # Hacky piggybacking on --verbose so tests go faster. if '--verbose' in sys.argv: validator = post_multipart('validator.w3.org', '/check', {'fragment': response.data}) assert PyQuery(validator)('#congrats').size() == 1
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_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_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_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
class AppStatsMiddlewareTestCase(GAETestBase): KIND_NAME_UNSWAPPED = False USE_PRODUCTION_STUBS = True CLEANUP_USED_KIND = 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 tearDown(self): pass def test_appstats_middleware(self): request = Request({}) middleware = AppStatsMiddleware() r = middleware.process_request(request) self.assertTrue(r is None) r = middleware.process_response(request, BaseResponse("", 200)) self.assertTrue(isinstance(r, BaseResponse)) summary = recording.load_summary_protos() self.assert_(summary) def test_appstats_middleware_request(self): response = self.client.get('/no_decorator') summary = recording.load_summary_protos() self.assert_(summary)
def test_get_transaction_by_id( self, authorized_client: Client, allow_user_to_account, get_transaction_by_id_mock, ) -> None: rv: Response = authorized_client.get("/account/transactions/1", ) assert rv.status_code == 200 transaction = rv.get_json() assert get_transaction_by_id_mock["transaction_id"] == 1 assert transaction == { "id": 1, "amount": 100, "currency": DiemCurrency.Coin1.value, "direction": TransactionDirection.SENT.value, "status": TransactionStatus.COMPLETED.value, "timestamp": "2020-06-23T19:49:26.989849", "source": { "full_addr": "tlb1p42424242424242424242424242rrhsrrm79jhucp0lc9r", "user_id": "863bc063df8b2bf3", "vasp_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", }, "destination": { "full_addr": "tlb1p4242424242424242424242424f6mztxd826s8fsfpwcy3", "user_id": "75b12ccd3ab503a6", "vasp_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", }, "blockchain_tx": None, "is_internal": True, }
class DownloadicsTest(GAETestBase): def setUp(self): app = get_application() self.client = Client(app, BaseResponse) self.test_values = { 'date': datetime.datetime(2016, 5, 20, 15, 0), 'title': 'THIS IS TITLE', 'description': 'THIS IS TITLE', } eve = Event( event_date=self.test_values['date'], title=self.test_values['title'], description=self.test_values['description'], ) eve.put() events = Event.all().fetch(100) self.assertEquals(len(events), 1) self.assertEquals(events[0].title, 'THIS IS TITLE') self.event_key = str(events[0].key()) def test_download_individual_icsfile(self): target_url = urlparse.urljoin('/ical/', self.event_key) res = self.client.get(target_url) self.assertEquals(res.status_code, 200) downloaded = res.get_data() reparsed = icalendar.Calendar.from_ical(downloaded) reparsed_eve = reparsed.walk('VEVENT')[0] stringfied = self.test_values['date'].strftime('%Y%m%dT%H%M%S') self.assertEquals(reparsed_eve['summary'].to_ical(), self.test_values['title']) self.assertEquals(reparsed_eve['dtstart'].to_ical(), stringfied) self.assertEquals(reparsed_eve['description'].to_ical(), self.test_values['description'])
def test_get_account_transactions( self, authorized_client: Client, allow_user_to_account, account_transactions_mock, ) -> None: rv: Response = authorized_client.get( "/account/transactions", ) assert rv.status_code == 200 transactions = rv.get_json() assert len(transactions) == 1 assert transactions["transaction_list"] == [ { "id": 1, "amount": 100, "currency": DiemCurrency.XUS.value, "direction": TransactionDirection.SENT.value, "status": TransactionStatus.COMPLETED.value, "timestamp": "2020-06-23T19:49:26.989849", "source": { "full_addr": "tdm1p42424242424242424242424242rrhsrrm79jhuckttdwm", "user_id": "863bc063df8b2bf3", "vasp_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", }, "destination": { "full_addr": "tdm1p4242424242424242424242424f6mztxd826s8fs796d0f", "user_id": "75b12ccd3ab503a6", "vasp_name": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", }, "blockchain_tx": None, "is_internal": True, } ]
def open(self, *args, **kwargs): if self.context_preserved: _request_ctx_stack.pop() self.context_preserved = False kwargs.setdefault('environ_overrides', {}) \ ['flask._preserve_context'] = self.preserve_context as_tuple = kwargs.pop('as_tuple', False) buffered = kwargs.pop('buffered', False) follow_redirects = kwargs.pop('follow_redirects', False) builder = EnvironBuilder(*args, **kwargs) if self.application.config.get('SERVER_NAME'): server_name = self.application.config.get('SERVER_NAME') if ':' not in server_name: http_host, http_port = server_name, None else: http_host, http_port = server_name.split(':', 1) if builder.base_url == 'http://localhost/': # Default Generated Base URL if http_port != None: builder.host = http_host + ':' + http_port else: builder.host = http_host old = _request_ctx_stack.top try: return Client.open(self, builder, as_tuple=as_tuple, buffered=buffered, follow_redirects=follow_redirects) finally: self.context_preserved = _request_ctx_stack.top is not old
def setUp(self): self.test_doc_path = mkdtemp() self.doc = open_document(path.join(self.test_doc_path, 'test_doc.db')) self.doc.create_note({'desc': 'note 1'}) self.doc.create_note({'desc': 'note 2'}) self.app = server.CorkApp(self.doc) self.client = Client(self.app, BaseResponse)
class CronOnlyTestCase(GAETestBase): def setUp(self): s = LazySettings(settings_module='kay.tests.settings') app = get_application(settings=s) self.client = Client(app, BaseResponse) def test_cron_only(self): response = self.client.get("/cron", headers=(('X-AppEngine-Cron', 'true'),)) self.assertEqual(response.status_code, 200) self.assertTrue(response.data == "OK") def test_cron_only_failure(self): response = self.client.get("/cron") self.assertEqual(response.status_code, 403)
def get_auth_token( client: werkzeug.Client, data: Dict[str, Optional[str]]) -> Tuple[str, CaseInsensitiveDict[str]]: data["totp_code"] = BaseTests.generate_totp(data.get("username")) r = client.post("/auth/login", json=data) content = orjson.loads(r.data.decode("utf-8")) if r.status_code == 403: if isinstance(content, dict) and content.get("actions"): actions = content.get("actions", {}) if "FIRST LOGIN" in actions or "PASSWORD EXPIRED" in actions: currentpwd = data["password"] newpwd = BaseTests.faker.password(strong=True) data["new_password"] = newpwd data["password_confirm"] = newpwd # Change the password to silence FIRST_LOGIN and PASSWORD_EXPIRED get_auth_token(client, data) # Change again to restore the default password # and keep all other tests fully working data["password"] = newpwd data["new_password"] = currentpwd data["password_confirm"] = currentpwd return get_auth_token(client, data) assert r.status_code == 200 assert content is not None headers: CaseInsensitiveDict[str] = CaseInsensitiveDict() headers["Authorization"] = f"Bearer {content}" return content, headers
def test_get_receiving_addresses(self, authorized_client: Client, allow_user_to_account, get_deposit_address_mock) -> None: rv: Response = authorized_client.post("/account/receiving-addresses") print(rv.data) assert rv.status_code == 200 assert rv.get_json() == {"address": FULL_ADDRESS}
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 setUp(self): 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_user_get_all(self, client: Client): register_user(client) login_resp = login_user(client) resp = client.get( url_for("user.get_users"), headers={"Authorization": f"Bearer {login_resp.json['token']}"}, ) assert resp.status_code == 401
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 test_get_transaction_by_id_other_user( self, authorized_client: Client, allow_user_to_account, get_transaction_by_id_mock, ) -> None: rv: Response = authorized_client.get("/account/transactions/2", ) assert get_transaction_by_id_mock["transaction_id"] == 2 assert rv.status_code == 404
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 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 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 test_get_account_info(self, authorized_client: Client, allow_user_to_account, account_balance) -> None: rv: Response = authorized_client.get("/account", ) assert rv.status_code == 200 balances = rv.get_json()["balances"] assert account_balance["account_name"] == "fake_account" assert len(balances) == 1 assert balances[0]["currency"] == DiemCurrency.Coin1.value assert balances[0]["balance"] == 100
class ChannelsViewTest(unittest.TestCase): def setUp(self): self.c = Client(views.handler, BaseResponse) def test_POSTing_with_create_client_id_header_should_create_new_channel(self): r = self.c.post(path="/channels/", headers={"Create-Client-Id":"1"}) self.assertEquals(r.status_code, 200) self.assertTrue("1" in views.clients)
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)
class MaintenanceCheckTestCase(unittest.TestCase): 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 tearDown(self): pass def test_success(self): """Test with normal CapabilityServiceStub""" apiproxy_stub_map.apiproxy.RegisterStub("capability_service", capability_stub.CapabilityServiceStub()) response = self.client.get("/") self.assertEqual(response.status_code, 200) def test_failure(self): """Test with DisabledCapabilityServiceStub """ apiproxy_stub_map.apiproxy.RegisterStub( "capability_service", mocked_capability_stub.DisabledCapabilityServiceStub() ) response = self.client.get("/") self.assertEqual(response.status_code, 302) self.assertEqual(response.headers["Location"], "http://localhost/maintenance_page") response = self.client.get("/index2") self.assertEqual(response.status_code, 302) self.assertEqual(response.headers["Location"], "http://localhost/no_decorator") response = self.client.get("/no_decorator") self.assertEqual(response.status_code, 200)
def open(self, *args, **kwargs): if self.context_preserved: _request_ctx_stack.pop() self.context_preserved = False kwargs.setdefault('environ_overrides', {}) \ ['flask._preserve_context'] = self.preserve_context old = _request_ctx_stack.top try: return Client.open(self, *args, **kwargs) finally: self.context_preserved = _request_ctx_stack.top is not old
class CronOnlyDebugTestCase(GAETestBase): def setUp(self): s = LazySettings(settings_module='kay.tests.settings') s.DEBUG = True app = get_application(settings=s) self.client = Client(app, BaseResponse) def test_cron_only_failure(self): from kay.utils import is_dev_server response = self.client.get("/cron") if is_dev_server(): self.assertEqual(response.status_code, 200) else: self.assertEqual(response.status_code, 403) def test_cron_only(self): response = self.client.get("/cron", headers=(('X-AppEngine-Cron', 'true'),)) self.assertEqual(response.status_code, 200) self.assertTrue(response.data == "OK")
class test_View_index(GAETestBase): CLEANUP_USED_KIND = True USE_PRODUCTION_STUBS = True def setUp(self): init_recording() app = get_application() self.client = Client(app, BaseResponse) def tearDown(self): disable_recording() def test_base(self): response = self.client.get('/') self.assertEquals(response.status_code, 404) def test_client_get(self): response = self.client.get('/client') self.assertEquals(response.status_code, 301) def test_client_head(self): self.fail('test_View_index.test_client_head not yet written') def test_client_post(self): self.fail('test_View_index.test_client_post not yet written') def test_client_put(self): self.fail('test_View_index.test_client_put not yet written') def test_client_delete(self): self.fail('test_View_index.test_client_delete not yet written') def test_client_options(self): self.fail('test_View_index.test_client_options not yet written') def test_client_trace(self): self.fail('test_View_index.test_client_trace not yet written') def test_client_connect(self): self.fail('test_View_index.test_client_connect not yet written')
class TaskViewTest(GAETestBase): CLEANUP_USED_KIND = True def setUp(self): init_recording() app = get_application() self.client = Client(app, BaseResponse) def tearDown(self): disable_recording() def test_post(self): data = { "name": "foo", } response = self.client.post('/tasks', data=data, follow_redirects=True) actual = Task.all().get() self.assertEquals("foo", actual.name) def test_delete(self): key = Task(name="fuga").put() tasks = Task.all().fetch(100) self.assertEquals(1, len(tasks)) response = self.client.delete('/tasks/%s' % key, follow_redirects=True) tasks = Task.all().fetch(100) self.assertEquals(0, len(tasks)) def test_put(self): key = Task(name="hoge").put() tasks = Task.all().fetch(100) self.assertEquals(1, len(tasks)) input_stream = StringIO('{ "name" : "fuga" }') response = self.client.put('/tasks/%s' % key, input_stream=input_stream, follow_redirects=True) actual = Task.get(key) self.assertEquals("fuga", actual.name)
class MaintenanceCheckTestCase(unittest.TestCase): def setUp(self): 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 tearDown(self): pass def test_success(self): """Test with normal CapabilityServiceStub""" apiproxy_stub_map.apiproxy.RegisterStub( 'capability_service', capability_stub.CapabilityServiceStub()) response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_failure(self): """Test with DisabledCapabilityServiceStub """ apiproxy_stub_map.apiproxy.RegisterStub( 'capability_service', mocked_capability_stub.DisabledCapabilityServiceStub()) response = self.client.get('/') self.assertEqual(response.status_code, 302) self.assertEqual(response.headers['Location'], 'http://localhost/_kay/maintenance_page') response = self.client.get('/index2') self.assertEqual(response.status_code, 302) self.assertEqual(response.headers['Location'], 'http://localhost/no_decorator') response = self.client.get('/no_decorator') self.assertEqual(response.status_code, 200)
class MaintenanceCheckTestCase(unittest.TestCase): def setUp(self): s = LazySettings(settings_module='kay.tests.settings') app = get_application(settings=s) self.client = Client(app, BaseResponse) def tearDown(self): pass def test_redirect(self): """Test with normal CapabilityServiceStub""" response = self.client.get('/oldpage', follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, "New")
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 setUp(self): app = get_application() self.client = Client(app, BaseResponse) self.test_values = { 'date': datetime.datetime(2016, 5, 20, 15, 0), 'title': 'THIS IS TITLE', 'description': 'THIS IS TITLE', } eve = Event( event_date=self.test_values['date'], title=self.test_values['title'], description=self.test_values['description'], ) eve.put() events = Event.all().fetch(100) self.assertEquals(len(events), 1) self.assertEquals(events[0].title, 'THIS IS TITLE') self.event_key = str(events[0].key())
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'])
class WebTestCase(unittest.TestCase): def setUp(self): self.test_doc_path = mkdtemp() self.doc = open_document(path.join(self.test_doc_path, 'test_doc.db')) self.doc.create_note({'desc': 'note 1'}) self.doc.create_note({'desc': 'note 2'}) self.app = server.CorkApp(self.doc) self.client = Client(self.app, BaseResponse) def tearDown(self): rmtree(self.test_doc_path) def failUnlessJsonResponse(self, resp, json_data): self.failUnlessEqual(resp.status_code, 200) self.failUnlessEqual(resp.headers['Content-Type'], 'application/json') self.failUnlessEqual(json.loads(resp.data), json_data) def test_notes_listing(self): self.failUnlessJsonResponse(self.client.get('/notes'), [0, 1, 2]) def test_get_note(self): self.failUnlessJsonResponse(self.client.get('/notes/0'), { 'props': {'desc': 'ROOT'}, 'children': [1, 2], }) def test_change_note(self): test_props = {'desc': 'new content here', 'a': 'b'} resp = self.client.post('/notes/1', data={'props': json.dumps(test_props)}) self.doc.abort() # checking if transaction was committed self.failUnlessEqual(dict(self.doc.notes[1]), test_props) self.failUnlessJsonResponse(resp, {'props': test_props, 'children': []}) def test_create_note(self): resp = self.client.post('/notes', data={ 'parent_id': 1, 'props': json.dumps({'f': 'g'})}) self.failUnlessJsonResponse(resp, 3) self.doc.abort() # checking if transaction was committed self.failUnlessEqual(len(self.doc.notes), 4) self.failUnlessEqual(dict(self.doc.notes[3]), {'f': 'g'}) self.failUnlessEqual(list(self.doc.notes[1].children_ids()), [3]) self.failUnlessEqual(list(self.doc.notes[0].children_ids()), [1, 2]) def test_set_parent(self): resp = self.client.post('/notes/2/parent', data={'parent_id': 1}) self.failUnlessEqual(resp.status_code, 200) self.doc.abort() # checking if transaction was committed self.failUnlessEqual(list(self.doc.notes[1].children_ids()), [2]) self.failUnlessEqual(list(self.doc.notes[0].children_ids()), [1]) def test_remove_note(self): self.client.post('/notes/2/parent', data={'parent_id': 1}) self.failUnless(1 in self.doc.notes) self.failUnless(1 in list(self.doc.notes[0].children_ids())) self.failUnless(2 in self.doc.notes) self.failUnless(2 in list(self.doc.notes[1].children_ids())) resp = self.client.delete('/notes/1') self.failUnlessJsonResponse(resp, 'ok') self.failIf(1 in self.doc.notes) self.failIf(1 in list(self.doc.notes[0].children_ids())) self.failIf(2 in self.doc.notes) def test_custom_html(self): gsm = component.getGlobalSiteManager() def customViewAdapter(note): if note.id == test_note_id: return CustomView(note) gsm.registerSubscriptionAdapter(customViewAdapter, required=[INote], provided=INoteView) test_note_id = self.doc.create_note({'a': 'b'}).id self.failUnlessJsonResponse(self.client.get('/notes/%d' % test_note_id), { 'props': {'a': 'b'}, 'children': [], 'html': '<em>hello custom!</em>', }) gsm.unregisterSubscriptionAdapter(customViewAdapter, required=[INote], provided=INoteView) def test_ajax(self): gsm = component.getGlobalSiteManager() def customViewAdapter(note): if note.id == test_note_id: return CustomView(note) gsm.registerSubscriptionAdapter(customViewAdapter, required=[INote], provided=INoteView) test_note_id = self.doc.create_note({}).id resp = self.client.post('/notes/3/ajax', data={'args': json.dumps({'token': 'asdf'})}) self.failUnlessJsonResponse(resp, '-asdf-') gsm.unregisterSubscriptionAdapter(customViewAdapter, required=[INote], provided=INoteView)
def setUp(self): s = LazySettings(settings_module='kay.tests.settings') app = get_application(settings=s) self.client = Client(app, BaseResponse)
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)