def test_permission_for_spec_directories(simple_config, route, permission, status) -> None: """Allow (200) or deny (403) access to the spec/explorer view.""" with tempfile.TemporaryDirectory() as directory: spec_name = os.path.join(directory, "openapi.yaml") spec_paths_name = os.path.join(directory, "paths.yaml") with open(spec_name, "wb") as f: f.write(SPLIT_OPENAPI_YAML) with open(spec_paths_name, "wb") as f: f.write(SPLIT_PATHS_YAML) simple_config.pyramid_openapi3_spec_directory( spec_name, route="/api/v1/spec", route_name="api_spec", permission=permission, ) simple_config.pyramid_openapi3_add_explorer( route="/api/v1/", route_name="api_explorer", permission=permission, ) simple_config.add_route("foo", "/foo") testapp = TestApp(simple_config.make_wsgi_app()) testapp.get(route, status=status)
def setUp(self): super(StartPageTestCase, self).setUp() self.mock_randint = patch.object( main.random, 'randint', autospec=True).start() self.mock_randint.return_value = 8675309 q1 = Question( question='Test Question 1', answers={ 'A': 'First Answer', 'B': 'Second Answer' }, correct_answer='B') q2 = Question( question='Test Question 2', answers={ 'A': 'An Answer', 'B': 'Another Answer' }, correct_answer='A') self.quiz_key = Quiz( questions=[q1, q2], name='Test Quiz', userid='test.user-ID').put() self.app = TestApp(application)
def git_lfs_https_app(tmpdir): custom_app = WebObTestApp( create_app(git_lfs_enabled=True, git_lfs_store_path=str(tmpdir), git_lfs_http_scheme='https')) custom_app._store = str(tmpdir) return custom_app
class ResponsePageTestCase(DatastoreBaseCase): def setUp(self): super(ResponsePageTestCase, self).setUp() self.app = TestApp(application) def test_get(self): self.login(**DatastoreBaseCase.DEFAULT_USER) resp = self.app.get('/respond') resp.mustcontain( '<h1>Respond to a Quiz</h1>', '<input name="pin" id="pin" class="form-control" type="number" ' 'value="0">', '<h4>Current User: [email protected]</h4>', '<h4>Submitted Response: </h4>') def test_get_login_required(self): resp = self.app.get('/respond', status=302) resp.mustcontain(no=[ '<h1>Respond to a Quiz</h1>', '<input name="pin" id="pin" class="form-control" type="number" ' 'value="0">', '<h4>Current User: [email protected]</h4>', '<h4>Submitted Response: </h4>']) def test_post(self): self.login(**DatastoreBaseCase.DEFAULT_USER) resp = self.app.post('/respond?pin=7&answer=B') resp.mustcontain( '<h1>Respond to a Quiz</h1>', '<input name="pin" id="pin" class="form-control" type="number" ' 'value="7">', '<h4>Current User: [email protected]</h4>', '<h4>Submitted Response: B</h4>') def test_post_no_pin(self): self.login(**DatastoreBaseCase.DEFAULT_USER) resp = self.app.post('/respond?answer=B') resp.mustcontain( '<h1>Respond to a Quiz</h1>', '<input name="pin" id="pin" class="form-control" type="number" ' 'value="-1">', '<h4>Current User: [email protected]</h4>', '<h4>Submitted Response: B</h4>') def test_post_login_required(self): resp = self.app.post('/respond?pin=7&answer=B', status=302) resp.mustcontain(no=[ '<h1>Respond to a Quiz</h1>', '<input name="pin" id="pin" class="form-control" type="number" ' 'value="7">', '<h4>Current User: [email protected]</h4>', '<h4>Submitted Response: B</h4>'])
def _post_json_data(url, data): th_collection = data[jm.project] OAuthCredentials.set_credentials( SampleData.get_credentials() ) credentials = OAuthCredentials.get_credentials(jm.project) tr = TreeherderRequest( protocol='http', host='localhost', project=jm.project, oauth_key=credentials['consumer_key'], oauth_secret=credentials['consumer_secret'] ) signed_uri = tr.oauth_client.get_signed_uri( th_collection.to_json(), tr.get_uri(th_collection.endpoint_base), "POST" ) response = TestApp(application).post_json( str(signed_uri), params=th_collection.get_collection_data() ) response.getcode = lambda: response.status_int return response
def _format(self, subdomain=None) -> None: if self._app is None: self._app = TestApp(router, extra_environ=self.extra_environ) domain = self.extra_environ['SERVER_NAME'] if subdomain is not None: domain = ('{}.' + domain).format(subdomain) # replace self._app.extra_environ = new_extra_environ(domain) else: self._app.extra_environ = new_extra_environ(domain)
def test_permission_for_specs(route, permission, status) -> None: """Allow (200) or deny (403) access to the spec/explorer view.""" with tempfile.NamedTemporaryFile() as document: document.write(OPENAPI_YAML.encode()) document.seek(0) testapp = TestApp(app(document.name, permission)) testapp.get(route, status=status)
def setUp(self): super(QuizPageTestCase, self).setUp() q1 = Question( question='Test Question 1', answers={ 'A': 'First Answer', 'B': 'Second Answer' }, correct_answer='B') q2 = Question( question='Test Question 2', answers={ 'A': 'An Answer', 'B': 'Another Answer' }, correct_answer='A') q3 = Question( question='Test Question 3', answers={ 'A': 'Alpha', 'B': 'Bravo', 'C': 'Charlie' }, correct_answer='C') q4 = Question( question='Test Question 4', answers={ 'A': 'Good Luck' }, correct_answer='B') Quiz( questions=[q1, q2], code=8675309, name='Test Quiz 1', userid='test.user-ID').put() Quiz( questions=[q3], code=1234, name='Test Quiz 2', userid='test.user-ID').put() Quiz( questions=[q4], code=5678, name='Test Quiz 3', userid='another.user-ID').put() self.app = TestApp(application)
def __init__(self, app, extra_environ=None, lint=False): super(WSGIAdapter, self).__init__() if not isinstance(app, TestApp): app = TestApp(app, extra_environ=extra_environ, lint=lint) app.RequestClass = PyriformTestRequest elif extra_environ: raise ValueError('cannot pass extra_environ and a TestApp instance' ' at the same time') elif lint: raise ValueError('cannot use lint and pass a TestApp instance' ' at the same time') self.app = app
def test_cannot_mix_testapp_and_environ(self): from webtest.app import TestApp # You can wrap an application with the testapp library, but don't # do that *and* try to set an environment together. WSGIAdapter(TestApp(binapp)) # This is allowed. with pytest.raises(ValueError): WSGIAdapter(TestApp(binapp), {'HTTP_HOST': 'thisapp.local'}) with pytest.raises(ValueError): # Also test the lint argument too. WSGIAdapter(TestApp(binapp), lint=True)
def submit_attachment(url, message, attachments): click.echo('running against %s!' % url) # files = [('attachments', (attachment, open(path.abspath(attachment)))) for attachment in attachments] browser = TestApp(url) submit_page = browser.get('/briefkasten/') submit_form = submit_page.forms['briefkasten-form'] submit_form['message'] = u'Hello there' try: response = submit_form.submit() import pdb; pdb.set_trace() click.echo(u'Got %s' % response.url) except AppError as exc: click.echo(u'Oops %s' % exc)
def submit_attachment(url, message, attachments): click.echo('running against %s!' % url) # files = [('attachments', (attachment, open(path.abspath(attachment)))) for attachment in attachments] browser = TestApp(url) submit_page = browser.get('/briefkasten/') submit_form = submit_page.forms['briefkasten-form'] submit_form['message'] = u'Hello there' try: response = submit_form.submit() import pdb pdb.set_trace() click.echo(u'Got %s' % response.url) except AppError as exc: click.echo(u'Oops %s' % exc)
def post_job_data(project, uri, data, status=None, expect_errors=False): # Since the uri is passed in it's not generated by the # treeherder request or collection and is missing the protocol # and host. Add those missing elements here. uri = 'http://localhost{0}'.format(uri) # Set the credentials OAuthCredentials.set_credentials(SampleData.get_credentials()) credentials = OAuthCredentials.get_credentials(project) tr = TreeherderRequest(protocol='http', host='localhost', project=project, oauth_key=credentials['consumer_key'], oauth_secret=credentials['consumer_secret']) signed_uri = tr.get_signed_uri(json.dumps(data), uri) response = TestApp(application).post_json(str(signed_uri), params=data, status=status, expect_errors=expect_errors) return response
def post_collection( project, th_collection, status=None, expect_errors=False, consumer_key=None, consumer_secret=None): # Set the credentials OAuthCredentials.set_credentials(SampleData.get_credentials()) credentials = OAuthCredentials.get_credentials(project) # The only time the credentials should be overridden are when # a client needs to test authentication failure confirmation consumer_key = consumer_key or credentials['consumer_key'] consumer_secret = consumer_secret or credentials['consumer_secret'] auth = TreeherderAuth(consumer_key, consumer_secret, project) client = TreeherderClient(protocol='http', host='localhost', auth=auth) uri = client._get_project_uri(project, th_collection.endpoint_base) req = Request('POST', uri, json=th_collection.get_collection_data(), auth=auth) prepped_request = req.prepare() response = TestApp(application).post_json( prepped_request.url, params=th_collection.get_collection_data(), status=status ) return response
def __init__( self, read_permissions=None, write_permissions=None, users=None, plugins=None, base_path=None, server_version=Version(SERVER_VERSION), min_client_compatible_version=Version(MIN_CLIENT_COMPATIBLE_VERSION)): """ 'read_permissions' and 'write_permissions' is a list of: [("opencv/2.3.4@lasote/testing", "user1, user2")] 'users': {username: plain-text-passwd} """ # Unique identifier for this server, will be used by TestRequester # to determine where to call. Why? remote_manager just assing an url # to the rest_client, so rest_client doesn't know about object instances, # just urls, so testing framework performs a map between fake urls and instances self.fake_url = "http://fake%s.com" % str(uuid.uuid4()).replace( "-", "") self.test_server = TestServerLauncher( base_path, read_permissions, write_permissions, users, base_url=self.fake_url + "/v1", plugins=plugins, server_version=server_version, min_client_compatible_version=min_client_compatible_version) self.app = TestApp(self.test_server.ra.root_app)
def __init__(self, read_permissions=None, write_permissions=None, users=None, plugins=None, base_path=None, server_capabilities=None, complete_urls=False): """ 'read_permissions' and 'write_permissions' is a list of: [("opencv/2.3.4@lasote/testing", "user1, user2")] 'users': {username: plain-text-passwd} """ # Unique identifier for this server, will be used by TestRequester # to determine where to call. Why? remote_manager just assing an url # to the rest_client, so rest_client doesn't know about object instances, # just urls, so testing framework performs a map between fake urls and instances if read_permissions is None: read_permissions = [("*/*@*/*", "*")] if write_permissions is None: write_permissions = [] if users is None: users = {"lasote": "mypass", "conan": "password"} self.fake_url = "http://fake%s.com" % str(uuid.uuid4()).replace("-", "") base_url = "%s/v1" % self.fake_url if complete_urls else "v1" self.test_server = TestServerLauncher(base_path, read_permissions, write_permissions, users, base_url=base_url, plugins=plugins, server_capabilities=server_capabilities) self.app = TestApp(self.test_server.ra.root_app)
def setup_test(test): app = make_debug_app({}, form=os.path.join(dirname, 'form.html'), show_form=True) test.globs['app'] = TestApp(app) for example in test.examples: example.options.setdefault(ELLIPSIS, 1) example.options.setdefault(NORMALIZE_WHITESPACE, 1)
def dummy_app(_app, extra_environ): # type (Router, dict) -> TestApp from pyramid_services import find_service app = TestApp(_app, extra_environ=extra_environ) req = app.RequestClass req.find_service = ( lambda *args, **kwargs: find_service(req, *args, **kwargs)) return app
def setUp(self): self.app = TestApp(build_app().wsgifunc()) self.db = orm.scoped_session( orm.sessionmaker(bind=engine, query_cls=NoCacheQuery))() self.db2 = orm.scoped_session( orm.sessionmaker(bind=engine, query_cls=NoCacheQuery))() self.default_headers = {"Content-Type": "application/json"} flush()
class UserPageTestCase(DatastoreBaseCase): def setUp(self): super(UserPageTestCase, self).setUp() self.app = TestApp(application) def test_get(self): self.login(**DatastoreBaseCase.DEFAULT_USER) resp = self.app.get('/user') resp.mustcontain( '<h1>User Page</h1>') def test_get_login_required(self): resp = self.app.get('/user', status=302) resp.mustcontain(no=[ '<h1>User Page</h1>'])
def _send(th_request, th_collection): OAuthCredentials.set_credentials(SampleData.get_credentials()) credentials = OAuthCredentials.get_credentials(jm.project) th_request.oauth_key = credentials['consumer_key'] th_request.oauth_secret = credentials['consumer_secret'] signed_uri = th_request.get_signed_uri( th_collection.to_json(), th_request.get_uri(th_collection) ) response = TestApp(application).post_json( str(signed_uri), params=th_collection.get_collection_data() ) response.getcode = lambda: response.status_int return response
def _testapp(self, view: t.Callable) -> TestApp: """Start up the app so that tests can send requests to it.""" from webtest import TestApp with tempfile.NamedTemporaryFile() as document: document.write(self.OPENAPI_YAML) document.seek(0) return TestApp(app(document.name, view, route="/foo"))
class DashboardPageTestCase(DatastoreBaseCase): def setUp(self): super(DashboardPageTestCase, self).setUp() self.app = TestApp(application) def test_get(self): self.login(**DatastoreBaseCase.DEFAULT_USER) resp = self.app.get('/home') resp.mustcontain( '<h1>Dashboard</h1>', '<h3>Welcome [email protected]</h3>') def test_get_login_required(self): resp = self.app.get('/home', status=302) resp.mustcontain(no=[ '<h1>Dashboard</h1>', '<h3>Welcome [email protected]</h3>'])
class AboutPageTestCase(DatastoreBaseCase): def setUp(self): super(AboutPageTestCase, self).setUp() self.app = TestApp(application) def test_get(self): resp = self.app.get('/') resp.mustcontain( '<h1>Welcome to Clicker</h1>', '<li><a href="{url}">Login</a></li>'.format( url=users.create_login_url('/home')))
def test_warn_if_streaming_with_custom_testapp(self): # Show that we generate a warning if you try to stream content, but you've set up the # adapter in a way which prevents us from streaming it in real time. from webtest.app import TestApp session = make_session(TestApp(binapp)) with pytest.warns(RuntimeWarning) as w: session.get('http://httpbin/image/png', stream=True) assert str(w[0].message) == ( 'Passing a TestApp instance to WSGIAdapter prevents ' 'streamed requests from streaming content in real time.' )
class DummyAppProxy(): """The wrapper for actual dummy app. Adds `switch_target()` to change subdomain via extra_environ. """ def __init__(self, extra_environ) -> None: self.extra_environ = extra_environ self._app = None self._format() # default example.org (not console.example.org) def _format(self, subdomain=None) -> None: if self._app is None: self._app = TestApp(router, extra_environ=self.extra_environ) domain = self.extra_environ['SERVER_NAME'] if subdomain is not None: domain = ('{}.' + domain).format(subdomain) # replace self._app.extra_environ = new_extra_environ(domain) else: self._app.extra_environ = new_extra_environ(domain) def switch_target(self, target=None) -> 'self': """Target subdomain switch utility method. >>> app = dummy_app.switch_target('console') >>> app.get('/', status=200) """ self._format(subdomain=target) return self @property def app(self): return self._app.app def get(self, *args, **kwargs): return self._app.get(*args, **kwargs) def post(self, *args, **kwargs): return self._app.post(*args, **kwargs)
def test_permission_for_specs(simple_config, route, permission, status) -> None: """Allow (200) or deny (403) access to the spec/explorer view.""" with tempfile.NamedTemporaryFile() as document: document.write(OPENAPI_YAML.encode()) document.seek(0) simple_config.pyramid_openapi3_spec( document.name, route="/api/v1/openapi.yaml", route_name="api_spec", permission=permission, ) simple_config.pyramid_openapi3_add_explorer( route="/api/v1/", route_name="api_explorer", permission=permission, ) simple_config.add_route("foo", "/foo") testapp = TestApp(simple_config.make_wsgi_app()) testapp.get(route, status=status)
def _update_parse_status(th_client, project, oauth_key, oauth_secret, job_log_url_id, parse_status): jsondata = json.dumps({'parse_status': parse_status}) signed_uri = th_client._get_project_uri( project, th_client.UPDATE_ENDPOINT.format(job_log_url_id), data=jsondata, oauth_key=oauth_key, oauth_secret=oauth_secret, method='POST') getattr(TestApp(application), 'post')(signed_uri, params=jsondata, content_type='application/json')
def _send(th_request, endpoint, method=None, data=None): if data and not isinstance(data, str): data = json.dumps(data) signed_uri = th_request.oauth_client.get_signed_uri( data, th_request.get_uri(endpoint), method) response = getattr(TestApp(application), method.lower())(str(signed_uri), params=data, content_type='application/json') response.getcode = lambda: response.status_int return response
def setUp(self): request = testing.DummyRequest() config = testing.setUp(request=request) config.registry.settings['sqlalchemy.url'] = "sqlite:///:memory:" config.include('sacrud.pyramid_ext') settings = config.registry.settings settings['sacrud_models'] = (User, Profile) config.scan() from sacrud.pyramid_ext import DBSession engine = create_engine('sqlite:///:memory:') DBSession.configure(bind=engine) self.session = DBSession # To create tables, you typically do: #User.metadata.create_all(engine) User.metadata.create_all(engine) Profile.metadata.create_all(engine) self.app = config.make_wsgi_app() self.testapp = TestApp(self.app)
def test_path_parameter_validation() -> None: """Test validated parameters in context factory.""" with NamedTemporaryFile() as tempdoc: tempdoc.write( b"""\ openapi: "3.0.0" info: version: "1.0.0" title: Foo API paths: /foo/{foo_id}: parameters: - name: foo_id in: path required: true schema: type: integer get: responses: 200: description: A foo """ ) tempdoc.seek(0) with Configurator() as config: config.include("pyramid_openapi3") config.pyramid_openapi3_spec(tempdoc.name) config.pyramid_openapi3_register_routes() config.add_route("foo_route", "/foo/{foo_id}", factory=_FooResource) config.add_view(_foo_view, route_name="foo_route", renderer="json") app = config.make_wsgi_app() test_app = TestApp(app) resp = test_app.get("/foo/1") assert resp.json == 1
def _post_json(th_client, project, endpoint, data, timeout=None, auth=None): uri = th_client._get_project_uri(project, endpoint) req = Request('POST', uri, json=data, auth=auth) prepped_request = req.prepare() getattr(TestApp(application), 'post')(prepped_request.url, params=json.dumps(data), content_type='application/json')
def _createApp(self, event_cls=events.BaseWebhookEvent): from webtest.app import TestApp app = TestApp(simple_app({})) app.grabber = app.app.registry.grabber return app
class SacrudTests(BaseSacrudTest): def setUp(self): request = testing.DummyRequest() config = testing.setUp(request=request) config.registry.settings['sqlalchemy.url'] = "sqlite:///:memory:" config.include('sacrud.pyramid_ext') settings = config.registry.settings settings['sacrud_models'] = (User, Profile) config.scan() from sacrud.pyramid_ext import DBSession engine = create_engine('sqlite:///:memory:') DBSession.configure(bind=engine) self.session = DBSession # To create tables, you typically do: #User.metadata.create_all(engine) User.metadata.create_all(engine) Profile.metadata.create_all(engine) self.app = config.make_wsgi_app() self.testapp = TestApp(self.app) def tearDown(self): def clear_files(): for filename in glob.glob("%s/*.html" % (PHOTO_PATH, )): os.remove(os.path.join(PHOTO_PATH, filename)) clear_files() self.session.remove() testing.tearDown() def test_home_view(self): self.user_add() request = testing.DummyRequest() name = route_url('sa_home', request) response = self.testapp.get(name) self.failUnlessEqual(response.status, '200 OK') self.failUnlessEqual("Tables" in response, True) self.failUnlessEqual("user" in response, True) self.failUnlessEqual("profile" in response, True) def test_list_view(self): user = self.user_add() self.profile_add(user) request = testing.DummyRequest() name = route_url('sa_list', request, table="user") response = self.testapp.get(name) self.failUnlessEqual(response.status, '200 OK') name = route_url('sa_list', request, table="profile") response = self.testapp.get(name) self.failUnlessEqual(response.status, '200 OK') def test_read_view(self): user = self.user_add() self.profile_add(user) request = testing.DummyRequest() name = route_url('sa_read', request, table="user", id="1") response = self.testapp.get(name) self.failUnlessEqual(response.status, '200 OK') name = route_url('sa_read', request, table="profile", id="1") response = self.testapp.get(name) self.failUnlessEqual(response.status, '200 OK') def test_create_view(self): request = testing.DummyRequest() name = route_url('sa_create', request, table="user") response = self.testapp.get(name) self.failUnlessEqual(response.status, '200 OK') form = response.form form['name'] = "Karlson" form['fullname'] = "Karlson the Third" form['password'] = 123 response = form.submit("form.submitted").follow() self.failUnlessEqual(response.status, '200 OK') user = self.session.query(User).get(1) self.assertFalse(user is None) self.assertEqual(user.name, "Karlson") self.assertEqual(user.fullname, "Karlson the Third") self.assertEqual(user.password, "123") self.assertEqual(user.position, 0) name = route_url('sa_create', request, table="profile") response = self.testapp.get(name) form = response.form form['user_id'] = "1" form['phone'] = "123" form['cv'] = "Karlson live on the roof" field = form.get('married', index=0) field.checked = False form['salary'] = "200.23" upload = Upload('filename.txt', 'data') form['photo'] = upload response = form.submit("form.submitted").follow() self.failUnlessEqual(response.status, '200 OK') profile = self.session.query(Profile).get(1) self.assertFalse(profile is None) self.assertEqual(profile.user.id, 1) self.assertEqual(profile.phone, "123") self.assertEqual(profile.cv, "Karlson live on the roof") self.assertEqual(profile.married, False) self.assertEqual(profile.salary, 200.23) def test_update_view(self): user = self.user_add() self.profile_add(user) request = testing.DummyRequest() name = route_url('sa_update', request, table="user", id="1") response = self.testapp.get(name) self.failUnlessEqual(response.status, '200 OK') form = response.form form['name'] = "Karlson" form['fullname'] = "Karlson the Third" form['password'] = 123 response = form.submit("form.submitted").follow() self.failUnlessEqual(response.status, '200 OK') user = self.session.query(User).get(1) self.assertFalse(user is None) self.assertEqual(user.name, "Karlson") self.assertEqual(user.fullname, "Karlson the Third") self.assertEqual(user.password, "123") name = route_url('sa_update', request, table="profile", id="1") response = self.testapp.get(name) form = response.form form['user_id'] = "1" form['phone'] = "123" form['cv'] = "Karlson live on the roof" field = form.get('married', index=0) field.checked = False form['salary'] = "200.23" upload = Upload('filename.txt', 'data') form['photo'] = upload response = form.submit("form.submitted").follow() self.failUnlessEqual(response.status, '200 OK') profile = self.session.query(Profile).get(1) self.assertFalse(profile is None) self.assertEqual(profile.user.id, 1) self.assertEqual(profile.phone, "123") self.assertEqual(profile.cv, "Karlson live on the roof") self.assertEqual(profile.married, False) self.assertEqual(profile.salary, 200.23) def test_delete_view(self): user = self.user_add() self.profile_add(user) request = testing.DummyRequest() name = route_url('sa_delete', request, table="profile", id=1) response = self.testapp.get(name).follow() self.failUnlessEqual(response.status, '200 OK') name = route_url('sa_delete', request, table="user", id=1) response = self.testapp.get(name).follow() self.failUnlessEqual(response.status, '200 OK') def test_paste_view(self): self.user_add() self.user_add() request = testing.DummyRequest() user1 = self.session.query(User).get(1) user2 = self.session.query(User).get(2) self.assertGreater(user1.position, user2.position) name = route_url('sa_paste', request, table="user", id=2, target_id=1) response = self.testapp.post(name).follow() self.failUnlessEqual(response.status, '200 OK') user1 = self.session.query(User).get(1) user2 = self.session.query(User).get(2) self.assertGreater(user2.position, user1.position)