class IssNowTest(TestCase): """Test the ISS-now API""" def setUp(self): self.app = app self.w = TestApp(self.app) def test_load(self): # Test the endpoints r = self.w.get('/iss-now.json') self.assertFalse(r.flashes) r = self.w.get('/iss-now/') self.assertFalse(r.flashes) r = self.w.get('/iss-now/v1') self.assertFalse(r.flashes) def test_data(self): r = self.w.get('/iss-now.json') r.charset = 'utf8' print("Current Message status, time stamP and position is", r) try: data = json.loads(r.text) except: self.fail("ISS API not a valid JSON responce") # Success message self.assertEqual(data['message'], "success", "ISS API Did not return 'sucess' message") # timestamp exists self.assertTrue('timestamp' in data) # position data self.assertTrue('iss_position' in data) self.assertTrue('latitude' in data['iss_position']) self.assertTrue('longitude' in data['iss_position'])
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()
class AstrosTest(TestCase): """Test the number of astros API""" def setUp(self): self.app = app self.w = TestApp(self.app) def test_load_astros(self): r = self.w.get('/astros.json') self.assertFalse(r.flashes) r = self.w.get('/astros/') self.assertFalse(r.flashes) r = self.w.get('/astros/v1') self.assertFalse(r.flashes) def test_data(self): r = self.w.get('/astros.json') r.charset = 'utf8' print("Names of the Astronots are", r) try: data = json.loads(r.text) except: self.fail("ISS API not a valid JSON responce") # Success message self.assertEqual(data['message'], "success", "ISS API Did not return 'sucess' message") # data exists self.assertTrue('number' in data) self.assertEqual(type(data['number']), int) self.assertTrue('people' in data)
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 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_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_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()
class TestMainFeatures(unittest.TestCase): def setUp(self): self.app = app1 self.w = TestApp(self.app) def test_single_template(self): r = self.w.get('/') self.assertFalse(r.flashes) self.assertEqual(len(r.contexts), 1) self.assertEqual(r.context['text'], 'Hello!') self.assertEqual(r.template, 'template.html') self.assertNotIn('qwerty', r.session) def test_two_templates_and_flash_messages(self): r = self.w.get('/').form.submit() self.assertEqual(len(r.contexts), 2) if flask_gte_0_10: self.assertEqual(len(r.flashes), 2) category, message = r.flashes[0] self.assertEqual(message, 'You have pressed "Quit"...') category, message = r.flashes[1] self.assertEqual(message, 'Flash message that will never be shown') else: self.assertEqual(len(r.flashes), 1) category, message = r.flashes[0] self.assertEqual(message, 'You have pressed "Quit"...') with self.assertRaises(AssertionError): r.context # Because there are more than one used templates self.assertEqual(r.contexts['template.html']['text'], 'Goodbye!') self.assertEqual(r.contexts['extra-template.html']['extra_text'], 'Some text.') def test_session_transaction(self): r = self.w.get('/whoami/') self.assertEqual(r.body.decode('utf-8'), 'nobody') with self.w.session_transaction() as sess: sess['username'] = '******' r = self.w.get('/whoami/') self.assertEqual(r.session['username'], 'aromanovich') self.assertEqual(r.body.decode('utf-8'), 'aromanovich') 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 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 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 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!')
class TestViewBase(object): def setup_method(self, _): self.ta = WebTestApp(flask.current_app) def get(self, url): return self.ta.get(url, expect_errors=True) def post(self, url): return self.ta.post(url, expect_errors=True)
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_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 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): 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 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 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_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): 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 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)
class ExampleTest(TestCase): def setUp(self): self.app = app self.w = TestApp(self.app) def test(self): r = self.w.post_json( '/link', { 'amount': 313, 'payment_reference': 'AB1273', 'payment_date': '2018-01-13' }) self.assertEqual(len(r.json), 2) def test_invalid_output(self): r = self.w.post_json('/link', { 'amount': 313, 'payment_date': '2018-01-13' }, expect_errors=True) assert r.status_code == 422
class PgnServerTest(TestCase): """ test the PGN relay application """ def setUp(self): self.app=app self.w=TestApp(self.app) self.debug=True pass def test(self): r=self.w.get('/game/cpOszEMY') self.assertEqual(r.status,"200 OK") game=chess.pgn.read_game(io.StringIO(r.text)) self.assertEqual(14,len(game.headers)) self.assertEqual("Play Chess With a WebCam",game.headers["Event"]) if self.debug: print (game) def assureRemoved(self,gameid): game=Game(gameid) self.assertFalse(game.lichess) if os.path.isfile(game.pgnfile): os.remove(game.pgnfile) return game def testPostNew(self): # use a non lichess gameId game=self.assureRemoved('abcdefg') r=self.w.post('/game/'+game.gameid,{'pgn':'e4','gameid':game.gameid}) self.assertEqual(r.template,"index.html") self.assertTrue(os.path.isfile(game.pgnfile)) def testUpdate(self): game=self.assureRemoved('game000') r=self.w.post('/game/'+game.gameid,{'pgn':'e4','gameid':game.gameid}) self.assertEqual(r.status,"200 OK") self.assertTrue(os.path.isfile(game.pgnfile)) r=self.w.get('/game/'+game.gameid,{'update':''}) self.assertEqual(r.status,"200 OK") self.assertEqual(r.template,"index.html") r=self.w.get('/game/'+game.gameid) self.assertEqual(r.status,"200 OK") self.assertTrue("1. e4" in r.text) def testIllegal(self): game=self.assureRemoved('spam') r=self.w.post('/game/'+game.gameid,{'pgn':'This is a spam message','gameid':game.gameid}) self.assertEqual(r.template,"index.html") game=Game(game.gameid) pgn="""[Event "?"] [Site "?"] [Date "????.??.??"] [Round "?"] [White "?"] [Black "?"] [Result "*"] *""" self.assertEqual(pgn,game.pgn) #self.assertFalse(os.path.isfile(game.pgnfile))
class TestAPI(unittest.TestCase): 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 test_api(self): mocked_value = json.dumps({'some': 'data'}) self.adapter.register_uri('GET', 'http://127.0.0.1:5000/api', text=mocked_value) res = self.app.get('/api') self.assertEqual(res.json['result']['some'], 'data')
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 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()
class FrontPageTest(TestCase): """Test that the front page is rendering""" def setUp(self): self.app = app self.w = TestApp(self.app) def test(self): r = self.w.get('/') # Assert there was no messages flashed self.assertFalse(r.flashes) # Assert that we got an index template self.assertEqual(r.template, 'index.html')
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"])
class TestMyApp(unittest.TestCase): 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 test_change(self): #app = TestApp(test_app) hello = self.app.get("/api") assert hello.json['Hello'] == 'world'
class TestAPI(unittest.TestCase): 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 test_api(self): mocked_value = json.dumps({'Hello': 'World!'}) self.adapter.register_uri('GET', 'http://127.0.0.1:5000/api', text=mocked_value) res = self.app.get('/api') self.assertEqual(res.json['Hello'], 'World!')
class TestSQLAlchemyFeatures(unittest.TestCase): 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 tearDown(self): db.drop_all() self.app_context.pop() def test_1(self): user = User(name='Anton') db.session.add(user) db.session.commit() r = self.w.get('/user/%i/' % user.id) self.assertEqual(r.body.decode('utf-8'), 'Hello, Anton!') # Note: we did not commit the change to `user`! user.name = 'Petr' r = self.w_without_scoping.get('/user/%i/' % user.id) self.assertEqual(r.body.decode('utf-8'), 'Hello, Petr!') r = self.w.get('/user/%i/' % user.id) self.assertEqual(r.body.decode('utf-8'), 'Hello, Anton!') def test_2(self): user = User(name='Anton') db.session.add(user) db.session.commit() r = self.w.get('/user/%i/' % user.id) self.assertEqual(r.body.decode('utf-8'), 'Hello, Anton!') r = self.w.post('/user/%i/preview/' % user.id, { 'greeting': 'Hi, %s.', }) self.assertEqual(r.body.decode('utf-8'), 'Hi, Anton.') db.session.refresh(user) r = self.w_without_scoping.post('/user/%i/preview/' % user.id, { 'greeting': 'Hi, %s.', }) self.assertEqual(r.body.decode('utf-8'), 'Hi, Anton.') self.assertRaises( sqlalchemy.exc.InvalidRequestError, lambda: db.session.refresh(user))
class TestSQLAlchemyFeatures(unittest.TestCase): 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 tearDown(self): db.drop_all() self.app_context.pop() def test_1(self): user = User(name='Anton') db.session.add(user) db.session.commit() r = self.w.get('/user/%i/' % user.id) self.assertEqual(r.body.decode('utf-8'), 'Hello, Anton!') # Note: we did not commit the change to `user`! user.name = 'Petr' r = self.w_without_scoping.get('/user/%i/' % user.id) self.assertEqual(r.body.decode('utf-8'), 'Hello, Petr!') r = self.w.get('/user/%i/' % user.id) self.assertEqual(r.body.decode('utf-8'), 'Hello, Anton!') def test_2(self): user = User(name='Anton') db.session.add(user) db.session.commit() r = self.w.get('/user/%i/' % user.id) self.assertEqual(r.body.decode('utf-8'), 'Hello, Anton!') r = self.w.post('/user/%i/preview/' % user.id, { 'greeting': 'Hi, %s.', }) self.assertEqual(r.body.decode('utf-8'), 'Hi, Anton.') db.session.refresh(user) r = self.w_without_scoping.post('/user/%i/preview/' % user.id, { 'greeting': 'Hi, %s.', }) self.assertEqual(r.body.decode('utf-8'), 'Hi, Anton.') self.assertRaises(sqlalchemy.exc.InvalidRequestError, lambda: db.session.refresh(user))
class TestMainFeatures(unittest.TestCase): def setUp(self): self.app = app1 self.w = TestApp(self.app) def test_single_template(self): r = self.w.get('/') self.assertFalse(r.flashes) self.assertEqual(len(r.contexts), 1) self.assertEqual(r.context['text'], 'Hello!') self.assertEqual(r.template, 'template.html') self.assertNotIn('qwerty', r.session) def test_two_templates_and_flash_messages(self): r = self.w.get('/').form.submit() self.assertEqual(len(r.contexts), 2) if flask_gte_0_10: self.assertEqual(len(r.flashes), 2) category, message = r.flashes[0] self.assertEqual(message, 'You have pressed "Quit"...') category, message = r.flashes[1] self.assertEqual(message, 'Flash message that will never be shown') else: self.assertEqual(len(r.flashes), 1) category, message = r.flashes[0] self.assertEqual(message, 'You have pressed "Quit"...') with self.assertRaises(AssertionError): r.context # Because there are more than one used templates self.assertEqual( r.contexts['template.html']['text'], 'Goodbye!') self.assertEqual( r.contexts['extra-template.html']['extra_text'], 'Some text.') def test_session_transaction(self): r = self.w.get('/whoami/') self.assertEqual(r.body.decode('utf-8'), 'nobody') with self.w.session_transaction() as sess: sess['username'] = '******' r = self.w.get('/whoami/') self.assertEqual(r.session['username'], 'aromanovich') self.assertEqual(r.body.decode('utf-8'), 'aromanovich') 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_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 setup_method(self, _): self.ta = WebTestApp(flask.current_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): self.app = app1 self.w = TestApp(self.app)