Best Python code snippet using localstack_python
test_user_views.py
Source:test_user_views.py
1import datetime2import freezegun3import pytest4import responses5from django.utils import timezone6from supportal.app.common.enums import ActivityStatus7from supportal.app.models.user import User, UserManager8from supportal.tests import utils9def _test_create_user_operation(10 client, request_user_object, request_user, user_to_create, user_email, monkeypatch11):12 user_payload = {13 "email": user_email,14 "first_name": user_to_create.first_name,15 "last_name": user_to_create.last_name,16 "address": user_to_create.address,17 "person": user_to_create.id,18 }19 # Create20 # Until we have a better way of mocking Cognito in tests, mokeypatch21 # the create_cognito_user method on the user manager22 monkeypatch.setattr(23 UserManager,24 "create_cognito_user",25 lambda self, e: {"User": {"Username": "12345"}},26 )27 create_res = client.post("/v1/users/", data=user_payload, **request_user)28 assert create_res.status_code == 20129 assert create_res.data["added_by"]["id"] == request_user_object.id30 user_id = create_res.data["id"]31 assert User.objects.get(id=user_id).verified_at is not None32 return user_id33def _test_read_user_operation(34 client,35 request_user,36 user_to_create,37 user_id,38 active_user_id,39 churning_user_id,40 innactive_user_id,41):42 # Read43 get_res = client.get(f"/v1/users/{user_id}/", **request_user)44 assert get_res.status_code == 20045 assert get_res.data["email"] == "newuser@example.com"46 assert get_res.data["activity_status"] == ActivityStatus.NEW47 # List48 with freezegun.freeze_time("2019-10-13T22:23:24Z"):49 list_res = client.get("/v1/users/", **request_user)50 assert list_res.status_code == 20051 full_get_list = list_res.data["results"]52 assert len(full_get_list) >= 253 assert user_id in [u["id"] for u in full_get_list]54 # activity_status active for users who logged in < 7 days ago55 for u in full_get_list:56 if u["id"] == active_user_id:57 assert u["activity_status"] == ActivityStatus.ACTIVE58 # is_active_user false for users who logged in > 7 days ago59 for u in full_get_list:60 if u["id"] == churning_user_id:61 assert u["activity_status"] == ActivityStatus.CHURNING62 # is_active_user false for users who logged in < 14 days ago63 for u in full_get_list:64 if u["id"] == innactive_user_id:65 assert u["activity_status"] == ActivityStatus.INACTIVE66def _test_update_user_operation(client, request_user, user_id, user_email):67 # Update via PATCH68 patch_res = client.patch(69 f"/v1/users/{user_id}/",70 data={"first_name": "Maggie"},71 content_type="application/json",72 **request_user,73 )74 assert patch_res.status_code == 20075 assert patch_res.data["id"] == user_id76 assert patch_res.data["first_name"] == "Maggie"77 # Update via POST78 post_update_res = client.post(79 f"/v1/users/",80 data={"email": user_email, "first_name": "Marge"},81 content_type="application/json",82 **request_user,83 )84 assert post_update_res.status_code == 20185 assert post_update_res.data["id"] == user_id86 assert post_update_res.data["email"] == User.objects.normalize_email(user_email)87 assert post_update_res.data["first_name"] == "Marge"88def _test_delete_user_operation(client, user):89 # Delete90 assert user.is_active91 del_res = client.delete(f"/v1/users/{user.id}/", **utils.id_auth(user))92 assert del_res.status_code == 20493 user.refresh_from_db()94 assert not user.is_active95 get_res = client.get(f"/v1/users/{user.id}/", **utils.id_auth(user))96 assert get_res.status_code == 40197def _test_crud_user_operation(98 client,99 user_object,100 request_user,101 user_to_create,102 active_user_id,103 churning_user_id,104 innactive_user_id,105 monkeypatch,106):107 email = "NewUser@Example.com"108 created_user_id = _test_create_user_operation(109 client, user_object, request_user, user_to_create, email, monkeypatch110 )111 _test_read_user_operation(112 client,113 request_user,114 user_to_create,115 created_user_id,116 active_user_id,117 churning_user_id,118 innactive_user_id,119 )120 _test_update_user_operation(client, request_user, created_user_id, email)121 _test_delete_user_operation(client, user_object)122@pytest.mark.django_db123def test_adding_demo_user(client, supportal_admin_user, monkeypatch):124 email = "newemail+test@example.com"125 user_payload = {126 "email": email,127 "first_name": "Susan",128 "last_name": "",129 "address": "123 Fake St, Somerville MA 941045",130 "is_mobilize_america_signup": True,131 }132 # Create133 # Until we have a better way of mocking Cognito in tests, mokeypatch134 # the create_cognito_user method on the user manager135 monkeypatch.setattr(136 UserManager,137 "create_cognito_user",138 lambda self, e: {"User": {"Username": "12345"}},139 )140 create_res = client.post(141 "/v1/users/",142 data=user_payload,143 **utils.id_auth(supportal_admin_user),144 content_type="application/json",145 )146 assert create_res.status_code == 201147 user = User.objects.get_user_by_email(email)148 assert user.verified_at is None149@pytest.mark.django_db150def test_bulk_adding_user(client, supportal_admin_user, monkeypatch):151 email = "newemail+test@example.com"152 assert (153 User.objects.filter(email__in=[supportal_admin_user.email, email]).count() == 1154 )155 user_payload = [156 {157 "email": "bad",158 "first_name": "Susan",159 "last_name": "",160 "address": "123 Fake St, Somerville MA 941045",161 "is_mobilize_america_signup": True,162 },163 {164 "email": email,165 "first_name": "Susan",166 "last_name": "",167 "address": "123 Fake St, Somerville MA 941045",168 "is_mobilize_america_signup": True,169 },170 {171 "email": supportal_admin_user.email,172 "first_name": "Susan",173 "last_name": "",174 "address": "123 Fake St, Somerville MA 941045",175 "is_mobilize_america_signup": False,176 },177 ]178 # Create179 # Until we have a better way of mocking Cognito in tests, mokeypatch180 # the create_cognito_user method on the user manager181 monkeypatch.setattr(182 UserManager,183 "create_cognito_user",184 lambda self, e: {"User": {"Username": "12345"}},185 )186 create_res = client.post(187 "/v1/users/",188 data=user_payload,189 **utils.id_auth(supportal_admin_user),190 content_type="application/json",191 )192 assert create_res.data[0]["error"] and create_res.data[0]["email"] == "bad"193 assert (User.objects.filter(email="bad").count()) == 0194 assert create_res.status_code == 201195 user = User.objects.get_user_by_email(email)196 assert user.verified_at is None197 assert (198 User.objects.filter(email__in=[supportal_admin_user.email, email]).count() == 2199 )200@pytest.mark.django_db201def test_adding_demo_user_already_exists(202 client, supportal_admin_user, cambridge_leader_user, monkeypatch203):204 assert cambridge_leader_user.verified_at is not None205 user_payload = {206 "email": cambridge_leader_user.email,207 "first_name": "Susan",208 "last_name": "",209 "address": "123 Fake St, Somerville MA 941045",210 "is_mobilize_america_signup": True,211 }212 # Create213 # Until we have a better way of mocking Cognito in tests, mokeypatch214 # the create_cognito_user method on the user manager215 monkeypatch.setattr(216 UserManager,217 "create_cognito_user",218 lambda self, e: {"User": {"Username": "12345"}},219 )220 create_res = client.post(221 "/v1/users/",222 data=user_payload,223 **utils.id_auth(supportal_admin_user),224 content_type="application/json",225 )226 assert create_res.status_code == 201227 cambridge_leader_user.refresh_from_db228 assert cambridge_leader_user.verified_at is not None229@pytest.mark.django_db230def test_adding_non_demo_user(client, supportal_admin_user, monkeypatch):231 email = "newemail+test2@example.com"232 user_payload = {233 "email": email,234 "first_name": "Susan",235 "last_name": "",236 "address": "123 Fake St, Somerville MA 941045",237 "is_mobilize_america_signup": False,238 }239 # Create240 # Until we have a better way of mocking Cognito in tests, mokeypatch241 # the create_cognito_user method on the user manager242 monkeypatch.setattr(243 UserManager,244 "create_cognito_user",245 lambda self, e: {"User": {"Username": "12345"}},246 )247 create_res = client.post(248 "/v1/users/",249 data=user_payload,250 **utils.id_auth(supportal_admin_user),251 content_type="application/json",252 )253 assert create_res.status_code == 201254 user = User.objects.get_user_by_email(email)255 assert user.verified_at is not None256@pytest.mark.django_db257def test_admin_list_pagination(258 client, supportal_admin_user, cambridge_leader_user, mattapan_leader_user259):260 cambridge_leader_user.created_at = timezone.now()261 cambridge_leader_user.save()262 mattapan_leader_user.created_at = timezone.now() - datetime.timedelta(days=1)263 mattapan_leader_user.save()264 supportal_admin_user.created_at = timezone.now() - datetime.timedelta(days=2)265 supportal_admin_user.save()266 # List First Page267 list_res = client.get(268 "/v1/users/?page=1&page_size=1", **utils.id_auth(supportal_admin_user)269 )270 assert list_res.status_code == 200271 full_get_list = list_res.data["results"]272 assert len(full_get_list) == 1273 assert cambridge_leader_user.id == full_get_list[0]["id"]274 # List Second Page275 second_list_res = client.get(276 list_res.data["next"], **utils.id_auth(supportal_admin_user)277 )278 assert second_list_res.status_code == 200279 full_get_list = second_list_res.data["results"]280 assert len(full_get_list) == 1281 assert mattapan_leader_user.id == full_get_list[0]["id"]282@pytest.mark.django_db283def test_admin_list_user_ordering(284 client,285 supportal_admin_user,286 cambridge_leader_user,287 mattapan_leader_user,288 hayes_valley_leader_user,289):290 # List291 with freezegun.freeze_time("2019-10-13T22:23:24Z"):292 # List first page and state filter293 list_res = client.get(294 "/v1/users/?ordering=-state,email", **utils.id_auth(supportal_admin_user)295 )296 assert list_res.status_code == 200297 full_get_list = list_res.data["results"]298 assert len(full_get_list) == 4299 result_ids = [300 mattapan_leader_user.id,301 cambridge_leader_user.id,302 hayes_valley_leader_user.id,303 supportal_admin_user.id,304 ]305 for i, user in enumerate(full_get_list):306 assert result_ids[i] == user["id"]307@pytest.mark.django_db308def test_admin_list_user_doesnt_include_inactive(309 client,310 supportal_admin_user,311 cambridge_leader_user,312 mattapan_leader_user,313 hayes_valley_leader_user,314):315 client.delete(316 f"/v1/users/{cambridge_leader_user.id}/", **utils.id_auth(supportal_admin_user)317 )318 # List first page and state filter319 list_res = client.get(320 "/v1/users/?ordering=-state,email", **utils.id_auth(supportal_admin_user)321 )322 assert list_res.status_code == 200323 full_get_list = list_res.data["results"]324 assert len(full_get_list) == 3325 assert cambridge_leader_user.id not in [u["id"] for u in full_get_list]326@pytest.mark.django_db327def test_admin_user_meta(328 client,329 supportal_admin_user,330 cambridge_leader_user,331 mattapan_leader_user,332 hayes_valley_leader_user,333):334 hayes_valley_leader_user.is_active = False335 hayes_valley_leader_user.save()336 # List first page and state filter337 meta_res = client.get("/v1/users/meta/", **utils.id_auth(supportal_admin_user))338 assert meta_res.status_code == 200339 assert meta_res.data["all"]["count"] == 3340 assert len(meta_res.data["states"]) == 2341 assert meta_res.data["states"][0]["state"] == ""342 assert meta_res.data["states"][0]["count"] == 1343 assert meta_res.data["states"][1]["state"] == "MA"344 assert meta_res.data["states"][1]["count"] == 2345@pytest.mark.django_db346def test_admin_list_user_filter_and_pagination(347 client,348 auth_supportal_admin_user,349 cambridge_leader_user,350 mattapan_leader_user,351 hayes_valley_leader_user,352):353 cambridge_leader_user.created_at = timezone.now()354 cambridge_leader_user.save()355 mattapan_leader_user.created_at = timezone.now() - datetime.timedelta(days=1)356 mattapan_leader_user.save()357 # List358 with freezegun.freeze_time("2019-10-13T22:23:24Z"):359 # List first page and state filter360 list_res = client.get(361 "/v1/users/?state=MA&page=1&page_size=1", **auth_supportal_admin_user362 )363 assert list_res.status_code == 200364 full_get_list = list_res.data["results"]365 assert len(full_get_list) == 1366 assert cambridge_leader_user.id in [u["id"] for u in full_get_list]367 # List second page with state filter368 filtered_list_res = client.get(369 list_res.data["next"], **auth_supportal_admin_user370 )371 assert filtered_list_res.status_code == 200372 full_get_list = filtered_list_res.data["results"]373 assert len(full_get_list) == 1 # auth_supportal_admin_user has no state374 assert mattapan_leader_user.id in [u["id"] for u in full_get_list]375 # There is no third page376 assert filtered_list_res.data["next"] is None377@pytest.mark.django_db378def test_admin_list_user_filter(379 client,380 auth_supportal_admin_user,381 cambridge_leader_user,382 mattapan_leader_user,383 hayes_valley_leader_user,384):385 # List386 with freezegun.freeze_time("2019-10-13T22:23:24Z"):387 # List Full Page388 list_res = client.get("/v1/users/", **auth_supportal_admin_user)389 assert list_res.status_code == 200390 full_get_list = list_res.data["results"]391 assert len(full_get_list) == 4392 assert hayes_valley_leader_user.id in [u["id"] for u in full_get_list]393 # List with state Filter394 filtered_list_res = client.get(395 "/v1/users/?state=MA", **auth_supportal_admin_user396 )397 assert filtered_list_res.status_code == 200398 full_get_list = filtered_list_res.data["results"]399 assert len(full_get_list) == 2 # auth_supportal_admin_user has no state400 assert hayes_valley_leader_user.id not in [u["id"] for u in full_get_list]401 assert cambridge_leader_user.id in [u["id"] for u in full_get_list]402@pytest.mark.django_db403def test_admin_crud_operations_on_users(404 client,405 supportal_admin_user,406 auth_supportal_admin_user,407 cambridge_leader,408 mattapan_leader_user,409 roslindale_leader_user,410 hayes_valley_leader_user,411 monkeypatch,412):413 """/v1/users: supportal admins can perform all CRUD operations """414 _test_crud_user_operation(415 client,416 supportal_admin_user,417 auth_supportal_admin_user,418 cambridge_leader,419 mattapan_leader_user.id,420 roslindale_leader_user.id,421 hayes_valley_leader_user.id,422 monkeypatch,423 )424@pytest.mark.django_db425def test_normal_user_cannot_access_user_api(api_client, user, auth):426 """/v1/users: normal users can't access the /v1/users api at all"""427 other_user_payload = {428 "email": "newuser2@example.com",429 "first_name": "Dont",430 "last_name": "CreateMe",431 }432 create_res = api_client.post("/v1/users/", data=other_user_payload, **auth)433 assert create_res.status_code == 403434 read_res = api_client.get(f"/v1/users/{user.id}/", **auth)435 assert read_res.status_code == 403436 list_res = api_client.get(f"/v1/users/", **auth)437 assert list_res.status_code == 403438 patch_res = api_client.patch(439 f"/v1/users/{user.id}/",440 data={"first_name": "Maggie"},441 content_type="application/json",442 **auth,443 )444 assert patch_res.status_code == 403445 del_res = api_client.delete(f"/v1/users/{user.id}/", **auth)446 assert del_res.status_code == 403447@pytest.mark.django_db448def test_normal_user_me_endpoint(client, user, auth):449 """/me: users can access their own information"""450 get_res = client.get("/v1/me", **auth)451 assert get_res.status_code == 200452 assert get_res.data["id"] == user.id453 assert get_res.data["email"] == user.email454 assert get_res.data["is_admin"] == user.is_admin455@pytest.mark.django_db456def test_impersonated_me_api_call(client, user, roslindale_leader_user):457 """/me: users can access their own information"""458 user.is_admin = True459 user.impersonated_user = roslindale_leader_user460 user.save()461 res = client.get("/v1/me", **utils.id_auth(user))462 assert res.status_code == 200463 assert res.data["email"] != user.email464 assert res.data["email"] == roslindale_leader_user.email465@pytest.mark.django_db466def test_normal_user_can_update_self(client, user, auth):467 """/me: users can update their own info"""468 new_address = "NewAddr"469 assert user.address != new_address470 client.patch(471 f"/v1/me",472 data={"address": new_address},473 content_type="application/json",474 **auth,475 )476 user.refresh_from_db()477 assert user.address == new_address478@pytest.mark.django_db479def test_normal_user_cannot_update_email(client, user, auth):480 """/me: users can update cannot update their email address"""481 new_email = "otheremail@example.com"482 old_email = user.email483 client.patch(484 f"/v1/me", data={"email": new_email}, content_type="application/json", **auth485 )486 user.refresh_from_db()487 assert user.email == old_email488@pytest.mark.django_db489def test_normal_user_cannot_update_is_admin(client, user, auth):490 """/me: users can update cannot update their admin status"""491 client.patch(492 f"/v1/me", data={"is_admin": True}, content_type="application/json", **auth493 )494 user.refresh_from_db()495 assert user.is_admin is False496@pytest.mark.django_db497def test_superuser_cannot_update_email_through_rest_api(client, user, auth_superuser):498 new_email = "otheremail@example.com"499 old_email = user.email500 res = client.patch(501 f"/v1/users/{user.id}/",502 data={"email": new_email},503 content_type="application/json",504 **auth_superuser,505 )506 assert res.status_code == 400507 user.refresh_from_db()508 assert user.email == old_email509@pytest.mark.django_db510def test_update_phone_number_formats(client, user, auth):511 client.patch(512 f"/v1/me",513 data={"phone": ""},514 content_type="application/json",515 **auth,516 )517 user.refresh_from_db()518 assert user.phone == "+"519@pytest.mark.django_db520@responses.activate # Just to make sure there are no live HTTP requests521def test_geocode_address(mocker, client, user, auth):522 mock_location = {"lat": 42.3865482, "lng": -71.0817715}523 mocker.patch(524 "supportal.app.serializers.user_serializers.geocode", return_value=mock_location525 )526 res = client.patch(527 f"/v1/me",528 data={529 "address": "10 Fake St.",530 "city": "Somerville",531 "state": "MA",532 "zip5": "02145",533 },534 content_type="application/json",535 **auth,536 )537 user.refresh_from_db()538 assert pytest.approx(user.coordinates.x, mock_location["lng"])539 assert pytest.approx(user.coordinates.y, mock_location["lat"])540@pytest.mark.django_db541@responses.activate542def test_geocode_address_failure(mocker, client, user, auth):543 mocker.patch(544 "supportal.app.serializers.user_serializers.geocode", return_value=None545 )546 res = client.patch(547 f"/v1/me",548 data={"address": "oogle boogle", "zip5": "02145"},549 content_type="application/json",550 **auth,551 )...
conftest.py
Source:conftest.py
...40 ReadAttributes=["cognito:username", "nickname"],41 )["UserPoolClient"]["ClientId"]42@pytest.fixture(scope="session")43def user_auth(cognito_idp_client: BaseClient, user_pool_id: str, app_client_id: str) -> UserAuth:44 nickname, username, password = create_cognito_user(cognito_idp_client, app_client_id)45 cognito_idp_client.admin_confirm_sign_up(UserPoolId=user_pool_id, Username=username)46 auth_results = cognito_idp_client.initiate_auth(47 ClientId=app_client_id,48 AuthFlow="USER_PASSWORD_AUTH",49 AuthParameters={"USERNAME": username, "PASSWORD": password},50 )["AuthenticationResult"]51 return UserAuth(**auth_results)52@pytest.fixture(scope="session")53def admin_group_name():54 return "admins"55@pytest.fixture(scope="session")56def admin_user_auth(57 cognito_idp_client: BaseClient, user_pool_id: str, app_client_id: str, admin_group_name: str58) -> UserAuth:59 nickname, username, password = create_cognito_user(cognito_idp_client, app_client_id)60 cognito_idp_client.admin_confirm_sign_up(UserPoolId=user_pool_id, Username=username)61 cognito_idp_client.create_group(GroupName=admin_group_name, UserPoolId=user_pool_id)62 cognito_idp_client.admin_add_user_to_group(63 UserPoolId=user_pool_id, Username=username, GroupName=admin_group_name64 )65 auth_results = cognito_idp_client.initiate_auth(66 ClientId=app_client_id,67 AuthFlow="USER_PASSWORD_AUTH",68 AuthParameters={"USERNAME": username, "PASSWORD": password},69 )["AuthenticationResult"]70 return UserAuth(**auth_results)71@pytest.fixture72def initialized_app(73 monkeypatch, cognito_idp_client: BaseClient, user_pool_id: str, app_client_id: str...
create_test_data.py
Source:create_test_data.py
1import import_authors2import import_users3import import_customers4import import_publications5import create_cognito_user67create_cognito_user.run()8import_customers.run()9import_users.run()10import_authors.run()
...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!