Best Python code snippet using lettuce-tools_python
tests.py
Source:tests.py  
1# -*- coding: utf-8 -*-2# pylint: disable=invalid-name3import json4from http import HTTPStatus5from uuslug import slugify6from django import test7from django.conf import settings8from django.urls import reverse9from django.utils.translation import ugettext_lazy as _10from tcms.management.models import Product11from tcms.management.models import Version12from tcms.testcases.models import TestCasePlan, TestCaseStatus13from tcms.testplans.models import TestPlan14from tcms.tests.factories import ClassificationFactory15from tcms.tests.factories import ProductFactory16from tcms.tests.factories import TestCaseFactory17from tcms.tests.factories import TestPlanFactory18from tcms.tests.factories import PlanTypeFactory19from tcms.tests.factories import UserFactory20from tcms.tests.factories import VersionFactory21from tcms.tests import BasePlanCase22from tcms.tests import remove_perm_from_user23from tcms.tests import user_should_have_perm24class BasePlanTest(test.TestCase):25    @classmethod26    def setUpTestData(cls):27        cls.user = UserFactory(username='admin', email='admin@example.com')28        cls.user.set_password('admin')29        cls.user.is_superuser = True30        cls.user.is_staff = True31        cls.user.save()32        cls.classification = ClassificationFactory(name='Auto')33        cls.product = ProductFactory(name='Kiwi', classification=cls.classification)34        cls.product_version = VersionFactory(value='0.1', product=cls.product)35        cls.plan_type = PlanTypeFactory()36        cls.test_plan = TestPlanFactory(name='another test plan for testing',37                                        product_version=cls.product_version,38                                        author=cls.user,39                                        product=cls.product,40                                        type=cls.plan_type)41        # add TestCases to plan with status CONFIRMED42        for _i in range(5):43            TestCaseFactory(plan=[cls.test_plan],44                            case_status=TestCaseStatus.objects.get(name='CONFIRMED'))45        # also add a few PROPOSED TestCases46        for _i in range(3):47            TestCaseFactory(plan=[cls.test_plan])48        cls.plan_id = cls.test_plan.pk49        cls.child_plan = TestPlanFactory(parent=cls.test_plan)50    def setUp(self):51        super().setUp()52        self.client.login(username=self.user.username,  # nosec:B106:hardcoded_password_funcarg53                          password='admin')54class PlanTests(BasePlanTest):55    def test_open_plans_search(self):56        location = reverse('plans-search')57        response = self.client.get(location)58        self.assertEqual(response.status_code, HTTPStatus.OK)59    def test_plan_details(self):60        location = reverse('test_plan_url_short', args=[self.plan_id])61        response = self.client.get(location)62        self.assertEqual(response.status_code, HTTPStatus.MOVED_PERMANENTLY)63        response = self.client.get(location, follow=True)64        self.assertEqual(response.status_code, HTTPStatus.OK)65    def test_plan_edit(self):66        location = reverse('plan-edit', args=[self.plan_id])67        response = self.client.get(location)68        self.assertEqual(response.status_code, HTTPStatus.OK)69    def test_plan_printable_without_selected_plan(self):70        location = reverse('plans-printable')71        response = self.client.post(location, follow=True)72        self.assertContains(response, _('At least one test plan is required for print'))73    def test_plan_printable(self):74        location = reverse('plans-printable')75        response = self.client.post(location, {'plan': [self.test_plan.pk]})76        self.assertEqual(response.status_code, HTTPStatus.OK)77        self.assertContains(response, self.test_plan.name)78        self.assertContains(response, self.test_plan.text)79        confirmed = TestCaseStatus.objects.get(name='CONFIRMED')80        for case in self.test_plan.case.filter(case_status=confirmed):81            self.assertContains(response, case.summary)82            self.assertContains(response, case.text)83    def test_plan_attachment(self):84        location = reverse('plan-attachment',85                           args=[self.plan_id])86        response = self.client.get(location)87        self.assertEqual(response.status_code, HTTPStatus.OK)88    def test_plan_history(self):89        # note: the history URL is generated on the fly and not accessible via90        # name91        location = "/admin/testplans/testplan/%d/history/" % self.plan_id92        response = self.client.get(location)93        self.assertEqual(response.status_code, HTTPStatus.OK)94class TestPlanModel(test.TestCase):95    """ Test some model operations directly without a view """96    @classmethod97    def setUpTestData(cls):98        cls.plan_1 = TestPlanFactory()99        cls.testcase_1 = TestCaseFactory()100        cls.testcase_2 = TestCaseFactory()101        cls.plan_1.add_case(cls.testcase_1)102        cls.plan_1.add_case(cls.testcase_2)103    def test_plan_delete_case(self):104        self.plan_1.delete_case(self.testcase_1)105        cases_left = TestCasePlan.objects.filter(plan=self.plan_1.pk)106        self.assertEqual(1, cases_left.count())107        self.assertEqual(self.testcase_2.pk, cases_left[0].case.pk)108    def test_add_cases_sortkey_autoincrement(self):109        """110        When you add new cases, each new case should get a sortkey of the111        highest sortkey in the database + 10.112        The first case should get sortkey 0. The offset between the sortkeys is113        to leave space to insert cases in between without having to update all114        cases.115        """116        plan = TestPlanFactory()117        for sequence_no in range(3):118            case_plan = plan.add_case(TestCaseFactory())119            self.assertEqual(sequence_no * 10, case_plan.sortkey)120        # Check if you can still specify a sortkey manually to insert a case in121        # between the other cases.122        case_plan = plan.add_case(TestCaseFactory(), sortkey=15)123        self.assertEqual(15, case_plan.sortkey)124class TestDeleteCasesFromPlan(BasePlanCase):125    """Test case for deleting cases from a plan"""126    @classmethod127    def setUpTestData(cls):128        super(TestDeleteCasesFromPlan, cls).setUpTestData()129        cls.plan_tester = UserFactory(username='tester')130        cls.plan_tester.set_password('password')131        cls.plan_tester.save()132        cls.cases_url = reverse('plan-delete-cases', args=[cls.plan.pk])133    def test_missing_cases_ids(self):134        self.client.login(  # nosec:B106:hardcoded_password_funcarg135            username=self.plan_tester.username,136            password='password')137        response = self.client.post(self.cases_url)138        data = json.loads(str(response.content, encoding=settings.DEFAULT_CHARSET))139        self.assertEqual(1, data['rc'])140        self.assertEqual('At least one case is required to delete.',141                         data['response'])142    def test_delete_cases(self):143        self.client.login(  # nosec:B106:hardcoded_password_funcarg144            username=self.plan_tester.username,145            password='password')146        post_data = {'case': [self.case_1.pk, self.case_3.pk]}147        response = self.client.post(self.cases_url, post_data)148        data = json.loads(str(response.content, encoding=settings.DEFAULT_CHARSET))149        self.assertEqual(0, data['rc'])150        self.assertEqual('ok', data['response'])151        self.assertFalse(self.plan.case.filter(152            pk__in=[self.case_1.pk, self.case_3.pk]).exists())153class TestSortCases(BasePlanCase):154    """Test case for sorting cases"""155    @classmethod156    def setUpTestData(cls):157        super(TestSortCases, cls).setUpTestData()158        cls.plan_tester = UserFactory(username='tester')159        cls.plan_tester.set_password('password')160        cls.plan_tester.save()161        cls.cases_url = reverse('plan-reorder-cases', args=[cls.plan.pk])162    def test_missing_cases_ids(self):163        self.client.login(  # nosec:B106:hardcoded_password_funcarg164            username=self.plan_tester.username,165            password='password')166        response = self.client.post(self.cases_url)167        data = json.loads(str(response.content, encoding=settings.DEFAULT_CHARSET))168        self.assertEqual(1, data['rc'])169        self.assertEqual('At least one case is required to re-order.', data['response'])170    def test_order_cases(self):171        self.client.login(  # nosec:B106:hardcoded_password_funcarg172            username=self.plan_tester.username,173            password='password')174        post_data = {'case': [self.case_3.pk, self.case_1.pk]}175        response = self.client.post(self.cases_url, post_data)176        data = json.loads(str(response.content, encoding=settings.DEFAULT_CHARSET))177        self.assertEqual({'rc': 0, 'response': 'ok'}, data)178        case_plan_rel = TestCasePlan.objects.get(plan=self.plan, case=self.case_3)179        self.assertEqual(10, case_plan_rel.sortkey)180        case_plan_rel = TestCasePlan.objects.get(plan=self.plan, case=self.case_1)181        self.assertEqual(20, case_plan_rel.sortkey)182class TestLinkCases(BasePlanCase):183    """Test case for linking cases from other plans"""184    @classmethod185    def setUpTestData(cls):186        super(TestLinkCases, cls).setUpTestData()187        cls.another_plan = TestPlanFactory(188            author=cls.tester,189            product=cls.product,190            product_version=cls.version)191        cls.another_case_1 = TestCaseFactory(192            author=cls.tester,193            default_tester=None,194            reviewer=cls.tester,195            plan=[cls.another_plan])196        cls.another_case_2 = TestCaseFactory(197            author=cls.tester,198            default_tester=None,199            reviewer=cls.tester,200            plan=[cls.another_plan])201        cls.plan_tester = UserFactory(username='tester')202        cls.plan_tester.set_password('password')203        cls.plan_tester.save()204        cls.search_cases_for_link_url = reverse('plan-search-cases-for-link',205                                                args=[cls.plan.pk])206        cls.link_cases_url = reverse('plan-link-cases', args=[cls.plan.pk])207    def tearDown(self):208        # Ensure permission is removed whenever it was added during tests209        remove_perm_from_user(self.plan_tester, 'testcases.add_testcaseplan')210    def assert_quick_search_is_shown(self, response):211        self.client.login(  # nosec:B106:hardcoded_password_funcarg212            username=self.plan_tester.username,213            password='password')214        self.assertContains(215            response,216            '<li class="profile_tab_active" id="quick_tab">')217    def assert_normal_search_is_shown(self, response):218        self.client.login(  # nosec:B106:hardcoded_password_funcarg219            username=self.plan_tester.username,220            password='password')221        self.assertContains(222            response,223            '<li class="profile_tab_active" id="normal_tab">')224    def test_show_quick_search_by_default(self):225        self.client.login(  # nosec:B106:hardcoded_password_funcarg226            username=self.plan_tester.username,227            password='password')228        response = self.client.post(self.search_cases_for_link_url, {})229        self.assert_quick_search_is_shown(response)230    def assert_search_result(self, response):231        self.client.login(  # nosec:B106:hardcoded_password_funcarg232            username=self.plan_tester.username,233            password='password')234        self.assertContains(235            response,236            '<a href="{}">{}</a>'.format(237                reverse('testcases-get', args=[self.another_case_2.pk]),238                self.another_case_2.pk))239        # Assert: Do not list case that already belongs to the plan240        self.assertNotContains(241            response,242            '<a href="{}">{}</a>'.format(243                reverse('testcases-get', args=[self.case_2.pk]),244                self.case_2.pk))245    def test_quick_search(self):246        self.client.login(  # nosec:B106:hardcoded_password_funcarg247            username=self.plan_tester.username,248            password='password')249        post_data = {250            'search_mode': 'quick',251            'case_id_set': ','.join(252                map(str, [self.case_1.pk, self.another_case_2.pk]))253        }254        response = self.client.post(self.search_cases_for_link_url, post_data)255        self.assert_quick_search_is_shown(response)256        self.assert_search_result(response)257    def test_normal_search(self):258        self.client.login(  # nosec:B106:hardcoded_password_funcarg259            username=self.plan_tester.username,260            password='password')261        post_data = {262            'search_mode': 'normal',263            'case_id_set': ','.join(264                map(str, [self.case_1.pk, self.another_case_2.pk]))265        }266        response = self.client.post(self.search_cases_for_link_url, post_data)267        self.assert_normal_search_is_shown(response)268        self.assert_search_result(response)269    def test_link_cases(self):270        self.client.login(  # nosec:B106:hardcoded_password_funcarg271            username=self.plan_tester.username,272            password='password')273        user_should_have_perm(self.plan_tester, 'testcases.add_testcaseplan')274        post_data = {275            'case': [self.another_case_1.pk, self.another_case_2.pk]276        }277        response = self.client.post(self.link_cases_url, post_data)278        self.assertRedirects(279            response,280            reverse('test_plan_url', args=[self.plan.pk, slugify(self.plan.name)]))281        self.assertTrue(282            TestCasePlan.objects.filter(283                plan=self.plan, case=self.another_case_1).exists())284        self.assertTrue(285            TestCasePlan.objects.filter(286                plan=self.plan, case=self.another_case_2).exists())287class TestCloneView(BasePlanCase):288    """Test case for cloning a plan"""289    @classmethod290    def setUpTestData(cls):291        super(TestCloneView, cls).setUpTestData()292        cls.another_plan = TestPlanFactory(293            name='Another plan for test',294            author=cls.tester,295            product=cls.product, product_version=cls.version)296        cls.another_case_1 = TestCaseFactory(297            author=cls.tester, default_tester=None,298            reviewer=cls.tester, plan=[cls.another_plan])299        cls.another_case_2 = TestCaseFactory(300            author=cls.tester, default_tester=None,301            reviewer=cls.tester, plan=[cls.another_plan])302        cls.third_plan = TestPlanFactory(303            name='Third plan for test',304            author=cls.tester,305            product=cls.product, product_version=cls.version)306        cls.third_case_1 = TestCaseFactory(307            author=cls.tester, default_tester=None,308            reviewer=cls.tester, plan=[cls.third_plan])309        cls.third_case_2 = TestCaseFactory(310            author=cls.tester, default_tester=None,311            reviewer=cls.tester, plan=[cls.third_plan])312        cls.totally_new_plan = TestPlanFactory(313            name='Test clone plan with copying cases',314            author=cls.tester,315            product=cls.product, product_version=cls.version)316        cls.case_maintain_original_author = TestCaseFactory(317            author=cls.tester, default_tester=None,318            reviewer=cls.tester, plan=[cls.totally_new_plan])319        cls.case_keep_default_tester = TestCaseFactory(320            author=cls.tester, default_tester=None,321            reviewer=cls.tester, plan=[cls.totally_new_plan])322        cls.plan_tester = UserFactory()323        cls.plan_tester.set_password('password')324        cls.plan_tester.save()325        user_should_have_perm(cls.plan_tester, 'testplans.add_testplan')326        cls.plan_clone_url = reverse('plans-clone')327    def test_refuse_if_missing_a_plan(self):328        self.client.login(  # nosec:B106:hardcoded_password_funcarg329            username=self.plan_tester.username,330            password='password')331        data_missing_plan = {}  # No plan is passed332        response = self.client.post(self.plan_clone_url, data_missing_plan, follow=True)333        self.assertContains(response, _('TestPlan is required'))334    def test_refuse_if_given_nonexisting_plan(self):335        self.client.login(  # nosec:B106:hardcoded_password_funcarg336            username=self.plan_tester.username,337            password='password')338        response = self.client.post(self.plan_clone_url, {'plan': 99999}, follow=True)339        self.assert404(response)340    def test_open_clone_page_to_clone_one_plan(self):341        self.client.login(  # nosec:B106:hardcoded_password_funcarg342            username=self.plan_tester.username,343            password='password')344        response = self.client.post(self.plan_clone_url, {'plan': self.plan.pk})345        self.assertContains(346            response,347            '<label class="strong" for="id_name">%s</label>' % _('New Plan Name'),348            html=True)349        self.assertContains(350            response,351            '<input id="id_name" name="name" type="text" value="Copy of {}">'.format(352                self.plan.name),353            html=True)354    def verify_cloned_plan(self, original_plan, cloned_plan,355                           link_cases=True, copy_cases=None,356                           maintain_case_orignal_author=None,357                           keep_case_default_tester=None):358        self.assertEqual('Copy of {}'.format(original_plan.name), cloned_plan.name)359        self.assertEqual(cloned_plan.text, original_plan.text)360        self.assertEqual(Product.objects.get(pk=self.product.pk), cloned_plan.product)361        self.assertEqual(Version.objects.get(pk=self.version.pk), cloned_plan.product_version)362        self._verify_options(original_plan, cloned_plan, copy_cases, link_cases)363        if link_cases and copy_cases:364            # Ensure cases of original plan are not linked to cloned plan365            for case in original_plan.case.all():366                original_case_not_linked_to_cloned_plan = TestCasePlan.objects.filter(367                    plan=cloned_plan, case=case).exists()368                self.assertFalse(original_case_not_linked_to_cloned_plan)369            self.assertEqual(cloned_plan.case.count(), original_plan.case.count())370            # Verify if case' author and default tester are set properly371            for original_case, copied_case in zip(original_plan.case.all(),372                                                  cloned_plan.case.all()):373                if maintain_case_orignal_author:374                    self.assertEqual(original_case.author, copied_case.author)375                else:376                    me = self.plan_tester377                    self.assertEqual(me, copied_case.author)378                if keep_case_default_tester:379                    self.assertEqual(original_case.default_tester, copied_case.default_tester)380                else:381                    me = self.plan_tester382                    self.assertEqual(me, copied_case.default_tester)383    def _verify_options(self, original_plan, cloned_plan, copy_cases, link_cases):384        # Verify option set_parent385        self.assertEqual(TestPlan.objects.get(pk=original_plan.pk), cloned_plan.parent)386        # Verify options link_testcases and copy_testcases387        if link_cases and not copy_cases:388            for case in original_plan.case.all():389                is_case_linked = TestCasePlan.objects.filter(plan=cloned_plan, case=case).exists()390                self.assertTrue(is_case_linked)391    def test_clone_a_plan_with_default_options(self):392        post_data = {393            'name': self.third_plan.make_cloned_name(),394            'plan': self.third_plan.pk,395            'product': self.product.pk,396            'product_version': self.version.pk,397            'set_parent': 'on',398            'link_testcases': 'on',399            'maintain_case_orignal_author': 'on',400            'keep_case_default_tester': 'on',401            'submit': 'Clone',402        }403        self.client.login(  # nosec:B106:hardcoded_password_funcarg404            username=self.plan_tester.username,405            password='password')406        response = self.client.post(self.plan_clone_url, post_data)407        cloned_plan = TestPlan.objects.get(name=self.third_plan.make_cloned_name())408        self.assertRedirects(409            response,410            reverse('test_plan_url_short', args=[cloned_plan.pk]),411            target_status_code=HTTPStatus.MOVED_PERMANENTLY)412        self.verify_cloned_plan(self.third_plan, cloned_plan)413    def test_clone_a_plan_by_copying_cases(self):414        post_data = {415            'name': self.totally_new_plan.make_cloned_name(),416            'plan': self.totally_new_plan.pk,417            'product': self.product.pk,418            'product_version': self.version.pk,419            'set_parent': 'on',420            'link_testcases': 'on',421            'maintain_case_orignal_author': 'on',422            'keep_case_default_tester': 'on',423            'submit': 'Clone',424            'copy_testcases': 'on',425        }426        self.client.login(  # nosec:B106:hardcoded_password_funcarg427            username=self.plan_tester.username,428            password='password')429        self.client.post(self.plan_clone_url, post_data)430        cloned_plan = TestPlan.objects.get(name=self.totally_new_plan.make_cloned_name())431        self.verify_cloned_plan(self.totally_new_plan, cloned_plan,432                                copy_cases=True,433                                maintain_case_orignal_author=True,434                                keep_case_default_tester=True)435    def test_clone_a_plan_by_setting_me_to_copied_cases_author_default_tester(self):436        post_data = {437            'name': self.totally_new_plan.make_cloned_name(),438            'plan': self.totally_new_plan.pk,439            'product': self.product.pk,440            'product_version': self.version.pk,441            'set_parent': 'on',442            'link_testcases': 'on',443            'submit': 'Clone',444            'copy_testcases': 'on',445            # Do not pass maintain_case_orignal_author and keep_case_default_tester446        }447        self.client.login(  # nosec:B106:hardcoded_password_funcarg448            username=self.plan_tester.username,449            password='password')450        self.client.post(self.plan_clone_url, post_data)451        cloned_plan = TestPlan.objects.get(name=self.totally_new_plan.make_cloned_name())...build.py
Source:build.py  
...59    cmd.append("-o")60    cmd.append(dst_path)61    cmd = " ".join(cmd)62    exec_cmd(cmd)63def link_testcases():64    for test_case in config["testcases"]:65        link_testcase(test_case)66def add_prefix(path, key):67    return config[key] + "/" + path68def get_file_name(path):69    """Get file name in path.70    """71    return path[path.rfind("/")+1:]72def filter_and_compile_test_cases(path):73    """Walk and compile testcases related files.74    """75    abs_path = add_prefix(path, "pro_dir") 76    # print(abs_path)77    if os.path.isfile(abs_path):78        # compile79        file_name = get_file_name(path)80        if file_name  in src_files: 81            dst_path = add_prefix(path, "build_dir") + ".o"82            if file_name in compile_files:83                compile_file(abs_path, dst_path)84            config["testobjs"][file_name] = dst_path85    else:86        # dir87        build_dir = add_prefix(path, "build_dir") 88        if not os.path.exists(build_dir):89            os.makedirs(build_dir)90            print("MK dir: " + build_dir)91        # process child92        for child in os.listdir(abs_path):93            filter_and_compile_test_cases(path+"/"+child)94def walk_src(path):95    """Walk and compile src files.96    """97    abs_path = add_prefix(path, "pro_dir") 98    # print(abs_path)99    if os.path.isfile(abs_path):100        # compile101        dst_path = add_prefix(path, "build_dir") + ".o"102        compile_file(abs_path, dst_path)103        config["objs"].append(dst_path)104    else:105        # dir106        build_dir = add_prefix(path, "build_dir") 107        if not os.path.exists(build_dir):108            os.makedirs(build_dir)109            print("MK dir: " + build_dir)110        # process child111        for child in os.listdir(abs_path):112            walk_src(path+"/"+child)113def test_exec():114    cmd = ["ls", config["build_dir"]]115    output = exec_cmd(cmd)116    if output:117        print(output)118    print("Done.")119def test_walk_src():120    src_dir = config["src_dir"]121    walk_src(src_dir)122def test_filter_test_cases():123    src_dir = config["src_dir"]124    global src_files125    global compile_files126    src_files = set()127    compile_files = set()128    for testcase in config["testcases"]:129        for c_file in testcase["compile_files"]:130            compile_files.add(c_file)131        for src_file in testcase["related_files"]:132            src_files.add(src_file)133    print(src_files) 134    print(compile_files)135    filter_and_compile_test_cases(src_dir)136    if config["linked"] == "ON":137        link_testcases()138def run():139    init()140    # test_exec()141    # test_walk_src()142    # link_files()143    test_filter_test_cases()144if __name__ == "__main__":...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!!
