Best Python code snippet using Kiwi_python
test_views.py
Source:test_views.py  
...62    """Test creating new run"""63    @classmethod64    def setUpTestData(cls):65        super().setUpTestData()66        user_should_have_perm(cls.tester, 'testruns.add_testrun')67        user_should_have_perm(cls.tester, 'testruns.view_testrun')68        cls.url = reverse('testruns-new')69    def test_refuse_if_missing_plan_pk(self):70        user_should_have_perm(self.tester, 'testplans.view_testplan')71        self.client.login(  # nosec:B106:hardcoded_password_funcarg72            username=self.tester.username,73            password='password')74        response = self.client.post(self.url, {})75        self.assertRedirects(response, reverse('plans-search'))76    def test_refuse_if_missing_cases_pks(self):77        self.client.login(  # nosec:B106:hardcoded_password_funcarg78            username=self.tester.username,79            password='password')80        response = self.client.post(self.url, {'from_plan': self.plan.pk}, follow=True)81        self.assertContains(response, _('Creating a TestRun requires at least one TestCase'))82    def test_show_create_new_run_page(self):83        self.client.login(  # nosec:B106:hardcoded_password_funcarg84            username=self.tester.username,85            password='password')86        response = self.client.post(self.url, {87            'from_plan': self.plan.pk,88            'case': [self.case_1.pk, self.case_2.pk, self.case_3.pk]89        })90        # Assert listed cases91        for _i, case in enumerate((self.case_1, self.case_2, self.case_3), 1):92            case_url = reverse('testcases-get', args=[case.pk])93            self.assertContains(94                response,95                '<a href="%s">TC-%d: %s</a>' % (case_url, case.pk, case.summary),96                html=True)97class CloneRunBaseTest(BaseCaseRun):98    def assert_one_run_clone_page(self, response):99        """Verify clone page for cloning one test run"""100        self.assertContains(101            response,102            '<input id="id_summary" class="form-control" name="summary" '103            'type="text" value="%s%s" required>' % (_('Clone of '), self.test_run.summary),104            html=True)105        for case_run in (self.execution_1, self.execution_2):106            case_url = reverse('testcases-get', args=[case_run.case.pk])107            self.assertContains(108                response,109                '<a href="%s">TC-%d: %s</a>' % (case_url, case_run.case.pk, case_run.case.summary),110                html=True)111class TestStartCloneRunFromRunPage(CloneRunBaseTest):112    """Test case for cloning run from a run page"""113    @classmethod114    def setUpTestData(cls):115        super(TestStartCloneRunFromRunPage, cls).setUpTestData()116        cls.permission = 'testruns.add_testrun'117        user_should_have_perm(cls.tester, cls.permission)118        user_should_have_perm(cls.tester, 'testruns.view_testrun')119    def test_refuse_without_selecting_case_runs(self):120        self.client.login(  # nosec:B106:hardcoded_password_funcarg121            username=self.tester.username,122            password='password')123        url = reverse('testruns-clone', args=[self.test_run.pk])124        response = self.client.post(url, {}, follow=True)125        self.assertContains(response, _('At least one TestCase is required'))126    def test_open_clone_page_by_selecting_case_runs(self):127        self.client.login(  # nosec:B106:hardcoded_password_funcarg128            username=self.tester.username,129            password='password')130        url = reverse('testruns-clone', args=[self.test_run.pk])131        response = self.client.post(url, {'case_run': [self.execution_1.pk, self.execution_2.pk]})132        self.assert_one_run_clone_page(response)133    def test_clone_a_run(self):134        self.client.login(  # nosec:B106:hardcoded_password_funcarg135            username=self.tester.username,136            password='password')137        new_summary = 'Clone {} - {}'.format(self.test_run.pk, self.test_run.summary)138        clone_data = {139            'summary': new_summary,140            'from_plan': self.plan.pk,141            'product_id': self.test_run.plan.product_id,142            'do': 'clone_run',143            'POSTING_TO_CREATE': 'YES',144            'product': self.test_run.plan.product_id,145            'product_version': self.test_run.product_version.pk,146            'build': self.test_run.build.pk,147            'errata_id': '',148            'manager': self.test_run.manager.email,149            'default_tester': self.test_run.default_tester.email,150            'notes': '',151            'case': [self.execution_1.case.pk, self.execution_2.case.pk],152            'execution_id': [self.execution_1.pk, self.execution_2.pk],153        }154        url = reverse('testruns-new')155        response = self.client.post(url, clone_data)156        cloned_run = TestRun.objects.get(summary=new_summary)157        self.assertRedirects(158            response,159            reverse('testruns-get', args=[cloned_run.pk]))160        self.assert_cloned_run(cloned_run)161    def test_clone_a_run_without_permissions(self):162        remove_perm_from_user(self.tester, 'testruns.add_testrun')163        self.client.login(  # nosec:B106:hardcoded_password_funcarg164            username=self.tester.username,165            password='password')166        new_summary = 'Clone {} - {}'.format(self.test_run.pk, self.test_run.summary)167        clone_data = {168            'summary': new_summary,169            'from_plan': self.plan.pk,170            'product_id': self.test_run.plan.product_id,171            'do': 'clone_run',172            'POSTING_TO_CREATE': 'YES',173            'product': self.test_run.plan.product_id,174            'product_version': self.test_run.product_version.pk,175            'build': self.test_run.build.pk,176            'errata_id': '',177            'manager': self.test_run.manager.email,178            'default_tester': self.test_run.default_tester.email,179            'notes': '',180            'case': [self.execution_1.case.pk, self.execution_2.case.pk],181            'execution_id': [self.execution_1.pk, self.execution_2.pk],182        }183        url = reverse('testruns-new')184        response = self.client.post(url, clone_data)185        self.assertRedirects(186            response,187            reverse('tcms-login') + '?next=' + url)188    def assert_cloned_run(self, cloned_run):189        # Assert clone settings result190        for origin_case_run, cloned_case_run in zip((self.execution_1, self.execution_2),191                                                    cloned_run.case_run.order_by('pk')):192            self.assertEqual(TestExecutionStatus.objects.filter(weight=0).first(),193                             cloned_case_run.status)194            self.assertEqual(origin_case_run.assignee, cloned_case_run.assignee)195class TestSearchRuns(BaseCaseRun):196    @classmethod197    def setUpTestData(cls):198        super(TestSearchRuns, cls).setUpTestData()199        cls.search_runs_url = reverse('testruns-search')200        user_should_have_perm(cls.tester, 'testruns.view_testrun')201    def test_search_page_is_shown(self):202        response = self.client.get(self.search_runs_url)203        self.assertContains(response, '<input id="id_summary" type="text"')204    def test_search_page_is_shown_with_get_parameter_used(self):205        response = self.client.get(self.search_runs_url, {'product': self.product.pk})206        self.assertContains(response,207                            '<option value="%d" selected>%s</option>' % (self.product.pk,208                                                                         self.product.name),209                            html=True)210class TestAddRemoveRunCC(BaseCaseRun):211    """Test view tcms.testruns.views.cc"""212    @classmethod213    def setUpTestData(cls):214        super(TestAddRemoveRunCC, cls).setUpTestData()215        cls.cc_url = reverse('testruns-cc', args=[cls.test_run.pk])216        cls.cc_user_1 = UserFactory(username='cc-user-1',217                                    email='cc-user-1@example.com')218        cls.cc_user_2 = UserFactory(username='cc-user-2',219                                    email='cc-user-2@example.com')220        cls.cc_user_3 = UserFactory(username='cc-user-3',221                                    email='cc-user-3@example.com')222        cls.test_run.add_cc(cls.cc_user_2)223        cls.test_run.add_cc(cls.cc_user_3)224    def test_404_if_run_not_exist(self):225        user_should_have_perm(self.tester, 'testruns.change_testrun')226        cc_url = reverse('testruns-cc', args=[999999])227        response = self.client.get(cc_url)228        self.assertEqual(HTTPStatus.NOT_FOUND, response.status_code)229    def assert_cc(self, response, expected_cc):230        self.assertEqual(len(expected_cc), self.test_run.cc.count())  # pylint: disable=no-member231        for cc in expected_cc:232            href = reverse('tcms-profile', args=[cc.username])233            self.assertContains(234                response,235                '<a href="%s">%s</a>' % (href, cc.username),236                html=True)237    def test_refuse_if_missing_action(self):238        user_should_have_perm(self.tester, 'testruns.change_testrun')239        response = self.client.get(self.cc_url,240                                   {'user': self.cc_user_1.username})241        self.assert_cc(response, [self.cc_user_2, self.cc_user_3])242    def test_add_cc(self):243        user_should_have_perm(self.tester, 'testruns.change_testrun')244        response = self.client.get(245            self.cc_url,246            {'do': 'add', 'user': self.cc_user_1.username})247        self.assert_cc(response,248                       [self.cc_user_2, self.cc_user_3, self.cc_user_1])249    def test_remove_cc(self):250        user_should_have_perm(self.tester, 'testruns.change_testrun')251        response = self.client.get(252            self.cc_url,253            {'do': 'remove', 'user': self.cc_user_2.username})254        self.assert_cc(response, [self.cc_user_3])255    def test_refuse_to_remove_if_missing_user(self):256        user_should_have_perm(self.tester, 'testruns.change_testrun')257        response = self.client.get(self.cc_url, {'do': 'remove'})258        response_text = html.unescape(str(response.content, encoding=settings.DEFAULT_CHARSET))259        self.assertIn(str(_('The user you typed does not exist in database')),260                      response_text)261        self.assert_cc(response, [self.cc_user_2, self.cc_user_3])262    def test_refuse_to_add_if_missing_user(self):263        user_should_have_perm(self.tester, 'testruns.change_testrun')264        response = self.client.get(self.cc_url, {'do': 'add'})265        response_text = html.unescape(str(response.content, encoding=settings.DEFAULT_CHARSET))266        self.assertIn(str(_('The user you typed does not exist in database')),267                      response_text)268        self.assert_cc(response, [self.cc_user_2, self.cc_user_3])269    def test_refuse_if_user_not_exist(self):270        user_should_have_perm(self.tester, 'testruns.change_testrun')271        response = self.client.get(self.cc_url,272                                   {'do': 'add', 'user': 'not exist'})273        response_text = html.unescape(str(response.content, encoding=settings.DEFAULT_CHARSET))274        self.assertIn(str(_('The user you typed does not exist in database')),275                      response_text)276        self.assert_cc(response, [self.cc_user_2, self.cc_user_3])277    def test_should_not_be_able_use_cc_when_user_has_no_pemissions(self):278        remove_perm_from_user(self.tester, 'testruns.change_testrun')279        self.assertRedirects(280            self.client.get(self.cc_url),281            reverse('tcms-login') + '?next=%s' % self.cc_url282        )283class TestAddCasesToRun(BaseCaseRun):284    """Test AddCasesToRunView"""285    @classmethod286    def setUpTestData(cls):287        super(TestAddCasesToRun, cls).setUpTestData()288        cls.proposed_case = TestCaseFactory(289            author=cls.tester,290            default_tester=None,291            reviewer=cls.tester,292            case_status=cls.case_status_proposed,293            plan=[cls.plan])294        user_should_have_perm(cls.tester, 'testruns.add_testexecution')295    def test_show_add_cases_to_run(self):296        url = reverse('add-cases-to-run', args=[self.test_run.pk])297        response = self.client.get(url)298        self.assertNotContains(299            response,300            '<a href="{0}">{1}</a>'.format(301                reverse('testcases-get',302                        args=[self.proposed_case.pk]),303                self.proposed_case.pk),304            html=True305        )306        confirmed_cases = [self.case, self.case_1, self.case_2, self.case_3]307        # Check selected and unselected case id checkboxes308        # cls.case is not added to cls.test_run, so it should not be checked.309        self.assertContains(310            response,311            '<td align="left">'312            '<input type="checkbox" name="case" value="{0}">'313            '</td>'.format(self.case.pk),314            html=True)315        # other cases are added to cls.test_run, so must be checked.316        for case in confirmed_cases[1:]:317            self.assertContains(318                response,319                '<td align="left">'320                '<input type="checkbox" name="case" value="{0}" '321                'disabled="true" checked="true">'322                '</td>'.format(case.pk),323                html=True)324        # Check listed case properties325        # note: the response is ordered by 'case'326        for loop_counter, case in enumerate(confirmed_cases, 1):327            case_url = reverse('testcases-get', args=[case.pk])328            html_pieces = [329                '<a href="{0}">{1}</a>'.format(330                    case_url,331                    case.pk),332                '<td class="js-case-summary" data-param="{0}">'333                '<a id="link_{0}" class="blind_title_link" '334                'href="{2}">{1}</a></td>'.format(loop_counter,335                                                 case.summary,336                                                 case_url),337                '<td>{0}</td>'.format(case.author.username),338                '<td>{0}</td>'.format(339                    formats.date_format(case.create_date, 'DATETIME_FORMAT')),340                '<td>{0}</td>'.format(case.category.name),341                '<td>{0}</td>'.format(case.priority.value),342            ]343            for piece in html_pieces:344                self.assertContains(response, piece, html=True)345class TestRunCasesMenu(BaseCaseRun):346    @classmethod347    def setUpTestData(cls):348        super().setUpTestData()349        user_should_have_perm(cls.tester, 'testruns.view_testrun')350        cls.url = reverse('testruns-get', args=[cls.test_run.pk])351        cls.add_cases_html = \352            '<a href="{0}" class="addBlue9">{1}</a>' \353            .format(354                reverse('add-cases-to-run', args=[cls.test_run.pk]),355                _('Add')356            )357        cls.remove_cases_html = \358            '<a href="#" title="{0}" data-param="{1}" \359            class="removeBlue9 js-del-case">{2}</a>' \360            .format(361                _('Remove selected cases form this test run'),362                cls.test_run.pk,363                _('Remove')364            )365        cls.update_case_run_text_html = \366            '<a href="#" title="{0}" \367            class="updateBlue9" id="update_case_run_text">{1}</a>' \368            .format(369                _('Update the IDLE case runs to newest case text'),370                _('Update')371            )372        cls.change_assignee_html = \373            '<a href="#" title="{0}" \374            class="assigneeBlue9 js-change-assignee">{1}</a>' \375            .format(376                _('Assign this case(s) to other people'),377                _('Assignee')378            )379    def test_add_cases_to_run_with_permission(self):380        user_should_have_perm(self.tester, 'testruns.add_testexecution')381        response = self.client.get(self.url)382        self.assertContains(response, self.add_cases_html, html=True)383    def test_remove_cases_from_run_with_permission(self):384        user_should_have_perm(self.tester, 'testruns.delete_testexecution')385        response = self.client.get(self.url)386        self.assertContains(response, self.remove_cases_html, html=True)387    def test_update_caserun_text_with_permission(self):388        user_should_have_perm(self.tester, 'testruns.change_testexecution')389        response = self.client.get(self.url)390        self.assertContains(response, self.update_case_run_text_html, html=True)391    def test_change_assignee_with_permission(self):392        user_should_have_perm(self.tester, 'testruns.change_testexecution')393        response = self.client.get(self.url)394        self.assertContains(response, self.change_assignee_html, html=True)395    def test_add_cases_to_run_without_permission(self):396        remove_perm_from_user(self.tester, 'testruns.add_testexecution')397        response = self.client.get(self.url)398        self.assertNotContains(response, self.add_cases_html, html=True)399    def test_remove_cases_from_run_without_permission(self):400        remove_perm_from_user(self.tester, 'testruns.delete_testexecution')401        response = self.client.get(self.url)402        self.assertNotContains(response, self.remove_cases_html, html=True)403    def test_update_caserun_text_without_permission(self):404        remove_perm_from_user(self.tester, 'testruns.change_testexecution')405        response = self.client.get(self.url)406        self.assertNotContains(response, self.update_case_run_text_html, html=True)407    def test_change_assignee_without_permission(self):408        remove_perm_from_user(self.tester, 'testruns.change_testexecution')409        response = self.client.get(self.url)410        self.assertNotContains(response, self.change_assignee_html, html=True)411class TestRunStatusMenu(BaseCaseRun):412    @classmethod413    def setUpTestData(cls):414        super().setUpTestData()415        cls.url = reverse('testruns-get', args=[cls.test_run.pk])416        user_should_have_perm(cls.tester, 'testruns.view_testrun')417        cls.status_menu_html = []418        for execution_status in TestExecutionStatus.objects.all():419            cls.status_menu_html.append(420                '<i class="{0}" style="color: {1}"></i>{2}'421                .format(execution_status.icon, execution_status.color, execution_status.name)422            )423    def test_get_status_options_with_permission(self):424        user_should_have_perm(self.tester, 'testruns.change_testexecution')425        response = self.client.get(self.url)426        self.assertEqual(HTTPStatus.OK, response.status_code)427        for html_code in self.status_menu_html:428            self.assertContains(response, html_code, html=True)429    def test_get_status_options_without_permission(self):430        remove_perm_from_user(self.tester, 'testruns.change_testexecution')431        response = self.client.get(self.url)432        self.assertEqual(HTTPStatus.OK, response.status_code)433        for _tcrs in TestExecutionStatus.objects.all():434            self.assertNotContains(response, self.status_menu_html, html=True)435class TestChangeTestRunStatus(BaseCaseRun):436    @classmethod437    def setUpTestData(cls):438        super().setUpTestData()439        cls.url = reverse('testruns-change_status', args=[cls.test_run.pk])440        user_should_have_perm(cls.tester, 'testruns.view_testrun')441    def test_change_status_to_finished(self):442        user_should_have_perm(self.tester, 'testruns.change_testrun')443        response = self.client.get(self.url, {'finished': 1})444        self.assertRedirects(445            response,446            reverse('testruns-get', args=[self.test_run.pk]))447        self.test_run.refresh_from_db()448        self.assertIsNotNone(self.test_run.stop_date)449    def test_change_status_to_running(self):450        user_should_have_perm(self.tester, 'testruns.change_testrun')451        response = self.client.get(self.url, {'finished': 0})452        self.assertRedirects(453            response,454            reverse('testruns-get', args=[self.test_run.pk]))455        self.test_run.refresh_from_db()456        self.assertIsNone(self.test_run.stop_date)457    def test_should_throw_404_on_non_existing_testrun(self):458        user_should_have_perm(self.tester, 'testruns.change_testrun')459        response = self.client.get(reverse('testruns-change_status', args=[99999]), {'finished': 0})460        self.assertEqual(HTTPStatus.NOT_FOUND, response.status_code)461    def test_should_fail_when_try_to_change_status_without_permissions(self):462        remove_perm_from_user(self.tester, 'testruns.change_testrun')463        self.assertRedirects(464            self.client.get(self.url, {'finished': 1}),...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!!
