def test_get_all(self, client: FlaskClient, jwt_token: str) -> None: """ It is possible to retrieve all Todo items created by the user """ first_post = client.post( "/todo", json={"text": "test_text"}, headers={"Authorization": jwt_token}, ) second_post = client.post( "/todo", json={"text": "test_text_2"}, headers={"Authorization": jwt_token}, ) first_obj_id = first_post.get_json()["obj_id"] second_obj_id = second_post.get_json()["obj_id"] res = client.get("/todo", headers={"Authorization": jwt_token}) get_data = res.get_json() assert res.status_code == 200 expected_data = [ { first_obj_id: "test_text" }, { second_obj_id: "test_text_2" }, ] assert get_data == expected_data
def test_post_uuid_wrong_len(test_cli: FlaskClient, test_db: SQLAlchemy): # Too short response = test_cli.post(f'/api/v1/cens/', data=json.dumps({ 'cens': [{ 'uuid': uuid.uuid4().hex, 'created_at': str(datetime.now()) }, { 'uuid': uuid.uuid4().hex[:-1], 'created_at': str(datetime.now()) }] }), content_type='application/json') assert response.status_code == 400 response = test_cli.post(f'/api/v1/cens/', data=json.dumps({ 'cens': [{ 'uuid': uuid.uuid4().hex, 'created_at': str(datetime.now()) }, { 'uuid': uuid.uuid4().hex + uuid.uuid4().hex, 'created_at': str(datetime.now()) }] }), content_type='application/json') assert response.status_code == 400
def test_get_new_novice_broadcasting( fx_test_client: FlaskClient, fx_user: User, fx_private_key: PrivateKey, fx_session: scoped_session, ): with unittest.mock.patch('nekoyume.game.multicast') as m: fx_test_client.post('/login', data={ 'private_key': fx_private_key.to_hex(), 'name': 'test_user', }, follow_redirects=True) res = fx_test_client.get('/new') assert res.status_code == 200 move = fx_session.query(Move).filter( Move.name == 'create_novice', ).first() assert move serialized = move.serialize( use_bencode=False, include_signature=True, include_id=True, ) assert m.called args = m.call_args[1] assert serialized == args['serialized'] my_node = args['my_node'] assert isinstance(my_node, Node) assert my_node.url == 'http://localhost' broadcast = args['broadcast'] assert isinstance(broadcast, typing.Callable) assert broadcast.__name__ == 'broadcast_move'
def test_intersection_xlsx(self, client: FlaskClient): token = self.get_token(client, admin=True) # Warstwa do testów path = os.path.join(TEST_DATA_DIR, 'layers', 'correct_3857.geojson') file_request = { 'file[]': (BytesIO(open(path, 'rb').read()), 'correct_3857.geojson'), 'name': 'test_points' } r = client.post('/api/layers?token={}'.format(token), data=file_request, follow_redirects=True, content_type='multipart/form-data') lid = r.json['layers']['id'] data = { # bbox Polski "geometry": { "coordinates": [[[14.1228848600001, 49.002046518], [14.1228848600001, 54.836416667], [24.1457830750001, 54.836416667], [24.1457830750001, 49.002046518], [14.1228848600001, 49.002046518]]], "type": "Polygon" } } r = client.post( f'/api/analysis/intersection/{lid}?token={token}&response_type=xlsx', data=json.dumps(data)) assert r.status_code == 200
def test_add_follow_up_note(client: FlaskClient, admin_login): from dal.customer import Installation from dal.customer import InstallationFollowUp from dal.user import Commentable inst_id = Installation.query.first().id date = datetime.datetime.utcnow() + relativedelta(days=7) payload = { 'installation_id': inst_id, 'alert_group_id': 1, 'next_follow_up': front_end_date(date), 'comment': 'This is a user note' } resp = client.post(endpoint('/customers/installations/follow-up'), json=payload) assert resp.status_code == 401 resp = client.post(endpoint('/customers/installations/follow-up'), json=payload, headers=admin_login) assert resp.status_code == 200 assert 'id' in resp.json n = Commentable.query.count() assert n == 1 follow_ups = InstallationFollowUp.query.all() assert len(follow_ups) == 1
def test_add_installation_financial_info(client: FlaskClient, admin_login): from dal.customer import InstallationFinancing from dal.customer import Installation inst_id = Installation.query.first().id data = { 'installation_id': inst_id, 'financial_entity_id': 1, 'status_id': 1, 'request_date': front_end_date(), 'requested_amount': 1500000, 'assigned_official': 'Pedro Juan', 'official_phone': '8095659869', 'official_email': '*****@*****.**', 'insurance': 120000, 'number_of_payments': 30, 'payments_amount': 50000 } error = client.post(endpoint('/customers/installations/financing'), json=data) assert error.status_code == 401 assert 'error' in error.json resp = client.post(endpoint('/customers/installations/financing'), json=data, headers=admin_login) assert resp.status_code == 200 assert 'id' in resp.json assert InstallationFinancing.query.first() is not None
def test_add_users_group(client: FlaskClient, admin_login): from dal.user import User client.post( endpoint('/users'), json={ 'first_name': 'John', 'last_name': 'Smith', 'email': '*****@*****.**', 'roles': [1], # admin 'attributes': {} }, headers=admin_login ) resp = client.post(endpoint('/user/groups')) assert resp.status_code == 401 users = User.query.all() assert len(users) == 2 resp = client.post(endpoint('/user/groups'), headers=admin_login, json={ 'ids': [r.id for r in users], 'name': 'Field Engineers'}) assert resp.status_code == 200 assert 'id' in resp.json
def logged_in_client(client: FlaskClient) -> FlaskClient: email, password = "******", "Dumm123!" client.post( "/register", json={"email": email, "password": password}, ) return client
def test_update_about(client: FlaskClient, user_client: FlaskClient, stuff_client: FlaskClient, app: Flask, data: dict, status_code: int) -> None: url = "/about" article = create_article(app) res = client.post(url, json=data) assert res.status_code == 401 res = user_client.post(url, json=data) assert res.status_code == 403 res = stuff_client.post(url, json=data) assert res.status_code == status_code if status_code == 400: return with app.app_context(): about = About.query.filter_by().first() assert about assert about.article == article.slug res = stuff_client.post(url, json=data) with app.app_context(): abouts = About.query.all() assert len(abouts) == 1
def test_create_article(client: FlaskClient, user_client: FlaskClient, stuff_client: FlaskClient, app: Flask, title: str, abstract: str, content: str, status_code: int) -> None: url = "/articles" data = { "title": title, "abstract": abstract, "content": content, } res = client.post(url, json=data) assert res.status_code == 401 res = user_client.post(url, json=data) assert res.status_code == 403 res = stuff_client.post(url, json=data) assert res.status_code == status_code if status_code == 400: return res = stuff_client.post(url, json=data) assert res.status_code == 400 with app.app_context(): article = Article.query.filter_by(title=title).first() assert article assert article.slug == slugify(article.title) assert article.abstract == abstract assert article.content == content assert article.author
def test_update_country_successful_response(app_test_client: FlaskClient, country_summary: Dict[str, Union[str, int]]): """ Test updating one country with success. Args: app_test_client (FlaskClient): App's HTTP client. country_summary (Dict[str, Union[str, int]]): Summary message example. """ clean_database() original_new_confirmed_number = country_summary["new_confirmed"] updated_new_confirmed_number = country_summary["new_confirmed"] + 100 app_test_client.post("countries/", json=country_summary) pre_update_get_response = app_test_client.get( f"countries/{country_summary['country_code']}") assert (pre_update_get_response.json["new_confirmed"] == original_new_confirmed_number) country_summary["new_confirmed"] = updated_new_confirmed_number response = app_test_client.patch( f"/countries/{country_summary['country_code']}", json=country_summary) assert response.status_code == 200 post_update_get_response = app_test_client.get( f"countries/{country_summary['country_code']}") assert (post_update_get_response.json["new_confirmed"] == updated_new_confirmed_number)
def test_edit_user(test_app, client: FlaskClient): """Tests editing a user's info, logging out and then logging in with new info.""" new_user = "******" new_pass = "******" resp = client.post( "/user/edit", data={ "username": new_user, "password": new_pass }, follow_redirects=True, ) assert request.path == "/" client.delete("/logout") resp = client.post( "/login", data={ "username": new_user, "password": new_pass }, follow_redirects=True, ) assert resp.status_code == 200 assert request.path == "/"
def test_run_tl_busy(test_client: testing.FlaskClient, sample_salt: str, sample_signature: str) -> None: test_client.post('/run_tl', data=dict(salt=sample_salt, signature=sample_signature)) post_return = test_client.post('/run_tl', data=dict(salt=sample_salt, signature=sample_signature)) assert post_return.status_code == HTTPStatus.TOO_MANY_REQUESTS
def test_user_creation(client: FlaskClient): response = client.post('/api/v1/auth/register', json={ 'name':"test2", 'password':"******", 'email':"*****@*****.**" }) user_id = response.json['_id'] assert response.status_code == 200 response = client.post('/api/v1/auth/token', json={ 'email':"*****@*****.**", 'password':'******' }) assert response.status_code == 401 response = client.post('/api/v1/auth/token', json={ 'email':"*****@*****.**", 'password':"******" }) assert response.status_code == 200 and response.json['access_token'] is not None User.objects(id=user_id).get().delete()
def test_api_key_restriction(client: FlaskClient): """ Make calls to routes that are API key restricted, make sure they complain if no API key is provided as a parameter and accept when correct API key is provided. """ # Try routes without API key, expect complaint about missing API key for path in _KEY_RESTRICTED_ROUTES: resp = client.post(path) assert resp.status_code == 200 assert resp.content_type == "application/json; charset=utf-8" assert isinstance(resp.json, dict) assert "errmsg" in resp.json.keys( ) and "missing API key" in resp.json["errmsg"] # Try routes w. correct API key, expect no complaints about missing API key # This only runs in the CI testing environment, which creates the dummy key global DUMMY_API_KEY # TODO: Fix me if False and IN_CI_TESTING_ENV: for path in _KEY_RESTRICTED_ROUTES: resp = client.post(f"{path}?key={DUMMY_API_KEY}") assert resp.status_code == 200 assert resp.content_type == "application/json; charset=utf-8" assert isinstance(resp.json, dict) assert "errmsg" not in resp.json.keys() # This route requires special handling since it receives JSON via POST resp = client.post( "/register_query_data.api", data=json.dumps(dict()), content_type="application/json", ) assert resp.status_code == 200 assert resp.content_type == "application/json; charset=utf-8" assert "errmsg" in resp.json and "missing API key" in resp.json["errmsg"]
def test_link_deletion(user_client: FlaskClient) -> None: create_from_file(user_client, "europe.xls") for link_name in links: link = fetch("Link", name=link_name) user_client.post(f"/delete/link/{link.id}") assert len(fetch_all("Device")) == 33 assert len(fetch_all("Link")) == 38
def test_html_to_pdf(client: FlaskClient, admin_login: dict): from urllib.parse import quote resp = client.post(endpoint('/to-pdf'), json={}) assert resp.status_code == 401 assert resp.json['error'] == 'Token is missing!' resp = client.post(endpoint('/to-pdf'), json={}, headers=admin_login) assert resp.status_code == 400 assert resp.json['error'] == 'Missing necessary arguments' data = { 'html': b64encode(quote('<div><h1>Hello</h1></div>').encode()).decode(), 'styles': b64encode(quote('<style>h1 {color: red;}</style>').encode()).decode(), 'extra_css': [ b64encode( quote( 'https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' ).encode()).decode() ], 'filename': 'filename' } resp = client.post(endpoint('/to-pdf'), json=data, headers=admin_login) assert resp.status_code == 200 assert isinstance(resp.data, bytes) assert resp.content_type == 'application/pdf' assert resp.headers[ 'Content-Disposition'] == "attachment; filename=filename.pdf"
def test_device_deletion(user_client: FlaskClient) -> None: create_from_file(user_client, "europe.xls") for device_name in routers: device = fetch("Device", name=device_name) user_client.post(f"/delete/device/{device.id}") assert len(fetch_all("Device")) == 18 assert len(fetch_all("Link")) == 18
def test_create_new_bookmark( test_app, client: FlaskClient, mocked_responses: RequestsMock ): mocked_responses.add( GET, "https://example.com/", body="""<html> <head><title>Random</title></head><body><p> Lorem ipsum dolor sit amet, consectetur adipiscing elit </p></body></html> """, ) bookmark_data = { "url": "https://example.com", "tags": "testing,bookmark", "path": "not classified", "submit": "true", } resp = client.post("/bookmarks/new", data=bookmark_data) assert resp.status_code == 302 assert not b"invalid" in resp.data resp = client.post("/bookmarks/new", data=bookmark_data, follow_redirects=True) assert resp.status_code == 200 assert b"testing, bookmark" in resp.data assert b"https://example.com" in resp.data assert b"Random" in resp.data
def test_multi_mws(client: FlaskClient): """test Router.route with multiple middlewares""" admin = 'Mehdi' headers = { 'content-type': 'application/json', 'admin': admin, 'Authorization': 'whatever' } resp = client.post('/multi-mws', headers=headers) assert resp.status_code == 200 assert resp.json.get('success') assert resp.json.get('admin') == admin resp = client.post('/multi-mws') assert resp.status_code == 401 headers = { 'Authorization': 'whatever', } resp = client.post('/multi-mws', headers=headers) assert resp.status_code == 403 headers = {'admin': admin, 'Authorization': 'whatever'} resp = client.post('/multi-mws', headers=headers) assert resp.status_code == 400
def test_intersection_json_no_match(self, client: FlaskClient): token = self.get_token(client, admin=True) # Warstwa do testów path = os.path.join(TEST_DATA_DIR, 'layers', 'correct_3857.geojson') file_request = { 'file[]': (BytesIO(open(path, 'rb').read()), 'correct_3857.geojson'), 'name': 'test_points' } r = client.post('/api/layers?token={}'.format(token), data=file_request, follow_redirects=True, content_type='multipart/form-data') lid = r.json['layers']['id'] data = { "geometry": { # bbox lubelskiego "type": "Polygon", "coordinates": [[[20.994873046875, 52.42252295423907], [21.258544921875, 50.240178884797025], [24.32373046875, 50.240178884797025], [24.01611328125, 52.30176096373671], [20.994873046875, 52.42252295423907]]] } } r = client.post( f'/api/analysis/intersection/{lid}?token={token}&response_type=json', data=json.dumps(data)) assert r.status_code == 200 assert r.json == {"data": []}
def test_notification_toggle_bad_requests(client: FlaskClient): # no body response = client.post("/location") assert response.status_code == 400 # invalid json response = client.post("/location", data='{"inv', content_type='application/json') assert response.status_code == 400 # wrong json key response = client.post("/location", data='{"wrongkey": "true"}', content_type='application/json') assert response.status_code == 400 # wrong value response = client.post("/location", data='{"notifications": "asdf"}', content_type='application/json') assert response.status_code == 400 # wrong value response = client.post("/location", data='{"notifications": [123, 456]}', content_type='application/json') assert response.status_code == 400
def test_login_post(session: Session, client: FlaskClient) -> None: kwargs = { "email": "*****@*****.**", "password": "******", "can_login": True } user = User(**kwargs) session.add(user) session.flush() response = client.post("/user/login", data=kwargs) assert response.status_code == 302 # wrong password d = dict(kwargs) d["password"] = "******" response = client.post("/user/login", data=d) assert response.status_code == 401 # login disabled # pyre-fixme[8]: Attribute has type `Column`; used as `bool`. user.can_login = False session.flush() response = client.post("/user/login", data=kwargs) assert response.status_code == 401
def test_base_services(user_client: FlaskClient) -> None: user_client.post("/update/NetmikoConfigurationService", data=netmiko_ping) assert len(fetch_all("NetmikoConfigurationService")) == 3 assert len(fetch_all("Service")) == 25 user_client.post("/update/NetmikoFileTransferService", data=file_transfer_service) assert len(fetch_all("NetmikoFileTransferService")) == 1 assert len(fetch_all("Service")) == 26
def test_get_saved_receipts(test_client: FlaskClient, client_headers: dict, client: User): first_ingredient, second_ingredient, first_step, second_step = prepare_create_receipt( ) receipt = Receipt( name='Name', description='Cool', calories=200, ingredients=[first_ingredient, second_ingredient], steps=[first_step, second_step], ) session.add(receipt) session.commit() test_client.post(f'/api/client/v1/receipts/{receipt.id}/save/', headers=client_headers) response = test_client.get(f'/api/client/v1/receipts/?user_id={client.id}', headers=client_headers) result = response.json['result'] actual = len(result) expected = 1 assert actual == expected actual = result[0] expected = ReceiptClientSchema().dump(receipt) assert actual == expected
def test_it_updates_the_access_token_when_exchanging( test_client: FlaskClient) -> None: original_orcid_token = OrcidToken('0000-0002-1825-0097', 'old-access-token', expires_at(1234)) db.session.add(original_orcid_token) db.session.commit() with requests_mock.Mocker() as mocker: mocker.post('http://www.example.com/oauth/token', json={ 'access_token': '1/fFAGRNJru1FTz70BzhT3Zg', 'expires_in': 3920, 'foo': 'bar', 'token_type': 'Bearer', 'orcid': '0000-0002-1825-0097', 'name': 'Josiah Carberry' }) mocker.get( 'http://www.example.com/api/v2.1/0000-0002-1825-0097/record', status_code=404) test_client.post('/oauth2/token', data={ 'client_id': 'client_id', 'client_secret': 'client_secret', 'redirect_uri': 'http://www.example.com/client/redirect', 'grant_type': 'authorization_code', 'code': '1234' }) assert OrcidToken.query.count() == 1 assert original_orcid_token.access_token == '1/fFAGRNJru1FTz70BzhT3Zg' assert original_orcid_token.expires_at == expires_at(3920)
def test_bad_request_registration(client: FlaskClient): response = client.post('/api/v1/auth/register', json={}) assert response.status_code == 400 response = client.post('/api/v1/auth/register', json={'name':'a'}) assert response.status_code == 400
def test_get_items_from_order(client: FlaskClient) -> None: item_id = client.get("/items/").json["data"]["data"][0]["id"] order_id = client.post("/orders/").json["data"]["data"]["id"] client.post(f"/orders/{order_id}/items/", json={"id": item_id}).json result = client.get(f"/orders/{order_id}/items/").json assert len(result["data"]["data"]) == 1 assert result["data"]["data"][0]["id"] == item_id
def test_task_added(self, client: FlaskClient): client.post('tasks/add-task/', data={'task': 'Task'}, follow_redirects=True) tasks = Task.query.all() assert len(tasks) == 1 task = tasks[0] assert task.description == 'Task' assert task.active is True
def jwt_token(client: FlaskClient) -> str: """ A JWT token for a new signed up user. """ credentials = {"email": "*****@*****.**", "password": "******"} client.post("/auth/signup", json=credentials) result_from_login = client.post("/auth/login", json=credentials) jwt_token = "Bearer " + str(result_from_login.get_json()["token"]) return jwt_token
class fillinTest(unittest.TestCase): def setUp(self): self.app = app self.app.testing = True self.client = FlaskClient(self.app, response_wrapper=FormWrapper) def tearDown(self): pass def test_login_form(self): response = self.client.get('/login-form') response.form.fields['username'] = "******" assert 'Missing password' in response.form.submit(self.client).data response = self.client.get('/login-form') response.form.fields['password'] = "******" assert 'Missing username' in response.form.submit(self.client).data response = self.client.get('/login-form') response.form.fields['username'] = "******" response.form.fields['password'] = "******" assert 'Welcome test' in response.form.submit(self.client).data def test_data_injection(self): response = self.client.get('/login-form') response.form.fields['password'] = "******" inject_data = {'username': '******'} response = response.form.submit(self.client, data=inject_data) assert 'Welcome test' in response.data def test_hidden_field_form(self): response = self.client.get('/hidden-field-form') response = response.form.submit(self.client) assert 'Hidden field received' in response.data response = self.client.post('/hidden-field-form') assert 'Missing the hidden field' in response.data def test_checkbox_form(self): response = self.client.get('/checkbox-field-form') response = response.form.submit(self.client) assert "Checkbox did not check" in response.data response.form.fields['checkbox_field'] = True response = response.form.submit(self.client) assert "Checkbox checked" in response.data def test_links_get(self): response = self.client.get('/link') self.assertEquals(2, len(response.links()), '2 links are parsed from the source') self.assertEquals('link1', response.link('#link1').text) self.assertEquals('link2', response.link('.link').text) def test_link_click(self): response = self.client.get('/link') response = response.link("#link1").click(self.client) self.assertEquals(200, response.status_code)
class AuDTestCase(unittest.TestCase): def setUp(self): prepare_db_for_tests() self.app = FlaskClient(app, response_wrapper=FormWrapper) self.app.application.config["CSRF_ENABLED"] = False self.depute = Depute(test_depute).save() self.user = create_user("test", "test") self.ctx = app.test_request_context() self.ctx.push() def login(self): return self.app.post(url_for("login"), data={"username": "******", "password": "******"}, follow_redirects=True) def tearDown(self): self.ctx.pop() def test_empty_home(self): Depute.collection.remove() rv = self.app.get(url_for("home")) self.assertTrue("Éric Ciotti" not in rv.data) def test_deputy_on_home(self): rv = self.app.get(url_for("home")) self.assertTrue("Éric Ciotti" in rv.data) def test_deputy_personnal_page(self): rv = self.app.get(url_for("depute", depute=self.depute.slug)) self.assertTrue("Éric Ciotti" in rv.data) def test_link_to_nosdeputes_fr(self): rv = self.app.get(url_for("depute", depute=self.depute.slug)) self.assertTrue("http://www.nosdeputes.fr/eric-ciotti" in rv.data) def test_link_to_memopol(self): rv = self.app.get(url_for("depute", depute=self.depute.slug)) self.assertTrue('https://memopol.lqdn.fr/france/assemblee/depute/EricCiotti/' in rv.data) def test_link_to_an(self): rv = self.app.get(url_for("depute", depute=self.depute.slug)) self.assertTrue("http://www.assembleenationale.fr/13/tribun/fiches_id/330240.asp" in rv.data) def test_display_group(self): rv = self.app.get(url_for("depute", depute=self.depute.slug)) self.assertTrue(self.depute.groupe_sigle.encode("Utf-8") in rv.data) def test_login_on_home(self): rv = self.app.get(url_for("home")) self.assertTrue(url_for("login") in rv.data) def test_login_page(self): rv = self.app.get(url_for("login")) self.assertTrue("Se connecter" in rv.data) self.assertTrue("Login" in rv.data) self.assertTrue("Mot de passe" in rv.data) def test_login_form(self): rv = self.app.get(url_for("login")) rv.form.fields["username"] = "******" rv.form.fields["password"] = "******" rv = rv.form.submit(self.app) self.assertEqual(rv.status_code, 302) def test_login_success(self): rv = self.login() self.assertTrue("Login success!" in rv.data) self.assertTrue("Se déconnecter" in rv.data) def test_logout(self): rv = self.app.post(url_for("login"), data={"username": "******", "password": "******"}, follow_redirects=True) self.app.get(url_for("logout")) self.assertTrue("Login" in rv.data) def test_login_bad_login(self): rv = self.app.post(url_for("login"), data={"username": "******", "password": "******"}, follow_redirects=True) self.assertTrue("This user doesn't exist or the password is wrong" in rv.data) def test_login_bad_password(self): rv = self.app.post(url_for("login"), data={"username": "******", "password": "******"}, follow_redirects=True) self.assertTrue("This user doesn't exist or the password is wrong" in rv.data) def test_register_on_home(self): rv = self.app.get(url_for("home")) self.assertTrue(url_for("register") in rv.data) def test_register_page(self): rv = self.app.get(url_for("register")) self.assertTrue("Login" in rv.data) self.assertTrue("Mot de passe" in rv.data) self.assertTrue("Confirmer le mot de " in rv.data) def test_register_form(self): rv = self.app.get(url_for("register")) rv.form.fields["username"] = "******" rv.form.fields["password"] = "******" rv.form.fields["confirm_password"] = "******" rv = rv.form.submit(self.app) self.assertEqual(rv.status_code, 302) def test_register_create_user(self): before = User.collection.count() self.app.post(url_for('register'), data={"username": "******", "password": "******", "confirm_password": "******"}, follow_redirects=True) self.assertEqual(before + 1, User.collection.count()) user = User.collection.find_one({"username": "******"}) self.assertFalse(user is None) self.assertTrue(user.test_password("pouet")) def test_empty_fields(self): rv = self.app.post(url_for('register'), data={"username": "", "password": "", "confirm_password": ""}, follow_redirects=True) self.assertTrue("This field is required" in rv.data) def test_duplicated_user(self): rv = self.app.post(url_for('register'), data={"username": "******", "password": "******", "confirm_password": "******"}, follow_redirects=True) self.assertTrue("Ce pseudonyme est déjà pris." in rv.data) def test_password_doesnt_match(self): rv = self.app.post(url_for('register'), data={"username": "******", "password": "******", "confirm_password": "******"}, follow_redirects=True) self.assertTrue("Les mots de passe ne correspondent pas." in rv.data) def test_register_login(self): rv = self.app.post(url_for('register'), data={"username": "******", "password": "******", "confirm_password": "******"}, follow_redirects=True) self.assertTrue("Votre compte a correctement été créé." in rv.data) self.assertTrue(url_for("logout") in rv.data) def test_register_on_login(self): rv = self.app.post(url_for('login')) self.assertEqual(rv.data.count(url_for('register')), 2) def test_follow_show_on_deputy_page(self): rv = self.app.get(url_for("depute", depute=self.depute.slug)) self.assertTrue("Adopter ce député" in rv.data) self.assertTrue(url_for("adopter", depute=self.depute.slug) in rv.data) def test_follow_not_logged_in(self): rv = self.app.get(url_for("adopter", depute=self.depute.slug)) self.assertEqual(rv.status_code, 302) def test_adopt_logged(self): self.login() rv = self.app.get(url_for("adopter", depute=self.depute.slug)) self.assertEqual(rv.status_code, 302) def test_adopt_is_marked(self): self.login() rv = self.app.get(url_for("adopter", depute=self.depute.slug), follow_redirects=True) self.assertTrue("Se déconnecter" in rv.data) self.assertTrue("Adopté" in rv.data) def test_no_adopters_on_deputy_page(self): rv = self.app.get(url_for("depute", depute=self.depute.slug)) self.assertTrue("Personne n'a adopté ce député" in rv.data) def test_show_deputy_adopters(self): self.login() self.app.get(url_for("adopter", depute=self.depute.slug), follow_redirects=True) rv = self.app.get(url_for("depute", depute=self.depute.slug)) self.assertTrue("%s" % self.user.username in rv.data)
class fillinTest(unittest.TestCase): def setUp(self): self.app = app self.app.testing = True self.client = FlaskClient(self.app, response_wrapper=FormWrapper) def tearDown(self): pass def test_login_form(self): response = self.client.get('/login-form') response.form.fields['username'] = "******" assert 'Missing password' in response.form.submit(self.client).data response = self.client.get('/login-form') response.form.fields['password'] = "******" assert 'Missing username' in response.form.submit(self.client).data response = self.client.get('/login-form') response.form.fields['username'] = "******" response.form.fields['password'] = "******" assert 'Welcome test' in response.form.submit(self.client).data def test_data_injection(self): response = self.client.get('/login-form') response.form.fields['password'] = "******" inject_data = {'username': '******'} response = response.form.submit(self.client, data=inject_data) assert 'Welcome test' in response.data def test_hidden_field_form(self): response = self.client.get('/hidden-field-form') response = response.form.submit(self.client) assert 'Hidden field received' in response.data response = self.client.post('/hidden-field-form') assert 'Missing the hidden field' in response.data def test_checkbox_form(self): response = self.client.get('/checkbox-field-form') response = response.form.submit(self.client) assert "Checkbox did not check" in response.data response.form.fields['checkbox_field'] = True response = response.form.submit(self.client) assert "Checkbox checked" in response.data def test_select_form(self): response = self.client.get('/select-field-form') response = response.form.submit(self.client) assert "select1" in response.data response.form.fields['select_field'] = "select2" response = response.form.submit(self.client) assert "select2" in response.data def test_radio_form(self): response = self.client.get('/radio-field-form') response = response.form.submit(self.client) assert "No Radio Value Selected" in response.data response.form.fields['radio_field'] = "1" response = response.form.submit(self.client) assert "Selected 1" in response.data response.form.fields['radio_field'] = "0" response = response.form.submit(self.client) assert "Selected 0" in response.data def test_empty_field_form(self): response = self.client.get('/empty-field-form') response.form.fields['text1'] = 'hi' # response.form.fields['text2'] = '' response = response.form.submit(self.client) assert "No None" in response.data response = self.client.get('/empty-field-form') response = response.form.submit(self.client) assert "No None" in response.data def test_links_get(self): response = self.client.get('/link') self.assertEquals(2, len(response.links()), '2 links are parsed from the source') self.assertEquals('link1', response.link('#link1').text) self.assertEquals('link2', response.link('.link').text) def test_link_click(self): response = self.client.get('/link') response = response.link("#link1").click(self.client) self.assertEquals(200, response.status_code) def test_file_form(self): response = self.client.get('file-form') response.form.fields['text'] = 'text' with open("README.rst") as fh: response.form.files['file'] = fh response = response.form.submit(self.client) assert "File submitted" in response.data def test_no_file_form(self): response = self.client.get('file-form') response.form.fields['text'] = 'text' response = response.form.submit(self.client) assert "File not submitted" in response.data def test_bad_file_form(self): response = self.client.get('file-form') response.form.fields['text'] = 'text' response.form.files['file'] = 'not a file type' with self.assertRaises(TypeError): self.response = response.form.submit(self.client) def test_bad_input_form(self): response = self.client.get('file-form') response.form.fields['text'] = 'text' with open("README.rst") as fh, self.assertRaises(ValueError): response.form.files['not_file_name'] = fh response = response.form.submit(self.client)