def test_check_pass_in_headers(): with app.test_client() as c: respon = c.get('/csrf_test') assert_equals(respon.status_code, 200) respon = c.post('/csrf_test', headers = [('X-CSRFToken', respon.data)]) assert_equals(respon.status_code, 200)
def test_check_pass_in_form(): with app.test_client() as c: respon = c.get('/csrf_test') assert_equals(respon.status_code, 200) respon = c.post('/csrf_test', data = {'CSRF_TOKEN': respon.data}) assert_equals(respon.status_code, 200)
def test_connectivity(): """ test to make sure the server can spin up and we can connect to endpoints """ # endpoints to test endpoints = [{ "endpoint": "/stacks", "status_code": 200 }, { "endpoint": "/stacks/error", "status_code": 200 }, { "endpoint": "/stacks/logout", "status_code": 302 }, { "endpoint": "/stacks-api/login", "status_code": 200 }, { "endpoint": "/stacks-api/outputs?stackname=" + os.environ.get("STACK"), "status_code": 200 }, { "endpoint": "/stacks-api/user", "status_code": 200 }] for endpoint in endpoints: with app.test_client() as c: print(endpoint["endpoint"]) req = c.get(endpoint["endpoint"]) assert req.status_code == endpoint["status_code"]
def test_get_orders_success() -> None: with app.test_client() as client: res: Response = client.get('/vendors/1/products/1/orders') payload: List[Dict[str, Union[int, str]]] = res.get_json() now: datetime = datetime.now() dt_fmt: str = '%Y-%m-%d' expected: List[Dict[str, Union[int, str]]] = [ { 'id': 1, 'fullName': 'Linus Torvalds', 'orderDate': (now - relativedelta(months=1)).strftime(dt_fmt), }, { 'id': 2, 'fullName': 'Elon Musk', 'orderDate': (now - relativedelta(months=1)).strftime(dt_fmt), }, { 'id': 3, 'fullName': 'Alan Turing', 'orderDate': (now - relativedelta(months=4)).strftime(dt_fmt), }, { 'id': 4, 'fullName': 'Katherine Johnson', 'orderDate': (now - relativedelta(months=4)).strftime(dt_fmt), }, ] assert res.status_code == 200 assert payload == expected
def test_token_rendered_in_template(): app.add_url_rule('/csrf_test/template', view_func = lambda: render_template_string("{{ CSRF_TOKEN() }}")) with app.test_client() as c: respon_data = c.get('/csrf_test/template').data assert_equals(respon_data, session['CSRF_TOKEN'])
def test_get_orders_where_product_doesnt_exist() -> None: with app.test_client() as client: res: Response = client.get('vendors/1/products/176/orders') payload: Dict[str, str] = res.get_json() expected: Dict[str, str] = {'message': 'Product not found.'} assert res.status_code == 404 assert payload == expected
def test_check_fail_wrong_token_in_header(): with app.test_client() as c: c.get('/csrf_test') respon = c.post('/csrf_test', headers = [('X-CSRFToken', uuid.uuid4().hex)]) assert_equals(respon.status_code, 403)
def test_get_products_where_vendor_doesnt_exist() -> None: with app.test_client() as client: res: Response = client.get('/vendors/999/products') payload: Dict[str, str] = res.get_json() expected: Dict[str, str] = {'message': 'Vendor not found.'} assert res.status_code == 404 assert payload == expected
def test_return_of_load_ajax3_4(self): tester = app.test_client(self) response = tester.post( '/load_ajax3', data='"THTR 23D~SCHMEDAKE A J~T R~2:00pm - 4:50pm"', content_type='application/json;charset=UTF-8') self.assertTrue(b'"T R~2:00pm - 4:50pm"' in response.data)
def test_token_passed_in_cookies(): with app.test_client() as c: respon = c.get('/csrf_test') set_cookie_header = 'X-CSRFToken=' + respon.data assert any(map( lambda x: x[1].startswith(set_cookie_header), respon.headers))
def test_check_fail_without_token(): with app.test_client() as c: respon = c.post('/csrf_test') assert_equals(respon.status_code, 403) c.get('/csrf_test') respon = c.post('/csrf_test') assert_equals(respon.status_code, 403)
def test_return_of_load_ajax1_2(self): tester = app.test_client(self) #curl --header"Content=Type: application/json;charset=UTF-8"--request POST --data "'Art'" #response = curl--header"Content=Type: application/json;charset=UTF-8"--request POST --data "'Art'" response = tester.post('/load_ajax', data='"Anthropology"', content_type='application/json;charset=UTF-8') self.assertTrue(b'"ANTH 199RA"' in response.data)
def client(): app.config.from_pyfile('{}/app/config/test.py'.format(cfg.BASE_DIR)) client = app.test_client() with app.app_context(): db.create_all() yield client os.unlink(app.config['DATABASE'])
def test_health_endpoint(): """ make sure health endpoint is working since the load balancer will hitting this endpoint on AWS """ with app.test_client() as c: req = c.get("/stacks/health") assert req.status_code == 200 assert req.data.decode() == "Healthy."
def test_logout(): with app.test_client() as c: if login(c).status_code != 200: return c.get('/admin/logout') respon = c.get('/admin/login/test').data assert_equals(respon, '0')
def test_404(self): print('should return a status_code of 404') with patch('services.processMovieNames.Session.get', side_effect=mocked_requests_get) as mocked_get: # Arrange client = app.test_client(self) # Act response = client.get('/api/random') # Assert self.assertEqual(response.status_code, 404)
def test_white_list(): @app.route('/csrf_test/white_list', methods = ['POST']) @disable_csrf_protection def white_list_view_func(): return '' with app.test_client() as c: respon = c.post('/csrf_test/white_list') assert_equals(respon.status_code, 200)
def setUp(self): TEST_DB = 'test_cardatabase.db' project_dir = os.path.dirname(os.path.abspath(__file__)) app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \ os.path.join(project_dir, TEST_DB) self.app = app.test_client() db.drop_all() db.create_all()
def test_client(): # Flask provides a way to test your application by exposing the Werkzeug test Client # and handling the context locals for you. testing_client = app.test_client() # Establish an application context before running the tests. ctx = app.app_context() ctx.push() yield testing_client # this is where the testing happens! ctx.pop()
def test_get_vendors_success() -> None: with app.test_client() as client: res: Response = client.get('/vendors') payload: List[Dict[str, Union[int, str]]] = res.get_json() expected: List[Dict[str, Union[int, str]]] = [ { 'id': 1, 'name': 'Tackle.io', }, ] assert res.status_code == 200 assert payload == expected
def test_logs_build_url(): """ testing that the server can build the correct url for the user to access the logs """ with app.test_client() as c: req = c.get("/stacks-api/outputs/logs?logname={1}".format( os.environ.get("STACK"), os.environ.get("LOG_GROUP"))) assert req.status_code == 200 assert json.loads( req.data.decode() )["log-url"] == "https://us-west-2.console.aws.amazon.com/cloudwatch/home?region=us-west-2#logStream:group={0}".format( os.environ.get("LOG_GROUP"))
def test_bucket_build_url(): """ testing that the server can build the correct url for the user to access the bucket """ with app.test_client() as c: req = c.get("/stacks-api/outputs/bucket?bucketname={1}".format( os.environ.get("STACK"), os.environ.get("BUCKET"))) assert req.status_code == 200 assert json.loads( req.data.decode() )["bucket-url"] == "https://s3.console.aws.amazon.com/s3/buckets/{0}".format( os.environ.get("BUCKET"))
def app(request): """Session-wide test `Flask` application.""" app = app1.test_client() # Establish an application context before running the tests. ctx = app1.app_context() ctx.push() def teardown(): ctx.pop() request.addfinalizer(teardown) return app
def test_auth_check(): with app.test_client() as c: respon = c.get('/admin/login/test').data assert_equals(respon, '0') if login(c).status_code != 200: return respon = c.get('/admin/login/test').data assert_equals(respon, '1') with c.session_transaction() as sess: sess['TOKEN'] = uuid.uuid4().hex respon = c.get('/admin/login/test').data assert_equals(respon, '0')
def test_service_page_build_url(): """ testing that the server can build the correct url for the user to access the ECS service page """ with app.test_client() as c: req = c.get( "/stacks-api/outputs/servicepage?clustername={1}&servicename={2}". format(os.environ.get("STACK"), os.environ.get("CLUSTER"), os.environ.get("WEBSERVICE_NAME"))) assert req.status_code == 200 assert json.loads( req.data.decode() )["service-page-url"] == "https://us-west-2.console.aws.amazon.com/ecs/home?region=us-west-2#/clusters/{0}/services/{1}/details".format( os.environ.get("CLUSTER"), os.environ.get("WEBSERVICE_NAME"))
def test_movieRoute(self): print('should return a status_code of 200') with patch('services.processMovieNames.Session.get', side_effect=mocked_requests_get) as mocked_get: # Arrange client = app.test_client(self) # Act response = client.post('/api/movie', data=json.dumps({"filmworld": "fw0076759"}), content_type='application/json') data = ast.literal_eval(response.data.decode("UTF-8")) # Assert self.assertEqual(response.status_code, 200) self.assertEqual(data['code'], 0) self.assertEqual(data['cinemas'], {"filmworld": {"Price": "29.5"}}) mocked_get.assert_called_once
def test_change_passwd_error(): with app.test_client() as c: if login(c, username = '******').status_code != 200: return respon = c.get('/admin/login?username=test2') respon = json.loads(respon.data) oldpwhash = bcrypt.hashpw('wrong_old_pw', respon['account_salt']) newpwhash = bcrypt.hashpw('newpw', respon['session_salt']) respon = c.post('/admin/change_passwd', data = {'oldpwhash': oldpwhash, 'newpwhash': newpwhash}) respon = json.loads(respon.data) assert_equals(respon['err_code'], -1) assert_equals(login(c, 'test2', 'newpw').status_code, 403) assert_equals(login(c, 'test2', 'test').status_code, 200)
def test_get_products_success() -> None: with app.test_client() as client: res: Response = client.get('/vendors/1/products') payload: List[Dict[str, Union[int, str]]] = res.get_json() expected: List[Dict[str, Union[int, str]]] = [ { 'id': 1, 'title': 'Tackle Amazon Machine Image', 'listingType': 'ami', 'price': 1000, }, { 'id': 2, 'title': 'Tackle for GovCloud', 'listingType': 'saas', 'price': 5000, }, ] assert res.status_code == 200 assert payload == expected
def test_views_scheduleMaker_load(self): tester = app.test_client(self) response = tester.get('/class-select', content_type='html/text') self.assertTrue(b'Subject:' in response.data)
def test_views_scheduleMaker(self): tester = app.test_client(self) response = tester.get('/class-select', content_type='html/text') self.assertEqual(response.status_code, 200)
def test_views_index_load(self): tester = app.test_client(self) response = tester.get('/', content_type='html/text') self.assertTrue(b'Gold Scheduler' in response.data)
def test_views_index(self): tester = app.test_client(self) response = tester.get('/', content_type='html/text') self.assertEqual(response.status_code, 200)
def test_login(): with app.test_client() as c: respon = login(c) assert_equals(respon.status_code, 200)
def test_index(self): test = app.test_client(self) response = test.get('/login', content_type='html/text') self.assertEqual(response.status_code, 200)
def test_check_fail_wrong_token_in_form(): with app.test_client() as c: c.get('/csrf_test') respon = c.post('/csrf_test', data = {'CSRF_TOKEN': uuid.uuid4().hex}) assert_equals(respon.status_code, 403)
def client(): app.config['TESTING'] = True with app.test_client() as client: yield client
def setup(self): tester = app.test_client(self)
def test_register(self): tester = app.test_client(self) response = tester.get('/register', content_type='html/text') self.assertEqual(response.status_code, 200)
def test_logout(self): tester = app.test_client(self) response = tester.get('/logout', content_type='html/text') self.assertEqual(response.status_code, 302)
def setUp(self): self.app = app.test_client()
def test_login_failed(): with app.test_client() as c: respon = login(c, 'test', 'wrong_pw') assert_equals(respon.status_code, 403)
def test_login(self): tester = app.test_client(self) response = tester.get('/api/v1/entries', content_type='html/text') self.assertEqual(response.status_code, 200)
def test_home(self): tester = app.test_client(self) response = tester.get('/api/v1/entries/delete_entry/<int:id>', content_type='html/text') self.assertEqual(response.status_code, 404)