Best Python code snippet using localstack_python
test_api.py
Source:test_api.py  
...93        enterprise_learner_patcher.return_value = {}94        self.addCleanup(enterprise_learner_patcher.stop)95    def test_get_username_provided(self):96        """Test the difference in behavior when a username is supplied to get_account_settings."""97        account_settings = get_account_settings(self.default_request)[0]98        assert self.user.username == account_settings['username']99        account_settings = get_account_settings(self.default_request, usernames=[self.user.username])[0]100        assert self.user.username == account_settings['username']101        account_settings = get_account_settings(self.default_request, usernames=[self.different_user.username])[0]102        assert self.different_user.username == account_settings['username']103    def test_get_configuration_provided(self):104        """Test the difference in behavior when a configuration is supplied to get_account_settings."""105        config = {106            "default_visibility": "private",107            "public_fields": [108                'email', 'name',109            ],110        }111        # With default configuration settings, email is not shared with other (non-staff) users.112        account_settings = get_account_settings(self.default_request, [self.different_user.username])[0]113        assert 'email' not in account_settings114        account_settings = get_account_settings(115            self.default_request,116            [self.different_user.username],117            configuration=config,118        )[0]119        assert self.different_user.email == account_settings['email']120    def test_get_user_not_found(self):121        """Test that UserNotFound is thrown if there is no user with username."""122        with pytest.raises(UserNotFound):123            get_account_settings(self.default_request, usernames=["does_not_exist"])124        self.user.username = "does_not_exist"125        request = self.request_factory.get("/api/user/v1/accounts/")126        request.user = self.user127        with pytest.raises(UserNotFound):128            get_account_settings(request)129    def test_update_username_provided(self):130        """Test the difference in behavior when a username is supplied to update_account_settings."""131        update_account_settings(self.user, {"name": "Mickey Mouse"})132        account_settings = get_account_settings(self.default_request)[0]133        assert 'Mickey Mouse' == account_settings['name']134        update_account_settings(self.user, {"name": "Donald Duck"}, username=self.user.username)135        account_settings = get_account_settings(self.default_request)[0]136        assert 'Donald Duck' == account_settings['name']137        with pytest.raises(UserNotAuthorized):138            update_account_settings(self.different_user, {"name": "Pluto"}, username=self.user.username)139    def test_update_non_existent_user(self):140        with pytest.raises(UserNotAuthorized):141            update_account_settings(self.user, {}, username="does_not_exist")142        self.user.username = "does_not_exist"143        with pytest.raises(UserNotFound):144            update_account_settings(self.user, {})145    def test_get_empty_social_links(self):146        account_settings = get_account_settings(self.default_request)[0]147        assert account_settings['social_links'] == []148    def test_set_single_social_link(self):149        social_links = [150            dict(platform="facebook", social_link=f"https://www.facebook.com/{self.user.username}")151        ]152        update_account_settings(self.user, {"social_links": social_links})153        account_settings = get_account_settings(self.default_request)[0]154        assert account_settings['social_links'] == social_links155    def test_set_multiple_social_links(self):156        social_links = [157            dict(platform="facebook", social_link=f"https://www.facebook.com/{self.user.username}"),158            dict(platform="twitter", social_link=f"https://www.twitter.com/{self.user.username}"),159        ]160        update_account_settings(self.user, {"social_links": social_links})161        account_settings = get_account_settings(self.default_request)[0]162        assert account_settings['social_links'] == social_links163    def test_add_social_links(self):164        original_social_links = [165            dict(platform="facebook", social_link=f"https://www.facebook.com/{self.user.username}")166        ]167        update_account_settings(self.user, {"social_links": original_social_links})168        extra_social_links = [169            dict(platform="twitter", social_link=f"https://www.twitter.com/{self.user.username}"),170            dict(platform="linkedin", social_link=f"https://www.linkedin.com/in/{self.user.username}"),171        ]172        update_account_settings(self.user, {"social_links": extra_social_links})173        account_settings = get_account_settings(self.default_request)[0]174        assert account_settings['social_links'] == \175            sorted((original_social_links + extra_social_links), key=(lambda s: s['platform']))176    def test_replace_social_links(self):177        original_facebook_link = dict(platform="facebook", social_link="https://www.facebook.com/myself")178        original_twitter_link = dict(platform="twitter", social_link="https://www.twitter.com/myself")179        update_account_settings(self.user, {"social_links": [original_facebook_link, original_twitter_link]})180        modified_facebook_link = dict(platform="facebook", social_link="https://www.facebook.com/new_me")181        update_account_settings(self.user, {"social_links": [modified_facebook_link]})182        account_settings = get_account_settings(self.default_request)[0]183        assert account_settings['social_links'] == [modified_facebook_link, original_twitter_link]184    def test_remove_social_link(self):185        original_facebook_link = dict(platform="facebook", social_link="https://www.facebook.com/myself")186        original_twitter_link = dict(platform="twitter", social_link="https://www.twitter.com/myself")187        update_account_settings(self.user, {"social_links": [original_facebook_link, original_twitter_link]})188        removed_facebook_link = dict(platform="facebook", social_link="")189        update_account_settings(self.user, {"social_links": [removed_facebook_link]})190        account_settings = get_account_settings(self.default_request)[0]191        assert account_settings['social_links'] == [original_twitter_link]192    def test_unsupported_social_link_platform(self):193        social_links = [194            dict(platform="unsupported", social_link=f"https://www.unsupported.com/{self.user.username}")195        ]196        with pytest.raises(AccountValidationError):197            update_account_settings(self.user, {"social_links": social_links})198    def test_update_success_for_enterprise(self):199        EnterpriseCustomerUserFactory(user_id=self.user.id)200        level_of_education = "m"201        successful_update = {202            "level_of_education": level_of_education,203        }204        update_account_settings(self.user, successful_update)205        account_settings = get_account_settings(self.default_request)[0]206        assert level_of_education == account_settings['level_of_education']207    @patch('openedx.features.enterprise_support.api.enterprise_customer_for_request')208    @patch('openedx.features.enterprise_support.utils.third_party_auth.provider.Registry.get')209    @ddt.data(210        *itertools.product(211            # field_name_value values212            (("email", "new_email@example.com"), ("name", "new name"), ("country", "IN")),213            # is_enterprise_user214            (True, False),215            # is_synch_learner_profile_data216            (True, False),217            # has `UserSocialAuth` record218            (True, False),219        )220    )221    @ddt.unpack222    def test_update_validation_error_for_enterprise(223        self,224        field_name_value,225        is_enterprise_user,226        is_synch_learner_profile_data,227        has_user_social_auth_record,228        mock_auth_provider,229        mock_customer,230    ):231        idp_backend_name = 'tpa-saml'232        mock_customer.return_value = {}233        if is_enterprise_user:234            mock_customer.return_value.update({235                'uuid': 'real-ent-uuid',236                'name': 'Dummy Enterprise',237                'identity_provider': 'saml-ubc',238                'identity_providers': [239                    {240                        "provider_id": "saml-ubc",241                    }242                ],243            })244        mock_auth_provider.return_value.sync_learner_profile_data = is_synch_learner_profile_data245        mock_auth_provider.return_value.backend_name = idp_backend_name246        update_data = {field_name_value[0]: field_name_value[1]}247        user_fullname_editable = False248        if has_user_social_auth_record:249            UserSocialAuth.objects.create(250                provider=idp_backend_name,251                user=self.user252            )253        else:254            UserSocialAuth.objects.all().delete()255            # user's fullname is editable if no `UserSocialAuth` record exists256            user_fullname_editable = field_name_value[0] == 'name'257        # prevent actual email change requests258        with patch('openedx.core.djangoapps.user_api.accounts.api.student_views.do_email_change_request'):259            # expect field un-editability only when all of the following conditions are met260            if is_enterprise_user and is_synch_learner_profile_data and not user_fullname_editable:261                with pytest.raises(AccountValidationError) as validation_error:262                    update_account_settings(self.user, update_data)263                    field_errors = validation_error.value.field_errors264                    assert 'This field is not editable via this API' ==\265                           field_errors[field_name_value[0]]['developer_message']266            else:267                update_account_settings(self.user, update_data)268                account_settings = get_account_settings(self.default_request)[0]269                if field_name_value[0] != "email":270                    assert field_name_value[1] == account_settings[field_name_value[0]]271    def test_update_error_validating(self):272        """Test that AccountValidationError is thrown if incorrect values are supplied."""273        with pytest.raises(AccountValidationError):274            update_account_settings(self.user, {"username": "not_allowed"})275        with pytest.raises(AccountValidationError):276            update_account_settings(self.user, {"gender": "undecided"})277        with pytest.raises(AccountValidationError):278            update_account_settings(279                self.user,280                {"profile_image": {"has_image": "not_allowed", "image_url": "not_allowed"}}281            )282        # Check the various language_proficiencies validation failures.283        # language_proficiencies must be a list of dicts, each containing a284        # unique 'code' key representing the language code.285        with pytest.raises(AccountValidationError):286            update_account_settings(287                self.user,288                {"language_proficiencies": "not_a_list"}289            )290        with pytest.raises(AccountValidationError):291            update_account_settings(292                self.user,293                {"language_proficiencies": [{}]}294            )295        with pytest.raises(AccountValidationError):296            update_account_settings(self.user, {"account_privacy": ""})297    def test_update_multiple_validation_errors(self):298        """Test that all validation errors are built up and returned at once"""299        # Send a read-only error, serializer error, and email validation error.300        naughty_update = {301            "username": "not_allowed",302            "gender": "undecided",303            "email": "not an email address",304            "name": "<p style=\"font-size:300px; color:green;\"></br>Name<input type=\"text\"></br>Content spoof"305        }306        with pytest.raises(AccountValidationError) as context_manager:307            update_account_settings(self.user, naughty_update)308        field_errors = context_manager.value.field_errors309        assert 4 == len(field_errors)310        assert 'This field is not editable via this API' == field_errors['username']['developer_message']311        assert "Value 'undecided' is not valid for field 'gender'" in field_errors['gender']['developer_message']312        assert 'Valid e-mail address required.' in field_errors['email']['developer_message']313        assert 'Full Name cannot contain the following characters: < >' in field_errors['name']['user_message']314    def test_validate_name_change_same_name(self):315        """316        Test that saving the user's profile name without changing it should not raise an error.317        """318        account_settings = get_account_settings(self.default_request)[0]319        # Add name change history to the profile metadeta; if the user has at least one certificate,320        # too many name changes will trigger the verification requirement, but this should only happen321        # if the name has actually been changed322        user_profile = UserProfile.objects.get(user=self.user)323        meta = user_profile.get_meta()324        meta['old_names'] = []325        for num in range(3):326            meta['old_names'].append(327                [f'old_name_{num}', 'test', datetime.datetime.now(UTC).isoformat()]328            )329        user_profile.set_meta(meta)330        user_profile.save()331        with patch(332            'openedx.core.djangoapps.user_api.accounts.api.get_certificates_for_user',333            return_value=[{'status': CertificateStatuses.downloadable}]334        ):335            update_account_settings(self.user, {'name': account_settings['name']})336            # The name should not be added to profile metadata337            updated_meta = user_profile.get_meta()338            self.assertEqual(meta, updated_meta)339    @patch('edx_name_affirmation.name_change_validator.NameChangeValidator.validate', Mock(return_value=False))340    @patch('openedx.core.djangoapps.user_api.accounts.api.get_certificates_for_user',341           Mock(return_value=[{'status': CertificateStatuses.downloadable}]))342    @patch('openedx.core.djangoapps.user_api.accounts.api.get_verified_enrollments',343           Mock(return_value=[{'name': 'Bob'}]))344    def test_name_update_requires_idv(self):345        """346        Test that a name change is blocked through this API if it requires ID verification.347        """348        with pytest.raises(AccountValidationError) as context_manager:349            update_account_settings(self.user, {'name': 'New Name'})350        field_errors = context_manager.value.field_errors351        assert len(field_errors) == 1352        assert field_errors['name']['developer_message'] == 'This name change requires ID verification.'353        account_settings = get_account_settings(self.default_request)[0]354        assert account_settings['name'] != 'New Name'355    @patch('edx_name_affirmation.name_change_validator.NameChangeValidator', Mock())356    @patch('edx_name_affirmation.name_change_validator.NameChangeValidator.validate', Mock(return_value=True))357    @ddt.data(358        (True, False),359        (False, True),360        (False, False)361    )362    @ddt.unpack363    def test_name_update_does_not_require_idv(self, has_passable_cert, enrolled_in_verified_mode):364        """365        Test that the user can change their name if change does not require IDV.366        """367        with patch('openedx.core.djangoapps.user_api.accounts.api.get_certificates_for_user') as mock_get_certs,\368             patch('openedx.core.djangoapps.user_api.accounts.api.get_verified_enrollments') as \369                mock_get_verified_enrollments:370            mock_get_certs.return_value = (371                [{'status': CertificateStatuses.downloadable}] if372                has_passable_cert else373                [{'status': CertificateStatuses.unverified}]374            )375            mock_get_verified_enrollments.return_value = [{'name': 'Bob'}] if enrolled_in_verified_mode else []376            update_account_settings(self.user, {'name': 'New Name'})377        account_settings = get_account_settings(self.default_request)[0]378        assert account_settings['name'] == 'New Name'379    @patch('django.core.mail.EmailMultiAlternatives.send')380    @patch('common.djangoapps.student.views.management.render_to_string', Mock(side_effect=mock_render_to_string, autospec=True))  # lint-amnesty, pylint: disable=line-too-long381    def test_update_sending_email_fails(self, send_mail):382        """Test what happens if all validation checks pass, but sending the email for email change fails."""383        send_mail.side_effect = [Exception, None]384        less_naughty_update = {385            "name": "Mickey Mouse",386            "email": "seems_ok@sample.com"387        }388        with patch('crum.get_current_request', return_value=self.fake_request):389            with pytest.raises(AccountUpdateError) as context_manager:390                update_account_settings(self.user, less_naughty_update)391        assert 'Error thrown from do_email_change_request' in context_manager.value.developer_message392        # Verify that the name change happened, even though the attempt to send the email failed.393        account_settings = get_account_settings(self.default_request)[0]394        assert 'Mickey Mouse' == account_settings['name']395    @patch.dict(settings.FEATURES, dict(ALLOW_EMAIL_ADDRESS_CHANGE=False))396    def test_email_changes_disabled(self):397        """398        Test that email address changes are rejected when ALLOW_EMAIL_ADDRESS_CHANGE is not set.399        """400        disabled_update = {"email": "valid@example.com"}401        with pytest.raises(AccountUpdateError) as context_manager:402            update_account_settings(self.user, disabled_update)403        assert 'Email address changes have been disabled' in context_manager.value.developer_message404    @patch.dict(settings.FEATURES, dict(ALLOW_EMAIL_ADDRESS_CHANGE=True))405    def test_email_changes_blocked_on_retired_email(self):406        """407        Test that email address changes are rejected when an email associated with a *partially* retired account is408        specified.409        """410        # First, record the original email addres of the primary user (the one seeking to update their email).411        original_email = self.user.email412        # Setup a partially retired user.  This user recently submitted a deletion request, but it has not been413        # processed yet.414        partially_retired_email = 'partially_retired@example.com'415        partially_retired_user = UserFactory(email=partially_retired_email)416        fake_requested_retirement(partially_retired_user)417        # Attempt to change email to the one of the partially retired user.418        rejected_update = {'email': partially_retired_email}419        update_account_settings(self.user, rejected_update)420        # No error should be thrown, and we need to check that the email update was skipped.421        assert self.user.email == original_email422    @patch('openedx.core.djangoapps.user_api.accounts.serializers.AccountUserSerializer.save')423    def test_serializer_save_fails(self, serializer_save):424        """425        Test the behavior of one of the serializers failing to save. Note that email request change426        won't be processed in this case.427        """428        serializer_save.side_effect = [Exception, None]429        update_will_fail = {430            "name": "Mickey Mouse",431            "email": "ok@sample.com"432        }433        with pytest.raises(AccountUpdateError) as context_manager:434            update_account_settings(self.user, update_will_fail)435        assert 'Error thrown when saving account updates' in context_manager.value.developer_message436        # Verify that no email change request was initiated.437        pending_change = PendingEmailChange.objects.filter(user=self.user)438        assert 0 == len(pending_change)439    def test_language_proficiency_eventing(self):440        """441        Test that eventing of language proficiencies, which happens update_account_settings method, behaves correctly.442        """443        def verify_event_emitted(new_value, old_value):444            """445            Confirm that the user setting event was properly emitted446            """447            update_account_settings(self.user, {"language_proficiencies": new_value})448            self.assert_user_setting_event_emitted(setting='language_proficiencies', old=old_value, new=new_value)449            self.reset_tracker()450        # Change language_proficiencies and verify events are fired.451        verify_event_emitted([{"code": "en"}], [])452        verify_event_emitted([{"code": "en"}, {"code": "fr"}], [{"code": "en"}])453        # Note that events are fired even if there has been no actual change.454        verify_event_emitted([{"code": "en"}, {"code": "fr"}], [{"code": "en"}, {"code": "fr"}])455        verify_event_emitted([], [{"code": "en"}, {"code": "fr"}])456    def test_add_account_recovery(self):457        test_email = "test@example.com"458        pending_secondary_email_changes = PendingSecondaryEmailChange.objects.filter(user=self.user)459        assert 0 == len(pending_secondary_email_changes)460        account_recovery_objects = AccountRecovery.objects.filter(user=self.user)461        assert 0 == len(account_recovery_objects)462        with patch('crum.get_current_request', return_value=self.fake_request):463            update = {"secondary_email": test_email}464            update_account_settings(self.user, update)465        pending_secondary_email_change = PendingSecondaryEmailChange.objects.get(user=self.user)466        assert pending_secondary_email_change is not None467        assert pending_secondary_email_change.new_secondary_email == test_email468        activate_secondary_email(self.fake_request, pending_secondary_email_change.activation_key)469        pending_secondary_email_changes = PendingSecondaryEmailChange.objects.filter(user=self.user)470        assert 0 == len(pending_secondary_email_changes)471        account_recovery = AccountRecovery.objects.get(user=self.user)472        assert account_recovery is not None473        assert account_recovery.secondary_email == test_email474    def test_change_country_removes_state(self):475        '''476        Test that changing the country (to something other than a country with477        states) removes the state478        '''479        # First set the country and state480        update_account_settings(self.user, {"country": UserProfile.COUNTRY_WITH_STATES, "state": "MA"})481        account_settings = get_account_settings(self.default_request)[0]482        assert account_settings['country'] == UserProfile.COUNTRY_WITH_STATES483        assert account_settings['state'] == 'MA'484        # Change the country and check that state is removed485        update_account_settings(self.user, {"country": ""})486        account_settings = get_account_settings(self.default_request)[0]487        assert account_settings['country'] is None488        assert account_settings['state'] is None489@patch('openedx.core.djangoapps.user_api.accounts.image_helpers._PROFILE_IMAGE_SIZES', [50, 10])490@patch.dict(491    'django.conf.settings.PROFILE_IMAGE_SIZES_MAP',492    {'full': 50, 'small': 10},493    clear=True494)495@skip_unless_lms496class AccountSettingsOnCreationTest(CreateAccountMixin, TestCase):497    # pylint: disable=missing-docstring498    USERNAME = 'frank-underwood'499    PASSWORD = 'á¹Ã¡ÅÅáºÅÅd'500    EMAIL = 'frank+underwood@example.com'501    def test_create_account(self):502        # Create a new account, which should have empty account settings by default.503        self.create_account(self.USERNAME, self.PASSWORD, self.EMAIL)504        # Retrieve the account settings505        user = User.objects.get(username=self.USERNAME)506        request = RequestFactory().get("/api/user/v1/accounts/")507        request.user = user508        account_settings = get_account_settings(request)[0]509        # Expect a date joined and last login field but remove it to simplify the following comparison510        assert account_settings['date_joined'] is not None511        assert account_settings['last_login'] is not None512        del account_settings['date_joined']513        del account_settings['last_login']514        # Expect all the values to be defaulted515        assert account_settings == {516            'username': self.USERNAME,517            'email': self.EMAIL,518            'id': user.id,519            'name': self.USERNAME,520            'verified_name': None,521            'activation_key': user.registration.activation_key,522            'gender': None, 'goals': '',...lambda_function.py
Source:lambda_function.py  
...7logger = logging.getLogger()8logger.setLevel(logging.INFO)9patch_all()10client = boto3.client('lambda')11client.get_account_settings()12def lambda_handler(event, context):13    logger.info('## ENVIRONMENT VARIABLES\r' + jsonpickle.encode(dict(**os.environ)))14    logger.info('## EVENT\r' + jsonpickle.encode(event))15    logger.info('## CONTEXT\r' + jsonpickle.encode(context))16    response = client.get_account_settings()...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!!
