Best Python code snippet using Kiwi_python
test_views.py
Source:test_views.py  
...75    def test_open_registration_page(self):76        response = self.client.get(self.register_url)77        _register = _("Register")78        self.assertContains(response, f">{_register}</button>")79    def assert_user_registration(self, username, follow=False):80        with patch("tcms.kiwi_auth.models.secrets") as _secrets:81            _secrets.token_hex.return_value = self.fake_activate_key82            try:83                # https://github.com/mbi/django-simple-captcha/issues/8484                # pylint: disable=import-outside-toplevel85                from captcha.conf import settings as captcha_settings86                captcha_settings.CAPTCHA_TEST_MODE = True87                response = self.client.post(88                    self.register_url,89                    {90                        "username": username,91                        "password1": "password",92                        "password2": "password",93                        "email": "new-tester@example.com",94                        "captcha_0": "PASSED",95                        "captcha_1": "PASSED",96                    },97                    follow=follow,98                )99            finally:100                captcha_settings.CAPTCHA_TEST_MODE = False101        user = User.objects.get(username=username)102        self.assertEqual("new-tester@example.com", user.email)103        if User.objects.filter(is_superuser=True).count() == 1 and user.is_superuser:104            self.assertTrue(user.is_active)105        else:106            self.assertFalse(user.is_active)107        key = UserActivationKey.objects.get(user=user)108        self.assertEqual(self.fake_activate_key, key.activation_key)109        return response, user110    @patch("tcms.signals.USER_REGISTERED_SIGNAL.send")111    def test_register_user_sends_signal(self, signal_mock):112        self.assert_user_registration("new-signal-tester")113        self.assertTrue(signal_mock.called)114        self.assertEqual(1, signal_mock.call_count)115    @override_settings(ADMINS=[("Test Admin", "admin@kiwitcms.org")])116    @patch("tcms.core.utils.mailto.send_mail")117    def test_signal_handler_notifies_admins(self, send_mail):118        # connect the handler b/c it is not connected by default119        signals.USER_REGISTERED_SIGNAL.connect(signals.notify_admins)120        try:121            response, user = self.assert_user_registration("signal-handler")122            self.assertRedirects(123                response, reverse("core-views-index"), target_status_code=302124            )125            # 1 - verification mail, 2 - email to admin126            self.assertTrue(send_mail.called)127            self.assertEqual(2, send_mail.call_count)128            # verify we've actually sent the admin email129            self.assertIn(130                str(_("New user awaiting approval")), send_mail.call_args_list[0][0][0]131            )132            values = {133                "username": "signal-handler",134                "user_url": f"http://testserver/admin/auth/user/{user.pk}/change/",135            }136            expected = (137                _(138                    """Dear Administrator,139somebody just registered an account with username %(username)s at your140Kiwi TCMS instance and is awaiting your approval!141Go to %(user_url)s to activate the account!"""142                )143                % values144            )145            self.assertEqual(146                expected.strip(), send_mail.call_args_list[0][0][1].strip()147            )148            self.assertIn("admin@kiwitcms.org", send_mail.call_args_list[0][0][-1])149        finally:150            signals.USER_REGISTERED_SIGNAL.disconnect(signals.notify_admins)151    @patch("tcms.core.utils.mailto.send_mail")152    def test_register_user_by_email_confirmation(self, send_mail):153        response, user = self.assert_user_registration("new-tester", follow=True)154        self.assertContains(155            response,156            _(157                "Your account has been created, please check your mailbox for confirmation"158            ),159        )160        site = Site.objects.get(pk=settings.SITE_ID)161        _confirm_url = reverse("tcms-confirm", args=[self.fake_activate_key])162        confirm_url = f"http://{site.domain}{_confirm_url}"163        # Verify notification mail164        values = {165            "user": user.username,166            "site_domain": site.domain,167            "confirm_url": confirm_url,168        }169        expected_subject = (170            settings.EMAIL_SUBJECT_PREFIX171            + _("Your new %s account confirmation") % site.domain172        )173        expected_body = (174            _(175                """Welcome %(user)s,176thank you for signing up for an %(site_domain)s account!177To activate your account, click this link:178%(confirm_url)s"""179            )180            % values181            + "\n"182        )183        send_mail.assert_called_once_with(184            expected_subject,185            expected_body,186            settings.DEFAULT_FROM_EMAIL,187            ["new-tester@example.com"],188            fail_silently=False,189        )190    @override_settings(191        AUTO_APPROVE_NEW_USERS=False,192        ADMINS=[("admin1", "admin1@example.com"), ("admin2", "admin2@example.com")],193    )194    def test_register_user_and_activate_by_admin(self):195        response, _user = self.assert_user_registration("plan-tester", follow=True)196        self.assertContains(197            response,198            _(199                "Your account has been created, but you need an administrator to activate it"200            ),201        )202        for (name, email) in settings.ADMINS:203            self.assertContains(204                response, f'<a href="mailto:{email}">{name}</a>', html=True205            )206    def test_invalid_form(self):207        response = self.client.post(208            self.register_url,209            {210                "username": "kiwi-tester",211                "password1": "password-1",212                "password2": "password-2",213                "email": "new-tester@example.com",214            },215            follow=False,216        )217        self.assertContains(response, _("The two password fields didnât match."))218        self.assertEqual(response.status_code, 200)219        self.assertTemplateUsed(response, "registration/registration_form.html")220    def test_register_user_already_registered(self):221        User.objects.create_user("kiwi-tester", "new-tester@example.com", "password")222        response = self.client.post(223            self.register_url,224            {225                "username": "test_user",226                "password1": "password",227                "password2": "password",228                "email": "new-tester@example.com",229            },230            follow=False,231        )232        self.assertContains(response, _("A user with that email already exists."))233        user = User.objects.filter(username="test_user")234        self.assertEqual(user.count(), 0)235    def test_first_user_is_superuser(self):236        _response, user = self.assert_user_registration("tester_1")237        self.assertTrue(user.is_superuser)238        self.assertTrue(user.is_active)239    def test_only_one_superuser(self):240        user1 = User.objects.create_user(241            "kiwi-tester", "tester@example.com", "password"242        )243        user1.is_superuser = True244        user1.save()245        self.assertTrue(user1.is_superuser)246        _response, user2 = self.assert_user_registration("plan-tester")247        self.assertFalse(user2.is_superuser)248class TestConfirm(TestCase):249    """Test for activation key confirmation"""250    @classmethod251    def setUpTestData(cls):252        cls.new_user = UserFactory()253    def setUp(self):254        self.new_user.is_active = False255        self.new_user.save()256    def test_fail_if_activation_key_does_not_exist(self):257        confirm_url = reverse("tcms-confirm", args=["nonexisting-activation-key"])258        response = self.client.get(confirm_url, follow=True)259        self.assertContains(260            response, _("This activation key no longer exists in the database")...tests.py
Source:tests.py  
...75            response,76            '<input value="Register" class="loginbutton sprites" type="submit">',77            html=True)78    @patch('tcms.core.contrib.auth.models.sha1')79    def assert_user_registration(self, username, sha1, follow=False):80        sha1.return_value.hexdigest.return_value = self.fake_activate_key81        response = self.client.post(self.register_url,82                                    {'username': username,83                                     'password1': 'password',84                                     'password2': 'password',85                                     'email': 'new-tester@example.com'},86                                    follow=follow)87        users = User.objects.filter(username=username)88        self.assertTrue(users.exists())89        user = users[0]90        self.assertEqual('new-tester@example.com', user.email)91        self.assertFalse(user.is_active)92        keys = UserActivateKey.objects.filter(user=user)93        self.assertTrue(keys.exists())94        self.assertEqual(self.fake_activate_key, keys[0].activation_key)95        return response96    @patch('tcms.signals.USER_REGISTERED_SIGNAL.send')97    def test_register_user_sends_signal(self, signal_mock):98        self.assert_user_registration('new-signal-tester')99        self.assertTrue(signal_mock.called)100        self.assertEqual(1, signal_mock.call_count)101    @override_settings(ADMINS=[('Test Admin', 'admin@kiwitcms.org')])102    @patch('tcms.core.utils.mailto.send_mail')103    def test_signal_handler_notifies_admins(self, send_mail):104        # connect the handler b/c it is not connected by default105        signals.USER_REGISTERED_SIGNAL.connect(signals.notify_admins)106        try:107            response = self.assert_user_registration('signal-handler')108            self.assertRedirects(response, reverse('core-views-index'), target_status_code=302)109            # 1 - verification mail, 2 - email to admin110            self.assertTrue(send_mail.called)111            self.assertEqual(2, send_mail.call_count)112            # verify we've actually sent the admin email113            self.assertIn('New user awaiting approval', send_mail.call_args_list[0][0][0])114            self.assertIn('somebody just registered an account with username signal-handler',115                          send_mail.call_args_list[0][0][1])116            self.assertIn('admin@kiwitcms.org', send_mail.call_args_list[0][0][-1])117        finally:118            signals.USER_REGISTERED_SIGNAL.disconnect(signals.notify_admins)119    @patch('tcms.core.utils.mailto.send_mail')120    def test_register_user_by_email_confirmation(self, send_mail):121        response = self.assert_user_registration('new-tester', follow=True)122        self.assertContains(123            response,124            'Your account has been created, please check your mailbox for confirmation'125        )126        s = Site.objects.get_current()127        confirm_url = 'http://%s%s' % (s.domain, reverse('tcms-confirm',128                                                         args=[self.fake_activate_key]))129        # Verify notification mail130        send_mail.assert_called_once_with(131            settings.EMAIL_SUBJECT_PREFIX + 'Your new 127.0.0.1:8000 account confirmation',132            """Welcome, new-tester, and thanks for signing up for an 127.0.0.1:8000 account!133%s134""" % confirm_url,135            settings.DEFAULT_FROM_EMAIL, ['new-tester@example.com'], fail_silently=False)136    @override_settings(AUTO_APPROVE_NEW_USERS=False,137                       ADMINS=[('admin1', 'admin1@example.com'),138                               ('admin2', 'admin2@example.com')])139    def test_register_user_and_activate_by_admin(self):140        response = self.assert_user_registration('plan-tester', follow=True)141        self.assertContains(142            response,143            'Your account has been created, but you need an administrator to activate it')144        for (name, email) in settings.ADMINS:145            self.assertContains(response,146                                '<a href="mailto:{}">{}</a>'.format(email, name),147                                html=True)148class TestConfirm(TestCase):149    """Test for activation key confirmation"""150    @classmethod151    def setUpTestData(cls):152        cls.new_user = User.objects.create(username='new-user',153                                           email='new-user@example.com',154                                           password='password')...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!!
