def setUp(self): http_server = os.environ.get('HTTP_SERVER', None) # 根据环境切换测试环境 if http_server is not None: self.app = TestApp(http_server) # 为url字符串.http://example.com这种 else: self.app = TestApp(test_app)
def setUp(self): self.app = app2 self.w_without_scoping = TestApp(self.app) self.w = TestApp(self.app, db=db, use_session_scopes=True) self.app_context = self.app.app_context() self.app_context.push() db.create_all()
def test_init(self): w = TestApp(self.app) self.assertEqual(w.get('/').status_code, 200) original_server_name = self.app.config['SERVER_NAME'] try: self.app.config['SERVER_NAME'] = 'webtest-app.local' w = TestApp(self.app) self.assertEqual(w.get('/').status_code, 200) finally: self.app.config['SERVER_NAME'] = original_server_name
def test_home_gallery_reorder_visible_sessionstore(app_sessionstore): app = app_sessionstore with app.test_request_context(): testapp = TestApp(app) user = User.sessionstore_user() # Goes to homepage res = testapp.get("/") # Fills out login form form = res.forms['loginForm'] form['email'] = user.email form['password'] = app.config['SESSIONSTORE_USER_PASSWORD'] # Submits res = form.submit().follow() form = res.forms['gi-reorder'] assert form['gallery_items-0-identifier'].value == '1' assert form['gallery_items-0-weight'].value == '0' assert form['gallery_items-1-identifier'].value == '2' assert form['gallery_items-1-weight'].value == '1' form['gallery_items-0-weight'] = '1' form['gallery_items-1-weight'] = '0' res = form.submit().follow() form = res.forms['gi-reorder'] assert form['gallery_items-0-identifier'].value == '1' assert form['gallery_items-0-weight'].value == '0' assert form['gallery_items-1-identifier'].value == '2' assert form['gallery_items-1-weight'].value == '1'
def test_home_event_delete_visible_sessionstore(app_sessionstore): app = app_sessionstore with app.test_request_context(): testapp = TestApp(app) user = User.sessionstore_user() # Goes to homepage res = testapp.get("/") # Fills out login form form = res.forms['loginForm'] form['email'] = user.email form['password'] = app.config['SESSIONSTORE_USER_PASSWORD'] # Submits res = form.submit().follow() assert ((len(res.session['event']) - 1) == app.config['EVENT_NUM_DEFAULT_ITEMS']) assert (len(res.html.findAll( 'article', {'class': 'events-item' })) == app.config['EVENT_NUM_DEFAULT_ITEMS']) form = res.forms['event-delete-1'] res = form.submit().follow() assert ((len(res.session['event']) - 1) == (app.config['EVENT_NUM_DEFAULT_ITEMS'] - 1)) assert (len(res.html.findAll( 'article', {'class': 'events-item' })) == (app.config['EVENT_NUM_DEFAULT_ITEMS'] - 1)) form = res.forms['event-add'] res = form.submit().follow() res = testapp.get(url_for('public.logout')).follow()
def test_home_textcontentblock_update_visible_sessionstore(app_sessionstore): app = app_sessionstore with app.test_request_context(): testapp = TestApp(app) user = User.sessionstore_user() # Goes to homepage res = testapp.get("/") # Fills out login form form = res.forms['loginForm'] form['email'] = user.email form['password'] = app.config['SESSIONSTORE_USER_PASSWORD'] # Submits res = form.submit().follow() default_content = ShortTextContentBlock.default_content() assert default_content['site-byline'].content in res form = res.forms[ 'short-text-form-short_text_content_block-content-site-byline'] new_byline = 'This is a rather mediocre byline.' form['content'] = new_byline res = form.submit().follow() assert new_byline in res assert not (default_content['site-byline'].content in res) res = testapp.get(url_for('public.logout')).follow()
def test_home_event_startdate_update_visible_sessionstore(app_sessionstore): app = app_sessionstore with app.test_request_context(): testapp = TestApp(app) user = User.sessionstore_user() # Goes to homepage res = testapp.get("/") # Fills out login form form = res.forms['loginForm'] form['email'] = user.email form['password'] = app.config['SESSIONSTORE_USER_PASSWORD'] # Submits res = form.submit().follow() event = res.session['event'][1] old_start_date = datetime.strptime(event['start_date'], '%Y-%m-%d') old_start_date_str = old_start_date.strftime('%d %b %Y') assert (('<input class="datepicker-enable" ' 'id="event-start_date-1" name="content" ' 'placeholder="Pick your start date" required type="text" ' 'value="{0}">').format(old_start_date_str) in res) form = res.forms['date-pick-form-event-start_date-1'] new_start_date = (old_start_date + timedelta(days=3)) new_start_date_str = new_start_date.strftime('%d %b %Y') form['content'] = new_start_date_str res = form.submit().follow() assert (('<input class="datepicker-enable" ' 'id="event-start_date-1" name="content" ' 'placeholder="Pick your start date" required type="text" ' 'value="{0}">').format(new_start_date_str) in res) res = testapp.get(url_for('public.logout')).follow()
def setUp(self): global _ONE_TIME super(BaseTest, self).setUp() self.app = self._coserver = None with warnings.catch_warnings(): warnings.simplefilter("ignore") shutil.copyfile(_DB, _DB + '.saved') shutil.copyfile(_BOOK, _BOOK + '.saved') try: old_stdout = sys.stdout old_stderr = sys.stderr sys.stderr = sys.stdout = StringIO() try: self._migrate(_DB) finally: sys.stdout = old_stdout sys.stderr = old_stderr with open(_BOOK) as f: new_content = f.read() % {'DB': _DB} with open(_BOOK, 'w') as w: w.write(new_content) if _ONE_TIME is None: _ONE_TIME = TestApp(create_app(_INI)) self._coserver = run_server(8888) self.app = _ONE_TIME except Exception: self.tearDown() raise
def get_test_app(): def test_loader(app): return load_themes_from(os.path.join(os.path.dirname(__file__), '../themes/')) Themes(main.app, app_identifier='yelplove', loaders=[test_loader]) return TestApp(main.app)
def test_setup_ldap_tree(slapd_server, configuration): output = slapd_server.slapcat().stdout.decode("utf-8") assert "dn: ou=tokens,ou=oauth,dc=slapd-test,dc=python-ldap,dc=org" not in output testclient = TestApp(create_app(configuration, validate=False)) runner = testclient.app.test_cli_runner() runner.invoke(cli, ["install"]) output = slapd_server.slapcat().stdout.decode("utf-8") assert "dn: ou=tokens,ou=oauth,dc=slapd-test,dc=python-ldap,dc=org" in output
def client(app): """ Flask-Webtest TestApp provides convenient methods for writing high-level functional tests See: http://flask-webtest.readthedocs.org/en/latest/ http://webtest.readthedocs.org/en/latest/ """ return TestApp(app)
def test_help(self): # creating a client to interact with the app app = TestApp(tested_app) # calling /api/ endpoint hello = app.get('/api') # asserting the body self.assertEqual(hello.json['Hello'], 'World!')
def setUp(self): from flask_basic import app as _app self.app = TestApp(_app) setup_connector(_app) # 요청을 모방한다. session = get_connector(_app) self.adapter = requests_mock.Adapter() session.mount('http://', self.adapter)
def setUp(self): super(BaseTest, self).setUp() global _ONE_TIME if _ONE_TIME is None: print('Creating the app and database. This takes time...') with silence(): importer(['--dump-file', _DUMP, '--sqluri', 'sqlite://']) app = app_creator(['--config-file', _INI, '--no-run']) _ONE_TIME = TestApp(app) self.app = _ONE_TIME
def test_home_imagecontentblock_update_visible_sessionstore(app_sessionstore): app = app_sessionstore with app.test_request_context(): testapp = TestApp(app) user = User.sessionstore_user() # Goes to homepage res = testapp.get("/") # Fills out login form form = res.forms['loginForm'] form['email'] = user.email form['password'] = app.config['SESSIONSTORE_USER_PASSWORD'] # Submits res = form.submit().follow() assert (( '<img class="img-responsive img-circle img-lesswidth" ' 'src="{0}" alt="{1}">').format( url_for( 'static', filename=thumb.thumbnail( app.config['EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'], size='256x256', crop='fit')), app.config['SITE_NAME']) in res.text) form = res.forms['image-form-image_content_block-image-site-logo'] old_image_filepath = '{0}/{1}'.format( app.config['MEDIA_FOLDER'], app.config['EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH']) assert os.path.exists(old_image_filepath) old_image_file = open(old_image_filepath, 'rb') new_image_filename = ''.join( random.choice(string.ascii_lowercase) for _ in range(10)) new_image_filename += '.jpg' form['image'] = Upload(new_image_filename, old_image_file.read(), 'image/jpeg') old_image_file.close() res = form.submit().follow() assert (( '<img class="img-responsive img-circle img-lesswidth" ' 'src="{0}" alt="{1}">').format( url_for( 'static', filename=thumb.thumbnail( app.config['EDITABLE_PLACEHOLDER_IMAGE_RELATIVE_PATH'], size='256x256', crop='fit')), app.config['SITE_NAME']) in res.text) res = testapp.get(url_for('public.logout')).follow()
def themed_testclient(app, configuration): configuration["TESTING"] = True root = os.path.dirname(os.path.abspath(__file__)) test_theme_path = os.path.join(root, "fixtures", "themes", "test") configuration["THEME"] = test_theme_path configuration["AUTHLIB_INSECURE_TRANSPORT"] = "true" app = create_app(configuration) return TestApp(app)
def test_home_event_starttime_update_visible_sessionstore(app_sessionstore): app = app_sessionstore with app.test_request_context(): testapp = TestApp(app) user = User.sessionstore_user() # Goes to homepage res = testapp.get("/") # Fills out login form form = res.forms['loginForm'] form['email'] = user.email form['password'] = app.config['SESSIONSTORE_USER_PASSWORD'] # Submits res = form.submit().follow() event = res.session['event'][1] dt_now_str = datetime.now().strftime('%Y-%m-%d') old_start_time_str = '' if (('start_time') in event) and event['start_time']: old_start_time = (datetime.strptime( dt_now_str + ' ' + event['start_time'], '%Y-%m-%d %H:%M:%S').time()) old_start_time_str = old_start_time.strftime('%H:%M') assert (('<input class="timepicker-enable" ' 'id="event-start_time-1" name="content" ' 'placeholder="Pick your start time" type="time" ' 'value="{0}">').format(old_start_time_str) in res) form = res.forms['time-pick-form-event-start_time-1'] dt_now = datetime.now() dt_midnighttoday = datetime(dt_now.year, dt_now.month, dt_now.day) rand_delta = timedelta(minutes=(15 * random.randrange(96))) new_start_time = (dt_midnighttoday + rand_delta).time() new_start_time_str = new_start_time.strftime('%H:%M') i = 0 while i < 3 and new_start_time_str == old_start_time_str: rand_delta = timedelta(minutes=(15 * random.randrange(96))) new_start_time = (dt_midnighttoday + rand_delta).time() new_start_time_str = new_start_time.strftime('%H:%M') form['content'] = new_start_time_str res = form.submit().follow() assert (('<input class="timepicker-enable" ' 'id="event-start_time-1" name="content" ' 'placeholder="Pick your start time" type="time" ' 'value="{0}">').format(new_start_time_str) in res) res = testapp.get(url_for('public.logout')).follow()
def setUp(self): # First, create an instance of the Testbed class. self.testapp = TestApp(self.app) self.testbed = testbed.Testbed() # Then activate the testbed, which prepares the service stubs for use. self.testbed.activate() # Next, declare which service stubs you want to use. self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() # Clear ndb's in-context cache between tests. # This prevents data from leaking between tests. # Alternatively, you could disable caching by # using ndb.get_context().set_cache_policy(False) ndb.get_context().clear_cache()
def test_install_keypair(configuration, tmpdir): keys_dir = os.path.join(tmpdir, "keys") os.makedirs(keys_dir) configuration["JWT"]["PRIVATE_KEY"] = os.path.join(keys_dir, "private.pem") configuration["JWT"]["PUBLIC_KEY"] = os.path.join(keys_dir, "public.pem") assert not os.path.exists(configuration["JWT"]["PRIVATE_KEY"]) assert not os.path.exists(configuration["JWT"]["PUBLIC_KEY"]) testclient = TestApp(create_app(configuration, validate=False)) runner = testclient.app.test_cli_runner() runner.invoke(cli, ["install"]) assert os.path.exists(configuration["JWT"]["PRIVATE_KEY"]) assert os.path.exists(configuration["JWT"]["PUBLIC_KEY"])
def test_login_returns_200_sessionstore(app_sessionstore): app = app_sessionstore with app.test_request_context(): testapp = TestApp(app_sessionstore) # Goes to homepage res = testapp.get("/") # Fills out login form form = res.forms['loginForm'] user = User.sessionstore_user() form['email'] = user.email form['password'] = app.config['SESSIONSTORE_USER_PASSWORD'] # Submits res = form.submit().follow() assert res.status_code == 200
def test_install_schemas_command(configuration, slapd_server_without_schemas): configuration["LDAP"]["ROOT_DN"] = slapd_server_without_schemas.suffix configuration["LDAP"]["URI"] = slapd_server_without_schemas.ldap_uri configuration["LDAP"]["BIND_DN"] = slapd_server_without_schemas.root_dn configuration["LDAP"]["BIND_PW"] = slapd_server_without_schemas.root_pw conn = ldap.ldapobject.SimpleLDAPObject( slapd_server_without_schemas.ldap_uri) conn.protocol_version = 3 conn.simple_bind_s(slapd_server_without_schemas.root_dn, slapd_server_without_schemas.root_pw) assert "oauthClient" not in LDAPObject.ldap_object_classes(conn=conn, force=True) testclient = TestApp(create_app(configuration, validate=False)) runner = testclient.app.test_cli_runner() runner.invoke(cli, ["install"]) assert "oauthClient" in LDAPObject.ldap_object_classes(conn=conn, force=True) conn.unbind_s() slapd_server_without_schemas.stop()
def setUp(self): disconnect() connect('mongoenginetest', host=TEST_MONGO_URL) self.w = TestApp(app)
def setUp(self): # pylint: disable=invalid-name """Set-up * Test app * Headers * Mock song ID and song """ self.api = TestApp(app) self.headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format('idT0ken'), } self.params = { 'time_of_day': 'afternoon', } self.song = { 'album': None, 'apple_music_player_url': 'https://genius.com/songs/2979924/apple_music_player', 'artist': 'Men I Trust', 'embed_content': "<div id='rg_embed_link_2979924' " "class='rg_embed_link' data-song-id='2979924'>" "Read <a href='https://genius.com/Men-i-trust-lauren-lyrics'>" "“Lauren” by Men\xa0I Trust</a> on Genius</div> <script " "crossorigin src='//genius.com/songs/2979924/embed.js'>" "</script>", 'id': 2979924, 'song_art_image_thumbnail_url': "https://images.genius.com/" "9a956e5a7c0d78e8441b31bdf14dc87b.300x300x1.jpg", 'time_of_day': 'afternoon', 'title': 'Lauren', 'url': 'https://genius.com/Men-i-trust-lauren-lyrics', } self.like = { 'album': 'Non-Album Single', 'apple_music_player_url': 'https://genius.com/songs/2979924/apple_music_player', 'artist': 'Men I Trust', 'email': '*****@*****.**', 'embed_content': "<div id='rg_embed_link_2979924' " "class='rg_embed_link' data-song-id='2979924'>" "Read <a href='https://genius.com/Men-i-trust-lauren-lyrics'>" "“Lauren” by Men\xa0I Trust</a> on Genius</div> <script " "crossorigin src='//genius.com/songs/2979924/embed.js'>" "</script>", 'id': 2979924, 'song_art_image_thumbnail_url': "https://images.genius.com/" "9a956e5a7c0d78e8441b31bdf14dc87b.300x300x1.jpg", 'time_of_day': 'afternoon', 'title': 'Lauren', 'uid': 'u1d', 'url': 'https://genius.com/Men-i-trust-lauren-lyrics', } self.likes = [{ "album": "Depression Cherry", "apple_music_player_url": "https://genius.com/songs/1929412/apple_music_player", "artist": "Beach House", "email": "*****@*****.**", "embed_content": "<div id='rg_embed_link_1929412' class='rg_embed_link' " "data-song-id='1929412'>Read <a " "href='https://genius.com/Beach-house-space-song-lyrics'>" "“Space Song” " "by Beach House</a> on Genius</div> <script crossorigin " "src='//genius.com/songs/1929412/embed.js'></script>", "id": 1929412, "song_art_image_url": "https://images.genius.com/" "98ce1842b01c032eef50b8726fbbfba6.900x900x1.jpg", "time_of_day": "night", "title": "Space Song", "uid": "u1d", "url": "https://genius.com/Beach-house-space-song-lyrics" }, { "album": "Non-Album Single", "apple_music_player_url": "https://genius.com/songs/2979924/apple_music_player", "artist": "Men I Trust", "email": "*****@*****.**", "embed_content": "<div id='rg_embed_link_2979924' class='rg_embed_link' " "data-song-id='2979924'>Read <a " "href='https://genius.com/Men-i-trust-lauren-lyrics'>" "“Lauren” " "by Men I Trust</a> on Genius</div> <script crossorigin " "src='//genius.com/songs/2979924/embed.js'></script>", "id": 2979924, "song_art_image_url": "https://images.genius.com/" "9a956e5a7c0d78e8441b31bdf14dc87b.1000x1000x1.jpg", "time_of_day": "afternoon", "title": "Lauren", "uid": "u1d", "url": "https://genius.com/Men-i-trust-lauren-lyrics" }]
def testapp(app, db): """A Webtest app.""" return TestApp(app, db=db)
def setup_class(cls): cls.app = cls.appcls.testing_prep() cls.testapp = TestApp(flask.current_app)
def setUp(self): self.app = app self.app_context = app.app_context() self.app_context.push() self.w = TestApp(self.app)
def setUp(self): Post._meta.database = test_db self.app = app self.testapp = TestApp(self.app)
def test_app(app): """A Webtest app.""" return TestApp(app, )
def setUp(self): self.app = TestApp(app) # mocking the request calls session = get_connector(app) self.adapter = requests_mock.Adapter() session.mount('http://', self.adapter)
def setUp(self): self.app = app self.w = TestApp(self.app)