def test_search_route(): """ Tests '/search' route status code """ rv = app.test_client().get('/search') assert rv.status_code == 200 assert b'<title>Flask Demo</title>' in rv.data
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join( basedir, TEST_DB) self.app = app.test_client() db.create_all()
def test_characters_fails_for_not_providing_name(self): tester = app.test_client(self) response = tester.get('/api/characters/') json_response = json.loads(response.data) self.assertEqual(response.status_code, 400) self.assertEqual(json_response['msg'], 'You must pass a name')
def test_characters_success_with_all_matching_list_for_a_search(self): tester = app.test_client(self) response = tester.get('/api/characters/?name=L') json_response = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertTrue(len(json_response) > 1)
def test_characters_success_the_desired_schema(self): tester = app.test_client(self) response = tester.get('/api/characters/?name=R2-D2') json_response = json.loads(response.data) json_expected = json.loads( '[{"fullName": "R2-D2","gender": "n/a","homePlanet": "Naboo","movies": ["A New Hope", "The Empire Strikes Back", "Return of the Jedi", "The Phantom Menace", "Attack of the Clones", "Revenge of the Sith"],"species":[{"averageLifespan": "indefinite", "name": "Droid"}]}]' ) response_item = json_response[0] expected_item = json_expected[0] self.assertEqual(response.status_code, 200) self.assertTrue(len(json_response) == 1) self.assertEqual(response_item['fullName'], expected_item['fullName']) self.assertEqual(response_item['gender'], expected_item['gender']) self.assertEqual(len(response_item['movies']), len(expected_item['movies'])) self.assertEqual(response_item['movies'], expected_item['movies']) self.assertEqual(len(response_item['species']), len(expected_item['species'])) self.assertEqual(response_item['species'][0]['averageLifespan'], expected_item['species'][0]['averageLifespan']) self.assertEqual(response_item['species'][0]['name'], expected_item['species'][0]['name']) self.assertEqual(response_item['species'], expected_item['species']) self.assertEqual(json_response, json_expected)
def setUp(self): app.config.from_object('tests.config') self.app = app.test_client() db.session.close() db.drop_all( ) # http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/basic_use.html db.create_all() seed_core(db) db.session.commit() self.payload = { 'payload': json.dumps({ 'salary': 50000, 'email': '*****@*****.**', 'years_experience': 1, 'years_with_current_employer': 1, 'number_of_employers': 1, 'employment_type': EmploymentType.query.first().id, 'location': EmploymentType.query.first().id, 'education': EmploymentType.query.first().id, 'perks': [], 'roles': [{ 'id': Tech.query.first().id }], 'techs': [{ 'name': 'Not already in DB' }], 'verification_request': { 'profile_url': 'https://www.linkedin.com/in/test', 'employer_name': 'Test Company', 'note': 'Test note' } }) }
def test_create_hole(reset_db, seed_course): """ GIVEN a Flask application configured for testing WHEN the POST endpoint 'holes' is requested THEN check that the response is valid """ course_uuid = pytest.course.uuid # Header headers = {'X-Consumer-Custom-ID': pytest.user_uuid} # Payload payload = { 'name': pytest.hole_name, 'number': pytest.hole_number, 'par': pytest.par, 'distance': pytest.distance } # Request response = app.test_client().post(f'/courses/{course_uuid}/holes', headers=headers, json=payload) # Response assert response.status_code == 200 response = json.loads(response.data) assert response['msg'] == 'OK' holes = response['data']['holes'] assert holes['uuid'] is not None assert holes['name'] == pytest.hole_name assert holes['number'] == pytest.hole_number assert holes['par'] == pytest.par assert holes['distance'] == pytest.distance
def test_update_hole(reset_db, seed_course, seed_hole): """ GIVEN a Flask application configured for testing WHEN the PUT endpoint 'hole' is requested THEN check that the response is valid """ hole_uuid = pytest.hole.uuid # Header headers = {'X-Consumer-Custom-ID': pytest.user_uuid} # Payload payload = { 'name': 'Bingo' } # Request response = app.test_client().put(f'/holes/{hole_uuid}', headers=headers, json=payload) # Response assert response.status_code == 200 response = json.loads(response.data) assert response['msg'] == 'OK' holes = response['data']['holes'] assert holes['name'] == payload['name']
def setUp(self): # Sample data's self.sample_zipcode = '94040' self.sample_country_code = 'us' self.sample_address = 'Franklin St New York, NY' self.client = app.test_client()
def test_get_film_by_uuid_with_db(self): client = app.test_client() uuid = FilmService.fetch_all_films(db.session).first().uuid response = client.get(f'/films/{uuid}') assert response.status_code == http.HTTPStatus.OK
def test_get_view(self): with app.test_request_context('/'), \ app.test_client(): url = request.host_url resp = requests.get(url, verify=False) assert resp.status_code == http.HTTPStatus.OK
def test_get_films_mock_db(self, mock_db_call): client = app.test_client() resp = client.get('/films') mock_db_call.assert_called_once() assert resp.status_code == http.HTTPStatus.OK assert len(resp.json) == 0
def test_update_course(reset_db, seed_course): """ GIVEN a Flask application configured for testing WHEN the PUT endpoint 'course' is requested THEN check that the response is valid """ course_uuid = pytest.course.uuid # Header headers = {'X-Consumer-Custom-ID': pytest.user_uuid} # Payload payload = {'status': 'active'} # Request response = app.test_client().put(f'/courses/{course_uuid}', headers=headers, json=payload) # Response assert response.status_code == 200 response = json.loads(response.data) assert response['msg'] == 'OK' courses = response['data']['courses'] assert courses['status'] == 'active' assert courses['uuid'] is not None
def test_create_course_fail(reset_db): """ GIVEN a Flask application configured for testing WHEN the POST endpoint 'courses' is requested THEN check that the response is valid """ # Header headers = {'X-Consumer-Custom-ID': pytest.user_uuid} # Payload payload = { 'name': None, 'line_1': pytest.line_1, 'line_2': pytest.line_2, 'city': pytest.city, 'province': pytest.province, 'country': pytest.country } # Request response = app.test_client().post('/courses', headers=headers, json=payload) # Response assert response.status_code == 400
def test_create_department_with_db_error_not_unique_409(self): client = app.test_client() data = {"name": "Fake Department"} resp = client.post('/json/departments', data=json.dumps(data), content_type='application/json') assert resp.status_code == http.HTTPStatus.CONFLICT
def test_create_department_with_db_error_validation_400(self): client = app.test_client() data = {"name": "Fake Department", "mood": "crazy"} resp = client.post('/json/departments', data=json.dumps(data), content_type='application/json') assert resp.status_code == http.HTTPStatus.BAD_REQUEST
def test_get_departments_mock_db(self): with patch('src.service.service.DepartmentService.fetch_all_departments_with_avg_salary_sort_by', autospec=True) \ as mock_db_call: client = app.test_client() resp = client.get(f'/json/departments') mock_db_call.assert_called_once() assert resp.status_code == http.HTTPStatus.OK
def test_put_department_with_db_validation_error_400(self): client = app.test_client() url = f"/json/departments/{db.session.query(Department).all()[-1].id}" data = {"name": "Fake Department", "mood": "uneasy"} resp = client.put(url, data=json.dumps(data), content_type='application/json') assert resp.status_code == http.HTTPStatus.BAD_REQUEST
def setUp(self): db.create_all() self.app = app.test_client() self.app_context = app.app_context() self.app_context.push() db_manage = DataManager() folder_path = os.path.dirname(os.path.abspath(__file__)) db_manage.load_data(folder_path)
def test_update_department_with_db_no_dep_404(self): client = app.test_client() url = "/json/departments/356345646346" data = {"name": "Update Name"} resp = client.put(url, data=json.dumps(data), content_type='application/json') assert resp.status_code == http.HTTPStatus.NOT_FOUND
def setUp(self) -> None: app.config['TESTING'] = True app.config['DEBUG'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' self.app = app.test_client() db.drop_all() db.create_all()
def setUp(self): app.config["TESTING"] = True app.config["WTF_CSRF_ENABLED"] = False app.config["DEBUG"] = False app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + TEST_DB self.app = app.test_client() db.drop_all() db.create_all()
def test_get_view_employees_with_db_param_more(self): with app.test_request_context('/'), \ app.test_client() as client: params = '?more=True' url = request.host_url[:-1] + f'{TestViews.port}/' + params resp = client.get(url, follow_redirects=True) assert resp.status_code == http.HTTPStatus.OK
def test_get_view_employees_with_db_between_dates(self): with app.test_request_context('/'), \ app.test_client() as client: params = '?date_picker1=1985-07-22&date_picker2=1992-07-22' url = request.host_url[:-1] + f'{TestViews.port}/' + params resp = client.get(url, follow_redirects=True) assert resp.status_code == http.HTTPStatus.OK
def test_client(): test_client = app.test_client() ctx = app.app_context() ctx.push() yield test_client ctx.pop()
def abort_requests(issue): auth_d = request.cookies.get("hasura_auth_uikit"); if auth_d: auth_d = json.loads(auth_d) if auth_d['user_info']: hasura_id = auth_d['user_info']['hasura_id'] username = auth_d['user_info']['username'] auth_token = auth_d['user_info']['auth_token'] u_role = auth_d['user_info']['hasura_roles'][0] headers = { "Content-Type": "application/json", "Authorization": "Bearer "+auth_token, "X-Hasura-Role": u_role } client = app.test_client() response = json.loads(client.get("/issue_editor/"+issue, headers=list(request.headers)).data) if response['editor'] == username: url = "https://data.enamor68.hasura-app.io/v1/query" rp = { "type": "select", "args": { "table": "request_abort", "columns": [ "*" ], "where": { "issue_id": { "$eq": issue }, "answer" : { "$eq" : None }, "hasura_id" :{ "$ne" : hasura_id } } } } ar_list = send_request(url,headers,rp).content.decode('utf-8') json_list = json.loads(ar_list) send_list = [] for index in range(0,len(json_list)): is_present = False for index2 in range(0,len(send_list)): if json_list[index]['hasura_id'] == send_list[index2]['hasura_id']: is_present = True break if not is_present: send_list.append(json_list[index]) return json.dumps(send_list) else: return "You are not editor of the issue" else: return "Please login and then continue"
def test_get_employees_with_db_error_connection(self): default = app.config['SQLALCHEMY_DATABASE_URI'] app.config[ 'SQLALCHEMY_DATABASE_URI'] = "mysql://root:@localhost/finalproject123" client = app.test_client() resp = client.get('/json/employees') assert resp.status_code == http.HTTPStatus.INTERNAL_SERVER_ERROR app.config['SQLALCHEMY_DATABASE_URI'] = default
def test_drop_all(self): with app.test_request_context('/'), \ app.test_client() as client: url = request.host_url[:-1] + f'{TestViews.port}/' + 'drop-all' resp = client.get(url, follow_redirects=True) message = get_flashed_messages() assert message[0] == "DB successfully dropped" assert resp.status_code == http.HTTPStatus.OK
def test_delete_view_department_with_db(self): with app.test_request_context('/'), \ app.test_client() as client: url = request.host_url[:-1] + f'{TestViews.port}/' + 'departments/' + f'delete/{TestViews.temp_id_dep}' resp = client.get(url, follow_redirects=True) message = get_flashed_messages() assert message[0] == "Department Deleted Successfully" assert resp.status_code == http.HTTPStatus.OK
def client(): """Fixture that enables flask in testing mode Yields: client: Client yielded to use in the following tests """ app.config['TESTING'] = True with app.test_client() as client: yield client
def request(self, method, uri, username, password, data=None): """Return an opened request using username and passoword.""" user_pass_bytes = bytes("{0}:{1}".format(username, password), 'ascii') headers = { 'Authorization': 'Basic ' + base64.b64encode(user_pass_bytes).decode('ascii') } with app.test_client() as client: return client.open(uri, method=method, headers=headers, data=data)
def setUp(self): app.config['DEBUG'] = True app.config['TESTING'] = True self.dbname = 'test_mockend' app.config['WTF_CSRF_ENABLED'] = False self.app = app.test_client() self.issue_default = { 'title': 'ALM - GERENCIAMENTO', 'body': 'O Problema eh que a de autenticação no sistema', 'register': '2015RI0000124', 'ugat': 'SUPOP', 'ugser': 'SUPGS', }
def setUpHelper(self): """Configure test app and upload sample data""" app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/malb-test' self.app = app.test_client() self.TEST_USERNAME = TEST_USERNAME self.TEST_MALKEY = TEST_MALKEY self.TEST_MAL = TEST_MAL db.drop_all() db.create_all() MALB.synchronize_with_mal('quetzalcoatl384', 'cXVldHphbGNvYXRsMzg0OnBhc3N3b3Jk', 4448103) MALB.upload_aa_data('../data/aaresults0.txt')
def setUp(self): app.config['DEBUG'] = True self.dbname = 'test_mockend' app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False self.app = app.test_client() int_seed = random.randint(1, 1100) register = ''.join(['2015RI00001', str(int_seed)]) self.issue_default = { 'title': 'ALM - GERENCIAMENTO', 'body': 'O Problema eh que a de autenticação no sistema', 'register': register, 'ugat': 'SUPOP', 'ugser': 'SUPGS', }
def client(request): """ Initializes a fixture for the client. :param request: :return: """ app.config['TESTING'] = True client = app.test_client() # Cleanup after request is finalized. currently not needed. def teardown(): pass request.addfinalizer(teardown) return client
def setUp(self): app.config['DEBUG'] = True self.dbname = 'test_mockend' app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False self.app = app.test_client() int_seed = random.randint(1, 1100) register = ''.join(['2015RI00001', str(int_seed)]) self.email = '*****@*****.**' % str(int_seed) self.issue_default = { 'title': 'ALM - GERENCIAMENTO', 'body': 'The problem with authentication on system', 'register': register, 'ugat': 'SUPOP', 'ugser': 'SUPGS', } self.sseclient = self.help_function_sse
def test_root_url(self): with app.test_client() as client: rv = client.get('/') assert b'Homepage' in rv.data
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, TEST_DB) self.app = app.test_client() db.create_all()