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)
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))
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 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 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'])
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_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()
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))
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_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_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 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()
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')
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!')
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
class TestFlaskApp(absltest.TestCase): """Flask App Testing Class""" 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" }] @patch.object(bigquery, 'get_song') @patch.object(bigquery, 'get_likes') @patch.object(firebase, 'logged_in') def test_get_recommendation(self, mock_logged_in, mock_get_likes, mock_get_song): """Test hitting the '_recommend' endpoint to get a recommendation""" mock_logged_in.return_value = True mock_get_likes.return_value = self.likes mock_get_song.return_value = self.song response = self.api.get('/_recommend', headers=self.headers, params=self.params) song = json.loads(response.text) self.assertEqual(response.headers['Content-Type'], 'application/json') self.assertEqual(response.status_code, 200) self.assertEqual(song, self.song) @patch.object(firebase, 'logged_in') def test_cannot_get_recommendation(self, mock_logged_in): """Test hitting the '_recommend' endpoint but user isn't logged in""" mock_logged_in.return_value = False response = self.api.get('/_recommend', headers=self.headers, expect_errors=True) self.assertEqual(response.headers['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response.status_code, 401) self.assertTrue('User not logged in!' in response.text) @patch.object(bigquery, 'get_likes') @patch.object(firebase, 'logged_in') def test_get_likes(self, mock_logged_in, mock_get_likes): """Test hitting the '_likes' endpoint to get user's liked songs""" mock_logged_in.return_value = True mock_get_likes.return_value = self.likes response = self.api.get('/_like', headers=self.headers) likes = json.loads(response.text) self.assertEqual(response.headers['Content-Type'], 'application/json') self.assertEqual(response.status_code, 200) self.assertEqual(likes, self.likes) @patch.object(firebase, 'like_song') @patch.object(firebase, 'logged_in') def test_post_like(self, mock_logged_in, mock_like_song): """Test hitting the '_like' endpoint to add the song recommendation""" mock_logged_in.return_value = True mock_like_song.return_value = self.like response = self.api.post('/_like', json.dumps(self.song), headers=self.headers) like = json.loads(response.text) self.assertEqual(response.headers['Content-Type'], 'application/json') self.assertEqual(response.status_code, 200) self.assertEqual(like, self.like) @patch.object(firebase, 'unlike_song') @patch.object(firebase, 'logged_in') def test_delete_like(self, mock_logged_in, mock_unlike_song): """Test hitting the '_unlike' endpoint to unlike the given song""" mock_logged_in.return_value = True mock_unlike_song.return_value = self.like response = self.api.delete(f'/_like?data={json.dumps(self.like)}', headers=self.headers) unlike = json.loads(response.text) self.assertEqual(response.headers['Content-Type'], 'application/json') self.assertEqual(response.status_code, 200) self.assertEqual(unlike, self.like)
class TestLogController(TestCase): def setUp(self): disconnect() connect('mongoenginetest', host=TEST_MONGO_URL) self.w = TestApp(app) def tearDown(self): disconnect() ############################################ # # TESTING GET /logs # ############################################ def test_status_code_with_valid_get_request(self): Log.objects().delete() r = self.w.get('/logs/?') # Assert there was no messages flushed: assert r is not None assert r.content_type == 'application/json' assert r.status_int < 400 def test_retrieving_with_invalid_from_date(self): Log.objects().delete() r = self.w.get('/logs/?from=2018-10-18T21:37:28-04:00', expect_errors=True) # Assert there was no messages flushed: assert r.status_int == 400 assert r.json == {'code': 'INVALID_TIME_FORMAT', 'success': False} def test_retrieving_with_invalid_to_date(self): Log.objects().delete() r = self.w.get('/logs/?to=2018-10-18T21:37:28-04:00', expect_errors=True) # Assert there was no messages flushed: assert r.status_int == 400 assert r.json == {'code': 'INVALID_TIME_FORMAT', 'success': False} def test_retrieving_with_invalid_from_and_to_date(self): Log.objects().delete() r = self.w.get( '/logs/?from=2018-10-18T21:37:28-04:00&to=2018-10-18T21:37:28-04:00', expect_errors=True) # Assert there was no messages flushed: assert r.status_int == 400 assert r.json == {'code': 'INVALID_TIME_FORMAT', 'success': False} def test_retrieving_valid_log(self): Log.objects().delete() answer = [{ 'userId': '12345', 'sessionId': 'asdfg', 'actions': [{ 'type': 'CLICK', 'properties': { 'locationX': 52, 'locationY': 22 }, 'time': '2018-10-18T21:37:28-06:00' }] }] action = Action(_time='2018-10-18T21:37:28-06:00', _type='CLICK', _properties=ClickProperties(locationX=52, locationY=22)) log = Log(userId='12345', sessionId='asdfg', actions=[action]) log.save() r = self.w.get('/logs/?') log.delete() assert r.json == answer def test_retrieving_log_by_user(self): Log.objects().delete() answer1 = [{ 'userId': 'ASDF', 'sessionId': '123', 'actions': [{ 'type': 'CLICK', 'properties': { 'locationX': 52, 'locationY': 22 }, 'time': '2018-10-18T21:37:28-06:00' }] }] answer2 = [{ 'userId': '12345', 'sessionId': 'asdfg', 'actions': [{ 'type': 'CLICK', 'properties': { 'locationX': 52, 'locationY': 22 }, 'time': '2018-10-18T21:37:28-06:00' }] }] action = Action(_time='2018-10-18T21:37:28-06:00', _type='CLICK', _properties=ClickProperties(locationX=52, locationY=22)) log1 = Log(userId='12345', sessionId='asdfg', actions=[action]) log2 = Log(userId='ASDF', sessionId='123', actions=[action]) log1.save() log2.save() r1 = self.w.get('/logs/?userId=ASDF') assert r1.json == answer1 r2 = self.w.get('/logs/?userId=12345') assert r2.json == answer2 r2 = self.w.get('/logs/?userId=12') assert r2.json == [] log1.delete() log2.delete() def test_retrieving_log_by_from_to(self): Log.objects().delete() answer1 = [ { "userId": "12345", "sessionId": "asdfg", "actions": [{ "time": "2018-10-17T21:37:28-06:00", "properties": { "locationX": 52, "locationY": 22 }, "type": "CLICK" }] }, { "userId": "ASDFG", "sessionId": "12345", "actions": [{ "time": "2018-10-18T21:37:28-06:00", "properties": { "viewedId": "12345" }, "type": "VIEW" }] }, ] answer2 = [ { "userId": "12345", "sessionId": "asdfg", "actions": [{ "time": "2018-10-19T21:37:28-06:00", "properties": { "pageFrom": 'X', "pageTo": 'Y' }, "type": "NAVIGATE" }] }, { "userId": "ASDFG", "sessionId": "12345", "actions": [{ "time": "2018-10-20T21:37:28-06:00", "properties": { "locationX": 60, "locationY": 30 }, "type": "CLICK" }] }, ] answer3 = [{ "userId": "ASDFG", "sessionId": "12345", "actions": [{ "time": "2018-10-18T21:37:28-06:00", "properties": { "viewedId": "12345", }, "type": "VIEW" }] }] action1 = Action(_time='2018-10-17T21:37:28-06:00', _type='CLICK', _properties=ClickProperties(locationX=52, locationY=22)) action2 = Action(_time='2018-10-19T21:37:28-06:00', _type='NAVIGATE', _properties=NavigateProperties(pageFrom='X', pageTo='Y')) log1 = Log(userId='12345', sessionId='asdfg', actions=[action1, action2]) action3 = Action(_time='2018-10-18T21:37:28-06:00', _type='VIEW', _properties=ViewProperties(viewedId='12345')) action4 = Action(_time='2018-10-20T21:37:28-06:00', _type='CLICK', _properties=ClickProperties(locationX=60, locationY=30)) log2 = Log(userId='ASDFG', sessionId='12345', actions=[action3, action4]) log1.save() log2.save() r1 = self.w.get('/logs/?to=2018-10-19T00:00:00-06:00') assert r1.json == answer1 r2 = self.w.get('/logs/?from=2018-10-19T00:00:00-06:00') assert r2.json == answer2 r3 = self.w.get( '/logs/?from=2018-10-18T00:00:00-06:00&to=2018-10-19T00:00:00-06:00' ) assert r3.json == answer3 r4 = self.w.get( '/logs/?from=2019-10-18T00:00:00-06:00&to=2020-10-19T00:00:00-06:00' ) assert r4.json == [] log1.delete() log2.delete() def test_retrieving_logs_with_matching_types(self): Log.objects().delete() answer1 = [ { "userId": "12345", "sessionId": "asdfg", "actions": [{ "time": "2018-10-20T21:37:28-06:00", "properties": { "locationX": 52, "locationY": 22 }, "type": "CLICK" }] }, { "userId": "ASDFG", "sessionId": "12345", "actions": [{ "time": "2019-10-20T21:37:28-06:00", "properties": { "locationX": 60, "locationY": 30 }, "type": "CLICK" }] }, ] answer2 = [ { "userId": "12345", "sessionId": "asdfg", "actions": [{ "time": "2018-10-20T21:37:28-06:00", "properties": { "locationX": 52, "locationY": 22 }, "type": "CLICK" }] }, { "userId": "ASDFG", "sessionId": "12345", "actions": [{ "time": "2019-10-19T21:37:28-06:00", "properties": { "viewedId": "12345", }, "type": "VIEW" }, { "time": "2019-10-20T21:37:28-06:00", "properties": { "locationX": 60, "locationY": 30 }, "type": "CLICK" }] }, ] answer3 = [{ "userId": "12345", "sessionId": "asdfg", "actions": [{ "time": "2018-10-20T21:37:28-06:00", "properties": { "pageFrom": "X", "pageTo": "Y" }, "type": "NAVIGATE" }] }] action1 = Action(_time='2018-10-20T21:37:28-06:00', _type='CLICK', _properties=ClickProperties(locationX=52, locationY=22)) action2 = Action(_time='2018-10-20T21:37:28-06:00', _type='NAVIGATE', _properties=NavigateProperties(pageFrom='X', pageTo='Y')) log1 = Log(userId='12345', sessionId='asdfg', actions=[action1, action2]) action3 = Action(_time='2019-10-19T21:37:28-06:00', _type='VIEW', _properties=ViewProperties(viewedId='12345')) action4 = Action(_time='2019-10-20T21:37:28-06:00', _type='CLICK', _properties=ClickProperties(locationX=60, locationY=30)) log2 = Log(userId='ASDFG', sessionId='12345', actions=[action3, action4]) log1.save() log2.save() r1 = self.w.get('/logs/?types=CLICK') assert r1.json == answer1 r2 = self.w.get('/logs/?types=CLICK,VIEW') assert r2.json == answer2 r3 = self.w.get('/logs/?types=NAVIGATE') assert r3.json == answer3 log1.delete() log2.delete() def test_retrieving_with_invalid_type(self): Log.objects().delete() answer = [{ 'userId': '12345', 'sessionId': 'asdfg', 'actions': [{ 'type': 'CLICK', 'properties': { 'locationX': 52, 'locationY': 22 }, 'time': '2018-10-17T21:37:28-06:00' }] }] action1 = Action(_time='2018-10-17T21:37:28-06:00', _type='CLICK', _properties=ClickProperties(locationX=52, locationY=22)) action2 = Action(_time='2018-10-19T21:37:28-06:00', _type='NAVIGATE', _properties=NavigateProperties(pageFrom='X', pageTo='Y')) log = Log(userId='12345', sessionId='asdfg', actions=[action1, action2]) log.save() r1 = self.w.get('/logs/?types=CLICK,WRONGTYPE,VIEW') assert r1.status_int == 200 assert r1.json == answer log.delete() ############################################ # # TESTING POST /logs # ############################################ def test_no_body(self): Log.objects().delete() r1 = self.w.post_json('/logs/', None, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'NO_LOGS_PROVIDED'} def test_no_userId(self): Log.objects().delete() body = [{ 'sessionId': '12345', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'CLICK', 'properties': { 'locationX': 52, 'locationY': 22 } }] }] r1 = self.w.post_json('/logs/', body, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'MISSING_USERID'} def test_no_sessionId(self): Log.objects().delete() body = [{ 'userId': '12345', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'CLICK', 'properties': { 'locationX': 52, 'locationY': 22 } }] }] r1 = self.w.post_json('/logs/', body, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'MISSING_SESSIONID'} def test_no_actions(self): Log.objects().delete() body = [{'userId': '12345', 'sessionId': '1234'}] r1 = self.w.post_json('/logs/', body, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'MISSING_ACTIONS'} def test_empty_actions(self): Log.objects().delete() body = [{'userId': '12345', 'sessionId': '1234', 'actions': []}] r1 = self.w.post_json('/logs/', body, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'MISSING_ACTIONS'} def test_invalid_time(self): Log.objects().delete() body = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'time': '2018-10-18T21:37:28', 'type': 'CLICK', 'properties': { 'locationX': 52, 'locationY': 22 } }] }] r1 = self.w.post_json('/logs/', body, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'INVALID_TIME_FORMAT'} def test_invalid_type(self): Log.objects().delete() body = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'INVALID', 'properties': { 'locationX': 52, 'locationY': 22 } }] }] r1 = self.w.post_json('/logs/', body, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'INVALID_ACTION_TYPE'} def test_invalid_type(self): Log.objects().delete() body = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'INVALID', 'properties': { 'locationX': 52, 'locationY': 22 } }] }] r1 = self.w.post_json('/logs/', body, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'INVALID_ACTION_TYPE'} def test_invalid_navigate(self): Log.objects().delete() body1 = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'NAVIGATE', 'properties': { 'pageTo': '22' } }] }] body2 = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'NAVIGATE', 'properties': { 'pageFrom': '22' } }] }] r1 = self.w.post_json('/logs/', body1, expect_errors=True) assert r1.status_int == 400 assert r1.json == {'success': False, 'code': 'MISSING_PAGEFROM_VALUE'} r2 = self.w.post_json('/logs/', body2, expect_errors=True) assert r2.status_int == 400 assert r2.json == {'success': False, 'code': 'MISSING_PAGETO_VALUE'} def test_invalid_click(self): Log.objects().delete() body1 = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'CLICK', 'properties': { 'locationX': 22 } }] }] body2 = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'CLICK', 'properties': { 'locationY': 23 } }] }] r1 = self.w.post_json('/logs/', body1, expect_errors=True) assert r1.status_int == 400 assert r1.json == { 'success': False, 'code': 'MISSING_LOCATION_Y_VALUE' } r2 = self.w.post_json('/logs/', body2, expect_errors=True) assert r2.status_int == 400 assert r2.json == { 'success': False, 'code': 'MISSING_LOCATION_X_VALUE' } def test_invalid_click(self): Log.objects().delete() body = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'time': '2018-10-18T21:37:28-06:00', 'type': 'VIEW', 'properties': { 'asdf': 'asdf' } }] }] r = self.w.post_json('/logs/', body, expect_errors=True) assert r.status_int == 400 assert r.json == {'success': False, 'code': 'MISSING_VIEWEDID_VALUE'} def test_missing_time(self): Log.objects().delete() body = [{ 'userId': '12345', 'sessionId': '1234', 'actions': [{ 'type': 'VIEW', 'properties': { 'asdf': 'asdf' } }] }] r = self.w.post_json('/logs/', body, expect_errors=True) assert r.status_int == 400 assert r.json == {'success': False, 'code': 'MISSING_TIME_VALUE'} def add_valid_log(self): Log.objects().delete() body = [{ "userId": "ABC123XYZ", "sessionId": "XYZ456ABC", "actions": [{ "time": "2018-10-18T21:37:28-06:00", "type": "CLICK", "properties": { "locationX": 52, "locationY": 11 } }, { "time": "2018-10-18T21:37:30-06:00", "type": "VIEW", "properties": { "viewedId": "FDJKLHSLD" } }, { "time": "2018-10-18T21:37:30-06:00", "type": "NAVIGATE", "properties": { "pageFrom": "communities", "pageTo": "inventory" } }] }, { "userId": "asd", "sessionId": "asdfg", "actions": [{ "time": "2018-10-18T21:37:28-06:00", "type": "CLICK", "properties": { "locationX": 60, "locationY": 70 } }, { "time": "2018-10-20T21:37:28-06:00", "type": "NAVIGATE", "properties": { "pageFrom": "X", "pageTo": "Y" } }] }] r = self.w.post_json('/logs/', body, expect_errors=True) assert r.status_int == 200 assert r.json == {'success': True} log = Log.objects() assert log is not None assert len(log) == 2 assert log[0].get('userId') == 'ABC123XYZ' assert log[0].get('sessionId') == 'XYZ456ABC' actions = log[0].get('actions') assert actions is not None assert len(actions) == 3 assert actions[0] == Action(_time="2018-10-18T21:37:28-06:00", _type="CLICK", _properties=ClickProperties(locationX=52, locationY=11)) assert actions[1] == Action( _time="2018-10-18T21:37:30-06:00", _type="VIEW", _properties=ViewProperties(viewedId="FDJKLHSLD")) assert actions[2] == Action(_time="2018-10-18T21:37:30-06:00", _type="NAVIGATE", _properties=NavigateProperties( pageFrom="communities", pageTo="inventory")) Log.objects().delete() assert log[1].get('userId') == 'asd' assert log[1].get('sessionId') == 'asdfg' actions = log[1].get('actions') assert actions is not None assert len(actions) == 2 assert actions[0] == Action(_time="2018-10-18T21:37:28-06:00", _type="CLICK", _properties=ClickProperties(locationX=60, locationY=70)) assert actions[1] == Action(_time="2018-10-20T21:37:28-06:00", _type="NAVIGATE", _properties=NavigateProperties( pageFrom="X", pageTo="Y")) Log.objects().delete()
class ScreensTest(unittest.TestCase): def setUp(self): Post._meta.database = test_db self.app = app self.testapp = TestApp(self.app) def create_testdata(self, no, title='test title {}', body='some body'): posts = [] for number in xrange(no): posts.append(Post.create(title=title.format(number), body=body)) return posts def test_post_view(self): with test_database(test_db, (Post, )): self.create_testdata(1) resp = self.testapp.get('/post/1') self.assertEqual(resp.context['post'].title, 'test title 0') def test_post_view_throws_404(self): with test_database(test_db, (Post, )): resp = self.testapp.get('/post/1', expect_errors=True) self.assertEqual(resp.status_code, 404) def test_post_list_view_is_paginated(self): with test_database(test_db, (Post, )): self.create_testdata(30) resp = self.testapp.get('/posts/2') self.assertEqual(len(resp.context['posts']), 10) self.assertEqual(resp.context['posts'][0].title, 'test title 10') def test_highlight_search_terms(self): with test_database(test_db, (Post, )): post = self.create_testdata( 1, body='lorem ipsum lorem ipsum test, lorem ipsum')[0] resp = self.testapp.get('/search?q=test') self.assertEqual(resp.context['posts'][0].body, '... lorem ipsum <b>test</b>, lorem ipsum ...') def test_highlight_search_terms_lacking_words_beginning(self): with test_database(test_db, (Post, )): post = self.create_testdata(1, body='ipsum test, lorem ipsum')[0] resp = self.testapp.get('/search?q=test') self.assertEqual(resp.context['posts'][0].body, '... ipsum <b>test</b>, lorem ipsum ...') def test_highlight_search_terms_repeated(self): with test_database(test_db, (Post, )): post = self.create_testdata(1, body='lorem ipsum, lorem ipsum')[0] resp = self.testapp.get('/search?q=ipsum') self.assertEqual(resp.context['posts'][0].body, '... lorem <b>ipsum</b>, lorem <b>ipsum</b> ...') def test_highlight_search_terms_lacking_words_end(self): with test_database(test_db, (Post, )): post = self.create_testdata(1, body='lorem ipsum test, lorem')[0] resp = self.testapp.get('/search?q=test') self.assertEqual(resp.context['posts'][0].body, '... lorem ipsum <b>test</b>, lorem ...') def test_search_handles_no_matches_in_body(self): with test_database(test_db, (Post, )): post = self.create_testdata(1, title='test', body='not found') resp = self.testapp.get('/search?q=test') self.assertEqual(len(resp.context['posts']), 1) def test_highlight_titles_when_found_in_search_result(self): with test_database(test_db, (Post, )): post = self.create_testdata(1, title='test title here test') resp = self.testapp.get('/search?q=test') self.assertEqual(resp.context['posts'][0].title, '<b>test</b> title here <b>test</b>') def test_create_post(self): with test_database(test_db, (Post, )): params = {'title': 'some title', 'body': 'some body'} resp = self.testapp.post('/post/create', params=params) self.assertEqual(resp.status_code, 302) self.assertEqual('/post/' in resp.location, True) def test_edit_post(self): with test_database(test_db, (Post, )): post = self.create_testdata(1, title='test', body='test body')[0] params = {'title': 'changed title', 'body': 'changed body'} resp = self.testapp.post('/post/edit/{}'.format(post.id), params=params) changed = Post.objects.get(post.id) self.assertEqual(resp.status_code, 302) self.assertEqual(changed.title, 'changed title') def test_edit_screen_contains_prefilled_form_on_get(self): with test_database(test_db, (Post, )): post = self.create_testdata(1, title='edit title', body='edit')[0] resp = self.testapp.get('/post/edit/{}'.format(post.id)) form = resp.context['form'] self.assertEqual(form.title.data, 'edit title') self.assertEqual(form.body.data, 'edit') def test_search_no_query_only_gives_form(self): resp = self.testapp.get('/search') self.assertEqual(resp.context['posts'], None) self.assertEqual(isinstance(resp.context['form'], SearchForm), True) def test_search_redirects_on_post_request(self): with test_database(test_db, (Post, )): self.create_testdata(1) resp = self.testapp.post('/search', params={'query': 'test'}) self.assertEqual(resp.status_code, 302) self.assertEqual('q=test' in resp.location, True)
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 test_help(self): from unit2.api_test import app as testapp app = TestApp(testapp) hello = app.get('/api') self.assertEqual(hello.json['Hello'], "World")
def test_help(self): app = TestApp(tested_app) hello = app.get('/api') self.assertEqual(hello.json['Hello'], 'World!')
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_view(self): app = TestApp(tested_app) home = app.get('/') body = home.json['data'] self.assertEqual(body, 'test fabric8 !')