def test_not_logged_in(self): """Test what happens when someone is not logged in.""" with app.test_request_context(): logged_in = is_logged_in() self.assertEquals(logged_in, False)
def postEvent(eventType, data, namespace=None, room=None): if not isinstance(data, dict): return error_response(500, "Message data must be of type dict.") headers = { 'Authorization': 'Bearer {}'.format(app.config.get('SERVICE_TOKEN')), 'Content-Type': 'application/json' } emit = { 'eventType': eventType, 'data': data, 'namespace': namespace, 'room': room, } with app.test_request_context(): url = url_for('message_api.emit_message', _external=True) try: resp = requests.post(url, json=emit, headers=headers) except: logger.debug('Failed to post to url: {}'.format(url)) abort(500) return resp
def test_remove_no_user_in_session(self): """Test removal when we start without any user in session.""" with app.test_request_context(): remove_session_info() self.assertNotIn('user', session)
def test_companies_act_full(self): with app.test_request_context(): self.assertIsNotNone(self.document_id) full = query_instrument({'document_id': '%s' % self.document_id}) self.assertIsNotNone(full['html_content']) self.assertEqual(full['format'], 'skeleton') self.assertEqual(full['title'], 'Companies Act 1993')
def test_render_template_success(): with app.test_request_context(): render_call = render_template('en/2019/index.html', lang='en', year='2019') # Check it's a decent size with 'Web Almanac' somewhere in there assert len(render_call) > 3000 and 'Web Almanac' in render_call
def test_definition_transience_simple(self): with app.test_request_context(): tree = etree.parse('tests/transient_defs.xml', parser=self.parser) tree, definitions = populate_definitions(tree, document_id=0) tree = process_definitions(tree, definitions) self.assertEqual(len(definitions.active), 1) # one global self.assertEqual(len(definitions.items()), 4)
def test_render_template_translation_valid_chapter(): with app.test_request_context(): request.full_path = '/es/2019/css' render_call = render_template(template='es/2019/chapters/css.html', lang='es', year='2019') assert len(render_call) > 3000 and '<html lang="es"' in render_call
def test_no_user(self): """Test what happens when no user is logged in.""" with app.test_request_context(): user = get_current_user() self.assertEquals(user, None)
def test_companies_act_more(self): with app.test_request_context(): parts = query_instrument({ 'id': '%s' % self.document_id, 'find': 'more', 'parts': '4,5,6' }) self.assertIsNotNone(parts['parts'])
def test_new_returns_400_on_no_drink_selection(self): with app.test_request_context(): new = self.app_client.post('/new', data={'drink': ''}) self.assertEqual( new.get_data(), b'Unable to process Entry: Something\'s wrong with your order, perhaps you meant to select "Other".', ) self.assertEqual(new.status_code, 422)
def test_new_returns_201_on_success(self): data = {'drink': 'g&t', 'message': 'do nothing'} app.redis = RedisStub() with app.test_request_context(): new = url_for('receive_new_order') res = self.app_client.post(new, data=data) self.assertEqual(res.status_code, 201) self.assertEqual(res.data, b'Order created')
def test_render_template_no_translation_invalid_chapter(): with app.test_request_context(): request.full_path = '/es/2019/random' render_call = render_template(template='es/2019/chapters/random.html', lang='es', year='2019') assert render_call.status_code == 302 and render_call.headers[ 'Location'] == '/es/2019/'
def test_user_in_session_is_null(self): """Test what happen if session is in wonky state (user=None).""" with app.test_request_context(): session['user'] = None logged_in = is_logged_in() self.assertEquals(logged_in, False)
def test_definition_extraction(self): with app.test_request_context(): tree = etree.parse('tests/3_definitions.xml', parser=self.parser) definitions = Definitions() find_all_definitions(tree, definitions, document_id=0, expire=False) self.assertEqual(len(definitions.items()), 3) self.assertTrue(('accounting period', 'accounting periods') in definitions.active) self.assertTrue(('address for service', 'address for services', 'addresses for service', 'addresses for services') in definitions.active) self.assertTrue(('annual meeting', 'annual meetings') in definitions.active)
def test_success_coinflip(self): with app.test_request_context(): with mock.patch("flask.request", data={ "bet": 50, "side": "Heads" }): with mock.patch("server.db.session.add", AlchemyMagicMock()): response = coinflip() self.assertIs(type(response), tuple)
def test_render_template_no_translation_valid_chapter(): with app.test_request_context(): request.full_path = '/es/2019/css' # Use a fake template that won't ever be found by overriding lang to 99 render_call = render_template(template='99/2019/chapters/css.html', lang='es', year='2019') assert render_call.status_code == 302 and render_call.headers[ 'Location'] == '/en/2019/css'
def test_companies_act_preview(self): with app.test_request_context(): preview = query_instrument({ 'document_id': '%s' % self.document_id, 'find': 'preview' }) self.assertIsNotNone(preview['html_content']) self.assertEqual(preview['format'], 'preview') self.assertEqual(preview['full_title'], 'Companies Act 1993')
def test_remove_user_is_none(self): """Test removal when user in session, but value is None.""" with app.test_request_context(): session['user'] = None self.assertIn('user', session) remove_session_info() self.assertNotIn('user', session)
def test_companies_act_fragment(self): with app.test_request_context(): fragment = query_instrument({ 'document_id': '%s' % self.document_id, 'location': 's 146(2)(a)(iv)', 'find': 'location' }) self.assertIsNotNone(fragment['html_content']) self.assertEqual(fragment['format'], 'fragment')
def test_complex(self): with app.test_request_context(): tree = etree.parse('tests/companiesact_gutted.xml', parser=self.parser) tree, definitions = populate_definitions(tree, document_id=0) tree, _ = process_definitions(tree, definitions) for d in definitions.pool: if d.full_word in ['shareholder', 'holder of the shares']: self.assertIn('DLM320498', d.expiry_tags) self.assertIn('DLM1624955', d.expiry_tags)
def test_render_template_no_chapter(): # Note normally this would be caught by validate before render_template is called with app.test_request_context(): request.full_path = '/en/2019/random' render_call = render_template(template='en/2019/chapters/random.html', lang='en', year='2019') assert render_call.status_code == 302 and render_call.headers[ 'Location'] == '/en/2019/'
def test_empty_message(self): """Test flashing a message with no text.""" message = '' alert_type = 'success' flash_message(message, alert_type) with app.test_request_context(): self.assertNotIn('_flashes', session)
def test_new_order_form_renders_choices(self): with app.test_request_context(): new_order_page = url_for('get_new_order') res = self.app_client.get(new_order_page) self.assertEqual(res.status_code, 200) assert b'Gin & Tonic' in res.data assert b'Espresso Martini' in res.data assert b'Negroni' in res.data assert b'Beer' in res.data assert b'Other' in res.data
def test_definition_redefinitions(self): with app.test_request_context(): tree = etree.parse('tests/redefinitions.xml', parser=self.parser) tree, definitions = populate_definitions(tree, document_id=0) tree, _ = process_definitions(tree, definitions) self.assertEqual(len(tree.xpath('.//catalex-def')), 4) self.assertEqual(tree.xpath('.//catalex-def')[0].attrib['def-ids'], '0-xxx') self.assertEqual(tree.xpath('.//catalex-def')[1].attrib['def-ids'], '0-yyy') self.assertEqual(tree.xpath('.//catalex-def')[2].attrib['def-ids'], '0-xxx') self.assertEqual(tree.xpath('.//catalex-def')[3].attrib['def-ids'], '0-zzz')
def test_list_orders_gets_updated(self): with app.test_request_context(): orders_page = url_for('get_orders_page') res = self.app_client.get(orders_page) self.assertEqual(res.status_code, 200) assert b'<li >Gin, Now (order received:' not in res.data Order('Gin', 'Now').save_order(self.db) res = self.app_client.get(orders_page) self.assertEqual(res.status_code, 200) assert b'<li >Gin, Now (order received:' in res.data
def test_get_orders_returns_data_list(self): Order( 'Banana Milkshake', 'No, I would not like to buy a subscription ' 'to your newsletter, thank you very much').save_order(self.db) with app.test_request_context(): get_orders = url_for('get_orders') res = self.app_client.get(get_orders) self.assertEqual(res.status_code, 200) data_0 = json.loads(res.data)[0] self.assertEqual(data_0['drink'], 'Banana Milkshake') assert 'newsletter' in data_0['message']
def test_get_order_returns_200(self): Order('Chiquita Sunrise', 'I\m not entirely sure if this is a man\'s drink').save_order( self.db) with app.test_request_context(): get_orders = url_for('get_order', order_id=1) res = self.app_client.get(get_orders) self.assertEqual(res.status_code, 200) data_0 = json.loads(res.data)[0] self.assertEqual(data_0['drink'], 'Chiquita Sunrise') assert 'entirely sure' in data_0['message']
def test_post_anno(self): tester = app.test_client(self) # validate payload # auth=(config.API_KEY, config.API_SECRET) headers = { 'Authorization': 'Basic ' + b64encode("{0}:{1}".format(config.USER_NAME, config.PASSWORD)), 'Content-Type': 'application/json' } annotation = { "body": { "text": "", "type": "TextualBody", "language": "en", "format": "text/html" }, "motivation": "describing", "target": { "source": "", "selector": { "type": "TypeOfSelector" } }, "generator": { "homepage": "", "type": "SoftwareAgent", "id": "", "name": "" }, "creator": { "nick": "", "type": "Person", "id": "", "name": "" }, "@context": "http://www.w3.org/ns/anno.jsonld", "type": "Annotation" } result = tester.post('/annotations/api/v1.0/annos', data=json.dumps(annotation), headers=headers) # Assert response codes with app.test_request_context('/annotations/api/v1.0/annos', method='POST'): assert request.path == '/annotations/api/v1.0/annos' assert request.method == 'POST' self.assertEqual(result.status_code, 201)
def test_login_invalid_user(self): """Test login for a user that does not exist.""" with app.test_request_context(): username = '******' password = '******' response = attempt_login(username, password) self.assertEquals(302, response.status_code) self.assertEquals('/register', response.location) self.assertNotIn('user', session)
def test_login_valid_user_valid_password(self): """Test a valid user/password pair.""" with app.test_request_context(): username = '******' password = '******' response = attempt_login(username, password) self.assertEquals('/', response.location) self.assertEquals(302, response.status_code) self.assertEquals(1, session['user']['id'])
def test_login_valid_user_invalid_password(self): """Test login for an existing user with an incorrect password.""" with app.test_request_context(): username = '******' password = '******' response = attempt_login(username, password) self.assertEquals('/login', response.location) self.assertEquals(302, response.status_code) self.assertNotIn('user', session)
def test_message_with_content(self): """Test flashing a message with text.""" with app.test_request_context(): message = 'message' alert_type = 'success' flash_message(message, alert_type) flashed_message = session['_flashes'][0] self.assertEquals(message, flashed_message[0]) self.assertIn(alert_type, flashed_message[1])
def test_recording_does_not_exist(self): """Test what happens when a recording does not exist.""" with app.test_request_context(): user = { 'id': 1, 'name': 'Angie' } session['user'] = user belongs_to_user = recording_belongs_to_user(3) self.assertEquals(False, belongs_to_user)
def test_does_not_belong_to_user(self): """Test a recording that does not belong to the user.""" with app.test_request_context(): user = { 'id': 1, 'name': 'Angie' } session['user'] = user belongs_to_user = recording_belongs_to_user(2) self.assertEquals(False, belongs_to_user)
def parse_protocol_async(protocol_id): with app.app_context(): with app.test_request_context("/"): try: protocol = Protocol.first_by_id(protocol_id) if protocol is None: raise Exception("No protocol given. Aborting parsing.") parse_protocol_async_inner(protocol) except Exception as exc: stacktrace = traceback.format_exc() return _make_error(protocol, "Parsing", "Exception", "{}\n\n{}".format(str(exc), stacktrace))
def test_remove_user_in_session(self): """Test removal when we start with a user in session.""" with app.test_request_context(): user = { 'id': 1, 'name': 'name' } session['user'] = user self.assertIn('user', session) remove_session_info() self.assertNotIn('user', session)
def test_find_by_string(self): with app.test_request_context(): prov = nodes_from_path_string(self.tree, 's 2')[0] self.assertTrue(prov.tag, 'prov') self.assertEqual(nodes_from_path_string(self.tree, 'Part 1 s 2')[0], prov) prov = nodes_from_path_string(self.tree, 's 216(2)(b)')[0] self.assertTrue(prov.tag, 'label-para') self.assertEqual(nodes_from_path_string(self.tree, 'Part 12 s 216(2)(b)')[0], prov) self.assertRaises(CustomException, nodes_from_path_string, self.tree, 'Part 2 s 666') sched = nodes_from_path_string(self.tree, 'sch')[0] self.assertTrue(sched.tag, 'schedule') self.assertEqual(nodes_from_path_string(self.tree, 'schedule 1')[0], sched) self.assertEqual(nodes_from_path_string(self.tree, 'sch 3 cl 1')[0].tag, 'prov') self.assertEqual(nodes_from_path_string(self.tree, 'sch 3 cl 1(2)')[0].tag, 'subprov')
def test_definition_redefinitions(self): with app.test_request_context(): tree = etree.parse('tests/redefinitions.xml', parser=self.parser) tree, definitions = populate_definitions(tree, document_id=0) tree, _ = process_definitions(tree, definitions) self.assertEqual(len(tree.xpath('.//catalex-def')), 4) self.assertEqual( tree.xpath('.//catalex-def')[0].attrib['def-ids'], '0-xxx') self.assertEqual( tree.xpath('.//catalex-def')[1].attrib['def-ids'], '0-yyy') self.assertEqual( tree.xpath('.//catalex-def')[2].attrib['def-ids'], '0-xxx') self.assertEqual( tree.xpath('.//catalex-def')[3].attrib['def-ids'], '0-zzz')
def test_add_session_info_user(self): """Test adding session info when user has a value.""" with app.test_request_context(): user = User(id=1, name='name', email='*****@*****.**', password='******') add_session_info(user) self.assertIn('user', session) session_user = session['user'] self.assertEquals(session_user['id'], 1) self.assertEquals(session_user['name'], 'name')
def test_render_error_template_404_no_error_template(): with app.test_request_context(): # As all languages should have an error template we fake a new "valid" language called random request.view_args = {'lang': 'random', 'year': '2020'} class Language(object): EN = _Language('English', 'en') RANDOM = _Language('Random', 'random') Languages = [] Languages.append(getattr(Language, 'EN')) Languages.append(getattr(Language, 'RANDOM')) SUPPORTED_LANGUAGES.update({'2020': Languages}) render_call = render_error_template(error='Not Found', status_code=404) assert render_call[1] == 404 and '<html lang="en"' in render_call[0]
def test_user_logged_in(self): """Test what happens when someone is logged in.""" with app.test_request_context(): user = { 'id': 1, 'name': 'Angie' } session['user'] = user current_user = get_current_user() self.assertNotEquals(current_user, None) self.assertIsInstance(current_user, User) self.assertEquals(current_user.name, 'Angie')
def test_logged_in(self): """Test what happens when someone is logged in.""" with app.test_request_context(): user = { 'id': 1, 'name': 'Angie' } session['user'] = user current_user = get_current_user() logged_in = is_logged_in() self.assertEquals(logged_in, True)
def test_invalid_user(self): """Test what happens when we try to get a user that is not in the db.""" with app.test_request_context(): user = { 'id': -1, 'name': 'Angie' } session['user'] = user current_user = get_current_user() self.assertIn('user', session) self.assertEquals(-1, session['user']['id']) self.assertEquals(current_user, None)
def test_case_and_plurals(self): with app.test_request_context(): tree = etree.parse('tests/plural_charcase_defs.xml', parser=self.parser) tree, definitions = populate_definitions(tree, document_id=0) tree, _ = process_definitions(tree, definitions) self.assertEqual(len(definitions.items()), 6) self.assertEqual(len(tree.xpath('.//*[@cid="case_wrong_start"]/catalex-def-def')), 0) self.assertEqual(len(tree.xpath('.//*[@cid="case_wrong_end"]/catalex-def')), 0) self.assertEqual(len(tree.xpath('.//*[@cid="case_correct"]/catalex-def')), 1) self.assertEqual(len(tree.xpath('.//*[@cid="case_plural_correct"]/catalex-def')), 1) self.assertEqual(len(tree.xpath('.//*[@cid="plural_correct"]/catalex-def')), 1) self.assertEqual(len(tree.xpath('.//*[@cid="plural_wrong"]/catalex-def')), 0) self.assertEqual(len(tree.xpath('.//*[@cid="complex_plural_correct"]/catalex-def')), 1) self.assertEqual(len(tree.xpath('.//*[@cid="complex_plural_possessive_correct"]/catalex-def')), 1) self.assertEqual(len(tree.xpath('.//*[@cid="complex_plural_possessive_correct_2"]/catalex-def')), 2) self.assertEqual(len(tree.xpath('.//*[@cid="complex_plural_possessive_correct_3"]/catalex-def')), 4) self.assertEqual(len(tree.xpath('.//catalex-def')), 12)
def test_register_existing_user(self): """Test what happens when trying to register a user that already exists.""" count_before = len(User.query.all()) with app.test_request_context(): response = register_user(name='Angie', email='*****@*****.**', password='******', zipcode='99999', country='US') count_after = len(User.query.all()) count_difference = count_after - count_before self.assertEquals(302, response.status_code) self.assertEquals('/login', response.location) self.assertEquals(count_difference, 0)
def test_add_recording(self): """Add a recording that contains all possible pieces of information.""" with app.test_request_context(): user = { 'id': 1, 'name': 'Angie' } session['user'] = user add_recording_to_db() recording = Recording.query.one() self.assertNotEquals(recording, None) self.assertIsInstance(recording, Recording) self.assertEquals(recording.user_id, 1) self.assertEquals(recording.public, True)
def test_choose_rand_results(self): """Test choose rand results route.""" import server with app.test_request_context(): session['rec_id'] = [] # self.maxDiff = None self.assertEqual( server.choose_rand_results([{ "id": 479102, "title": "On the Job: Pan Roasted Cauliflower From Food52", "readyInMinutes": 20 }]), ([{ "id": 479102, "title": "On the Job: Pan Roasted Cauliflower From Food52", "readyInMinutes": 20 }], 0))
def test_case_and_plurals(self): with app.test_request_context(): tree = etree.parse('tests/plural_charcase_defs.xml', parser=self.parser) tree, definitions = populate_definitions(tree, document_id=0) tree, _ = process_definitions(tree, definitions) self.assertEqual(len(definitions.items()), 6) self.assertEqual( len(tree.xpath( './/*[@cid="case_wrong_start"]/catalex-def-def')), 0) self.assertEqual( len(tree.xpath('.//*[@cid="case_wrong_end"]/catalex-def')), 0) self.assertEqual( len(tree.xpath('.//*[@cid="case_correct"]/catalex-def')), 1) self.assertEqual( len(tree.xpath( './/*[@cid="case_plural_correct"]/catalex-def')), 1) self.assertEqual( len(tree.xpath('.//*[@cid="plural_correct"]/catalex-def')), 1) self.assertEqual( len(tree.xpath('.//*[@cid="plural_wrong"]/catalex-def')), 0) self.assertEqual( len( tree.xpath( './/*[@cid="complex_plural_correct"]/catalex-def')), 1) self.assertEqual( len( tree.xpath( './/*[@cid="complex_plural_possessive_correct"]/catalex-def' )), 1) self.assertEqual( len( tree.xpath( './/*[@cid="complex_plural_possessive_correct_2"]/catalex-def' )), 2) self.assertEqual( len( tree.xpath( './/*[@cid="complex_plural_possessive_correct_3"]/catalex-def' )), 4) self.assertEqual(len(tree.xpath('.//catalex-def')), 12)
def test_find_by_string(self): with app.test_request_context(): prov = nodes_from_path_string(self.tree, 's 2')[0] self.assertTrue(prov.tag, 'prov') self.assertEqual( nodes_from_path_string(self.tree, 'Part 1 s 2')[0], prov) prov = nodes_from_path_string(self.tree, 's 216(2)(b)')[0] self.assertTrue(prov.tag, 'label-para') self.assertEqual( nodes_from_path_string(self.tree, 'Part 12 s 216(2)(b)')[0], prov) self.assertRaises(CustomException, nodes_from_path_string, self.tree, 'Part 2 s 666') sched = nodes_from_path_string(self.tree, 'sch')[0] self.assertTrue(sched.tag, 'schedule') self.assertEqual( nodes_from_path_string(self.tree, 'schedule 1')[0], sched) self.assertEqual( nodes_from_path_string(self.tree, 'sch 3 cl 1')[0].tag, 'prov') self.assertEqual( nodes_from_path_string(self.tree, 'sch 3 cl 1(2)')[0].tag, 'subprov')
def test_post_anno(self): tester = app.test_client(self) # validate payload # auth=(config.API_KEY, config.API_SECRET) headers = { 'Authorization': 'Basic ' + b64encode("{0}:{1}".format(config.USER_NAME, config.PASSWORD)), 'Content-Type': 'application/json' } annotation = {"body": {"text": "", "type": "TextualBody", "language": "en", "format": "text/html"}, "motivation": "describing", "target": {"source": "", "selector": {"type": "TypeOfSelector"} }, "generator": {"homepage": "", "type": "SoftwareAgent", "id": "", "name": ""}, "creator": {"nick": "", "type": "Person", "id": "", "name": ""}, "@context": "http://www.w3.org/ns/anno.jsonld", "type": "Annotation" } result = tester.post('/annotations/api/v1.0/annos', data=json.dumps(annotation), headers=headers) # Assert response codes with app.test_request_context('/annotations/api/v1.0/annos', method='POST'): assert request.path == '/annotations/api/v1.0/annos' assert request.method == 'POST' self.assertEqual(result.status_code, 201)
def test_render_error_template_404_bad_lang_and_year(): with app.test_request_context(): request.view_args = {'lang': '12', 'year': '2018'} render_call = render_error_template(error='Not Found', status_code=404) assert render_call[1] == 404 and '<html lang="en"' in render_call[0]
def test_render_error_template_404(): with app.test_request_context(): render_call = render_error_template(error='Not Found', status_code=404) assert render_call[1] == 404
def test_render_methodology_bad_year_lang(): with app.test_request_context(): render_call = get_ebook_methodology('random', '2018') assert render_call is False
#!/usr/bin/python # -*- coding: utf-8 -*- import os from server import db, app from user.models import User def create_user_data(dbsession, count=1): for u in range(0,count): user = User('Vorname Nachname {0}'.format(u), '{0}@hf.com'.format(u), '1234') dbsession.add(user) print user.mail, user.id dbsession.commit() if __name__ == '__main__': """ """ DB_NAME = 'dummy.db' if os.path.isfile(DB_NAME): os.remove(DB_NAME) db.create_all() with app.test_request_context(): create_user_data(db.session, 2)
def test_add_session_info_no_user(self): """Test what happens when no user is passed (hopefully nothing).""" with app.test_request_context(): add_session_info(None) self.assertNotIn('user', session)
def test_companies_act_more(self): with app.test_request_context(): parts = query_instrument({'id': '%s' % self.document_id, 'find': 'more', 'parts': '4,5,6'}) self.assertIsNotNone(parts['parts'])