def setUp(self):
     super().setUp()
     self.test_plan = TstPlan()
     self.test_plan_api = TestPlanAPI()
     self.article_api = ArticleAPI()
     self.test_plan.get_test_plans_page()
     self.test_plan_api.set_configuration()
 def setUp(self):
     super().setUp()
     self.article_page = Article()
     self.article_api = ArticleAPI()
     self.test_plan_api = TestPlanAPI()
     self.test_plans_page = TestPlans()
     self.test_plan_page = TstPlan()
     self.orders_page = Orders()
     self.order_api = OrdersAPI()
     self.order_page = Order()
     self.set_authorization(auth=self.article_api.AUTHORIZATION_RESPONSE)
     self.article_api.set_configuration()
     self.article_page.get_articles_page()
 def get_suborder_valid_data(self, formatted_material):
     article_api = ArticleAPI()
     res, payload = article_api.create_article(materialType=formatted_material,
                                               selectedMaterialType=[formatted_material],
                                               materialTypeId=formatted_material['id'])
     article_id = article_api.get_article_id(article_name=payload['name'], article_no=payload['No'])
     formatted_article = {'id': article_id, 'text': payload['name']}
     test_plan = TestPlanAPI().create_completed_testplan(material_type=formatted_material['text'],
                                                         formatted_article=formatted_article)
     tu_res, tu_payload = TestUnitAPI().create_qualitative_testunit(selectedMaterialTypes=[formatted_material])
     data = {'Material Type': formatted_material['text'],
             'Article': formatted_article['text'],
             'Test Plan': test_plan['testPlanEntity']['name'],
             'Test Unit': tu_payload['name']}
     return data
Ejemplo n.º 4
0
    def create_multiple_test_plan_with_same_article(self, no_of_testplans=2):
        materialType = {"id": 1, "text": 'Raw Material'}
        article_data = ArticleAPI(
        ).get_formatted_article_with_formatted_material_type(materialType)
        article_name = article_data['name']
        formatted_article = {'id': article_data['id'], 'text': article_name}
        formatted_material_type = {'id': 1, 'text': 'Raw Material'}
        testPlans = []
        test_units_in_test_plan = []
        for _ in range(no_of_testplans):
            tp = TestPlanAPI().create_completed_testplan(
                material_type='Raw Material',
                formatted_article=formatted_article)
            testPlans.append({
                'id': int(tp['id']),
                'name': tp['testPlanEntity']['name'],
                'version': 1
            })
            test_units_in_test_plan.append(tp['specifications'][0]['name'])

        created_data = {
            'material_type': formatted_material_type,
            'article': formatted_article,
            'testPlans': testPlans,
            'test_units': test_units_in_test_plan
        }
        return created_data
Ejemplo n.º 5
0
    def create_testplan_from_test_unit_id(self, test_unit_id):
        testunit_data = TestUnitAPI().get_testunit_form_data(
            id=test_unit_id)[0]['testUnit']
        if testunit_data['materialTypesObject'][0]['name'] == 'All':
            response, _ = GeneralUtilitiesAPI().list_all_material_types()
            _formatted_material = random.choice(response['materialTypes'])
        else:
            _formatted_material = testunit_data['materialTypesObject'][0]

        formatted_material = {
            'id': _formatted_material['id'],
            'text': _formatted_material['name']
        }

        # tu_response, tu_payload = TestUnitAPI().create_qualitative_testunit()
        testunit_data = TestUnitAPI().get_testunit_form_data(
            id=test_unit_id)[0]['testUnit']
        formated_testunit = TstUnit().map_testunit_to_testplan_format(
            testunit=testunit_data)
        formatted_article = ArticleAPI(
        ).get_formatted_article_with_formatted_material_type(
            formatted_material)
        testplan, payload = self.create_testplan(
            testUnits=[formated_testunit],
            selectedArticles=[formatted_article],
            materialType=[formatted_material],
            materialTypeId=[formatted_material['id']])

        if testplan['message'] == 'operation_success':
            return self.get_testplan_form_data(id=payload['number'])
        else:
            self.info(testplan)
 def setUp(self):
     super().setUp()
     self.test_unit_page = TstUnit()
     self.test_units_page = TstUnits()
     self.test_plan = TstPlan()
     self.article_api = ArticleAPI()
     self.test_unit_api = TestUnitAPI()
     self.set_authorization(auth=self.article_api.AUTHORIZATION_RESPONSE)
     self.test_unit_api.set_configuration()
     self.test_unit_page.get_test_units_page()
Ejemplo n.º 7
0
    def create_testplan_with_article_not_all(self):
        response, _ = GeneralUtilitiesAPI().list_all_material_types()
        formatted_material = random.choice(response['materialTypes'])

        formatted_article = ArticleAPI(
        ).get_formatted_article_with_formatted_material_type(
            formatted_material)
        testplan, payload = self.create_testplan(
            selectedArticles=[formatted_article],
            materialType=[formatted_material])
        if testplan['message'] == 'operation_success':
            return (self.get_testplan_form_data(id=payload['number']))
        else:
            raise Exception(
                f'cant create the test plan with payload {payload}')
    def create_order_with_double_test_plans(self, only_test_plans=False):
        testplan1 = TestPlanAPI().create_completed_testplan_random_data()
        article = testplan1['selectedArticles'][0]['text']
        article_id = testplan1['selectedArticles'][0]['id']
        if article == 'all':
            article, article_id = ArticleAPI().get_random_article_articleID()
        material_type = testplan1['materialType'][0]

        tu_response1, tu_payload1 = TestUnitAPI().create_qualitative_testunit()
        testunit1 = TestUnitAPI().get_testunit_form_data(id=tu_response1['testUnit']['testUnitId'])[0]['testUnit']
        tu_response2, tu_payload2 = TestUnitAPI().create_qualitative_testunit()
        testunit2 = TestUnitAPI().get_testunit_form_data(id=tu_response2['testUnit']['testUnitId'])[0]['testUnit']
        if only_test_plans:
            testunit_list = []
        else:
            testunit_list = [testunit1, testunit2]
        formated_testunit = TstUnit().map_testunit_to_testplan_format(testunit=testunit2)
        formatted_article = {'id': article_id, 'text': article}
        testplan2, _ = TestPlanAPI().create_testplan(testUnits=[formated_testunit],
                                                     selectedArticles=[formatted_article],
                                                     materialTypes=material_type)
        first_testPlan_data = TestPlanAPI()._get_testplan_form_data(id=testplan1['testPlan']['id'])
        testPlan1 = {
            'testPlan': {'id': int(first_testPlan_data[0]['testPlan']['testPlanEntity']['id']),
                         'text': first_testPlan_data[0]['testPlan']['testPlanEntity']['name']},
            'number': int(first_testPlan_data[0]['testPlan']['number'])}

        second_testPlan_data = TestPlanAPI()._get_testplan_form_data(id=testplan2['testPlanDetails']['id'])
        testPlan2 = {
            'testPlan': {'id': int(second_testPlan_data[0]['testPlan']['testPlanEntity']['id']),
                         'text': second_testPlan_data[0]['testPlan']['testPlanEntity']['name']},
            'number': int(second_testPlan_data[0]['testPlan']['number'])}
        testplan_list = [testPlan1, testPlan2]

        payload = {
            'testPlans': testplan_list,
            'testUnits': testunit_list,
            'materialType': material_type,
            'materialTypeId': material_type['id'],
            'article': {'id': article_id, 'text': article},
            'articleId': article_id
        }
        return self.create_new_order(**payload)
Ejemplo n.º 9
0
    def create_double_completed_testplan_same_name_diff_material(
            self, **kwargs):
        self.info("create completed test plan with random data")
        testplan1 = self.create_completed_testplan_random_data()
        test_plan_name_dict = {
            'id': 'new',
            'text': testplan1['testPlan']['text']
        }
        new_material = random.choice(
            GeneralUtilitiesAPI().get_material_types_without_duplicate(
                testplan1['materialType'][0]['text']))
        new_material_id = GeneralUtilitiesAPI().get_material_id(new_material)
        formatted_material = {'id': new_material_id, 'text': new_material}
        tu_response, _ = TestUnitAPI().create_qualitative_testunit(
            selectedMaterialTypes=[formatted_material])
        testunit_data = TestUnitAPI().get_testunit_form_data(
            id=tu_response['testUnit']['testUnitId'])[0]['testUnit']
        formated_testunit = TstUnit().map_testunit_to_testplan_format(
            testunit=testunit_data)
        self.info(
            "create completed test plan with same name {} and new material {}".
            format(testplan1['testPlan']['text'], new_material))
        formatted_article = ArticleAPI(
        ).get_formatted_article_with_formatted_material_type(
            material_type=formatted_material)
        response, testplan2 = self.create_testplan(
            selectedTestPlan=test_plan_name_dict,
            testPlan=test_plan_name_dict,
            testUnits=[formated_testunit],
            selectedArticles=[formatted_article],
            materialType=[formatted_material],
            materialTypeId=[new_material_id])

        if response['message'] == 'name_already_exist':
            testplan2['testPlan']['id'] = response['testPlanDetails'][
                'testPlanId']
            testplan2['selectedTestPlan']['id'] = response['testPlanDetails'][
                'testPlanId']
            return [testplan1, testplan2]
        else:
            raise Exception(
                f'cant create the test plan with payload {testplan2}')
Ejemplo n.º 10
0
 def get_suborder_data_with_different_material_type(self, material_type):
     new_material = random.choice(GeneralUtilitiesAPI(
     ).get_formatted_material_types_without_duplicate(material_type))
     formatted_material = {
         'id': new_material['id'],
         'text': new_material['name']
     }
     formatted_article = ArticleAPI(
     ).get_formatted_article_with_formatted_material_type(
         material_type=formatted_material)
     test_plan_data = self.create_completed_testplan(
         material_type=new_material['name'],
         formatted_article=formatted_article)
     created_data = {
         'test_plan': test_plan_data['testPlanEntity']['name'],
         'test_unit': test_plan_data['specifications'][0]['name'],
         'material_type': new_material['name'],
         'article': formatted_article['name']
     }
     return created_data
Ejemplo n.º 11
0
    def get_order_valid_testplan_and_test_unit(self, material_type, article_id,
                                               article, used_test_plan,
                                               used_test_unit):
        article_no = ArticleAPI().get_article_form_data(
            id=article_id)[0]['article']['No']
        self.info(
            "get new completed test plan with article {} No: {} and material_type {}"
            .format(article, article_no, material_type))
        completed_test_plan_list = self.get_completed_testplans_with_material_and_same_article(
            material_type=material_type, article=article, articleNo=article_no)
        completed_test_plans = [
            testplan for testplan in completed_test_plan_list
            if testplan['testPlanEntity']['name'] not in used_test_plan
        ]
        if completed_test_plans:
            new_test_plan_data = random.choice(completed_test_plans)
            new_test_plan = new_test_plan_data['testPlanEntity']['name']
            new_test_unit = new_test_plan_data['specifications'][0]['name']
            self.info(
                "completed test plan found with name {} and test unit {}".
                format(new_test_plan, new_test_unit))
        else:
            self.info("There is no completed test plan so create it ")
            formatted_article = {'id': article_id, 'text': article}
            test_plan = self.create_completed_testplan(
                material_type=material_type,
                formatted_article=formatted_article)
            new_test_plan = test_plan['testPlanEntity']['name']
            new_test_unit = test_plan['specifications'][0]['name']
            self.info(
                "completed test plan created with name {} and test unit {}".
                format(new_test_plan, new_test_unit))

        if new_test_unit in used_test_unit:
            api, payload = TestUnitAPI().create_quantitative_testunit()
            if api['status'] == 1:
                new_test_unit = payload['name']

        return new_test_plan, new_test_unit
Ejemplo n.º 12
0
    def create_completed_testplan_random_data(self, no_testunits=1):
        random_article = random.choice(ArticleAPI().get_all_articles_json())
        formatted_article = {
            'id': random_article['id'],
            'text': random_article['name']
        }
        material_type_id = GeneralUtilitiesAPI().get_material_id(
            random_article['materialType'])
        formatted_material = {
            'id': material_type_id,
            'text': random_article['materialType']
        }
        # creates test unit with values in it
        formatted_testunits = []
        for testunit in range(no_testunits):
            tu_response, _ = TestUnitAPI().create_quantitative_testunit(
                selectedMaterialTypes=[formatted_material])
            testunit_data = TestUnitAPI().get_testunit_form_data(
                id=tu_response['testUnit']['testUnitId'])[0]['testUnit']
            formatted_testunit = TstUnit().map_testunit_to_testplan_format(
                testunit=testunit_data)
            formatted_testunits.append(formatted_testunit)

        testplan, payload = self.create_testplan(
            testUnits=formatted_testunits,
            selectedArticles=[formatted_article],
            materialType=[formatted_material],
            materialTypeId=[material_type_id])

        if testplan['message'] == 'operation_success':
            payload['testPlan']['id'] = testplan['testPlanDetails'][
                'testPlanId']
            payload['selectedTestPlan']['id'] = testplan['testPlanDetails'][
                'testPlanId']
            return payload
        else:
            return None
class ArticlesTestCases(BaseTest):
    def setUp(self):
        super().setUp()
        self.article_page = Article()
        self.article_api = ArticleAPI()
        self.test_plan_api = TestPlanAPI()
        self.test_plans_page = TestPlans()
        self.test_plan_page = TstPlan()
        self.orders_page = Orders()
        self.order_api = OrdersAPI()
        self.order_page = Order()
        self.set_authorization(auth=self.article_api.AUTHORIZATION_RESPONSE)
        self.article_api.set_configuration()
        self.article_page.get_articles_page()

    @attr(series=True)
    def test021_user_archive_optional_config_fields(self):
        """
            LIMS-4123
            part-1:
                User should be able to archive/restore field
            steps:
             - restore all fields using API
             - archive it via the UI
             - assert all fields have been archived
        """
        self.info('restore all option fields via api')
        self.article_api.restore_all_optional_fields()

        self.info('archive all option fields via ui')
        self.article_page.archive_all_optional_fields()

        self.info('assert all option fields have been archived')
        self.assertFalse(self.article_page.is_field_active('unit'))
        self.assertFalse(self.article_page.is_field_active('comment'))
        self.assertFalse(self.article_page.is_field_active('related article'))

    @attr(series=True)
    def test022_user_restore_optional_config_fields(self):
        """
            LIMS-4123
            part-2:
                User should be able to archive/restore field
            steps:
             - archive all fields using API
             - restore it via the UI
             - assert all fields have been restored
        """
        self.info('archive all option fields via api')
        self.article_api.archive_all_optional_fields()

        self.info('restore all option fields via ui')
        self.article_page.restore_optional_fields()

        self.info('assert all option fields have been archived')
        self.assertFalse(self.article_page.is_field_restore('unit'))
        self.assertFalse(self.article_page.is_field_restore('comment'))
        self.assertFalse(self.article_page.is_field_restore('related article'))

    @attr(series=True)
    def test023_archive_optional_config_fields_does_not_effect_table(self):
        """
            LIMS-4123
            part-4:
                User should be able to archive/restore field
            steps:
             - archive options using api
             - assert all fields have been displayed in table
        """
        self.info('archive all option fields via api')
        self.article_api.archive_all_optional_fields()

        self.info(' open article table')
        self.article_page.get_articles_page()
        article_headers = self.base_selenium.get_table_head_elements('general:table')
        article_headers_text = [header.text for header in article_headers]

        self.info(' assert comment field existance in the table')
        self.assertIn('Comment', article_headers_text)

        self.info(' assert unit field existance in the table')
        self.assertIn('Unit', article_headers_text)

    @parameterized.expand(['edit', 'create'])
    @attr(series=True)
    def test024_archive_optional_config_fields_effect_(self, page):
        """
            LIMS-4123
            part-3:
                User should be able to archive/restore field
            steps:
             - archive options using api
             - assert all fields have been not displayed from the create/edit page
        """
        self.info('archive all option fields via api')
        self.article_api.archive_all_optional_fields()

        if page == "edit":
            self.info('open article edit page')
            self.article_page.open_edit_page(row=self.article_page.get_random_article_row())
        else:
            self.info('open article create page')
            self.base_selenium.click(element='articles:new_article')
            self.article_page.wait_until_page_is_loaded()
        self.info(' assert unit field is not existing in article page')
        self.assertTrue(self.base_selenium.check_element_is_not_exist('article:unit'))

        self.info(' assert comment field is not existing in article page')
        self.assertTrue(self.base_selenium.check_element_is_not_exist('article:comment'))

        self.info(' assert related article field is not existing in article page')
        self.assertTrue(self.base_selenium.check_element_is_not_exist('article:related_article'))

    @parameterized.expand(['edit', 'create'])
    @attr(series=True)
    def test025_restore_optional_config_fields_effect_(self, page):
        """
            LIMS-4123
            part-3:
                User should be able to archive/restore field
            steps:
             - restore options using api
             - assert all fields have been displayed from the create/edit page
        """
        self.info('restore all option fields via api')
        self.article_api.restore_all_optional_fields()

        if page == "edit":
            self.info('open article edit page')
            self.article_page.open_edit_page(row=self.article_page.get_random_article_row())
        else:
            self.info('open article create page')
            self.base_selenium.click(element='articles:new_article')
            self.article_page.wait_until_page_is_loaded()
        self.info('assert unit field is not existing in article page')
        self.assertTrue(self.base_selenium.check_element_is_exist('article:unit'))

        self.info('assert comment field is not existing in article page')
        self.assertTrue(self.base_selenium.check_element_is_exist('article:comment'))
class TestPlansTestCases(BaseTest):
    def setUp(self):
        super().setUp()
        self.test_plan = TstPlan()
        self.test_plan_api = TestPlanAPI()
        self.article_api = ArticleAPI()
        self.test_plan.get_test_plans_page()
        self.test_plan_api.set_configuration()

    def test001_test_plan_delete_testunit(self):
        """
        Testing deleting a test unit from test-plan create or update step two
        It deletes the first test unit in the chosen test plan and saves this,
        then refreshes the page and checks if the deletion was done correctly.

        LIMS-3504
        """
        self.info("get random completed test plan")
        random_completed_test_plan = random.choice(
            self.test_plan_api.get_completed_testplans())
        self.info("navigate to the test-plan No. {} edit page".format(
            random_completed_test_plan['number']))
        self.test_plan.get_test_plan_edit_page_by_id(
            random_completed_test_plan['id'])
        old_testunits = self.test_plan.get_all_testunits_in_testplan()
        self.assertTrue(old_testunits,
                        "There's no test units in this test plan")
        deleted_test_unit = (old_testunits[0])[0]
        self.info("delete the first test unit with name {}".format(
            deleted_test_unit))
        self.test_plan.delete_the_first_testunit_from_the_tableview()
        self.info(
            "save the changes and refresh to make sure test unit deleted")
        self.test_plan.save_and_confirm_popup()
        all_testunits = self.test_plan.get_all_testunits_in_testplan()
        self.info('Checking if the changes were saved successfully')
        deleted_test_unit_found = self.test_plan.check_if_deleted_testunit_is_available(
            all_testunits=all_testunits, deleted_test_unit=deleted_test_unit)
        self.assertFalse(deleted_test_unit_found)

    @parameterized.expand(['InProgress', 'Completed'])
    def test002_test_plan_edit_status(self, status):
        """
        Creation Approach: when the status converted from completed to completed, new version created
        when the status converted from In-Progress to completed, no new version created

        LIMS-3502
        LIMS-3501
        """
        self.info(
            "create test unit of  material type  = All  to complete test plan")
        response, test_unit = TestUnitAPI().create_qualitative_testunit()
        self.assertEqual(response['status'], 1, 'can not create test unit')
        testplan = random.choice(
            self.test_plan_api.get_testplans_with_status(status=status))
        self.assertTrue(testplan, 'No test plan selected')
        self.info(
            'Navigate to edit page of test plan: {} with version: {}'.format(
                testplan['testPlanName'], testplan['version']))
        self.test_plan.get_test_plan_edit_page_by_id(testplan['id'])
        self.info('Going to step 2 to add test unit to this test plan')
        self.test_plan.sleep_tiny()
        self.test_plan.set_test_unit(test_unit=test_unit['name'])
        if status == 'InProgress':
            self.info('Saving and completing the test plan')
            self.test_plan.save(save_btn='test_plan:save_and_complete',
                                sleep=True)
        else:
            self.info('Saving and confirm pop up')
            self.test_plan.save_and_confirm_popup()

        self.info(
            "go back to the active table and get test plan to check its version and status"
        )
        self.test_plan.get_test_plans_page()
        new_test_plan_version, test_plan_row_data_status = \
            self.test_plan.get_testplan_version_and_status(search_text=testplan['testPlanName'])

        if status == 'InProgress':
            self.assertEqual(int(new_test_plan_version), testplan['version'])
        else:
            self.assertGreater(int(new_test_plan_version),
                               int(testplan['version']))

        self.assertEqual(test_plan_row_data_status, 'Completed')

    def test003_archive_test_plan_one_record(self):
        """
        Archive one record

        LIMS-3506 Case 1
        """
        self.info('choosing a random test plan table row')
        selected_test_plan = self.test_plan.select_random_table_row()
        self.assertTrue(selected_test_plan)
        self.info(f'selected_test_plan : {selected_test_plan}')
        testplan_number = selected_test_plan['Test Plan No.']
        self.info(
            'Archive the selected item and navigating to the archived items table'
        )
        self.test_plan.archive_selected_items()
        self.test_plan.get_archived_items()
        archived_row = self.test_plan.search(testplan_number)
        self.info(
            'Checking if test plan number: {} is archived correctly'.format(
                testplan_number))
        self.assertIn(selected_test_plan['Test Plan Name'],
                      archived_row[0].text)
        self.info('Test plan number: {} is archived correctly'.format(
            testplan_number))

    def test004_restore_test_plan_one_record(self):
        """
         Restore one record

         LIMS-3506 Case 1
        """
        self.info("Navigate to archived test plan table")
        self.test_plan.get_archived_items()
        self.info('Choosing a random testplan table row')
        self.test_plan.sleep_tiny()
        selected_test_plan = self.test_plan.select_random_table_row()
        self.info(f"selected_test_plan : {selected_test_plan}")
        self.assertTrue(selected_test_plan)
        testplan_number = selected_test_plan['Test Plan No.']
        self.info('select Testplan number: {} to be restored'.format(
            testplan_number))
        self.info(
            'Restoring the selected item then navigating to the active items table'
        )
        self.test_plan.restore_selected_items()
        self.test_plan.get_active_items()
        self.test_plan.filter_by_testplan_number(filter_text=testplan_number)
        restored_row = self.test_plan.result_table()
        self.info(
            'Checking if testplan number: {} is restored correctly'.format(
                testplan_number))
        self.assertIn(selected_test_plan['Test Plan Name'],
                      restored_row[0].text)
        self.info('Testplan number: {} is restored correctly'.format(
            testplan_number))

    def test005_archive_test_plan_multiple_records(self):
        """
        Archive multiple records

        LIMS-3506 Case 2
        """
        self.info('Choosing random multiple test plans table rows')
        self.test_plan.sleep_small()
        rows_data, rows = self.test_plan.select_random_multiple_table_rows()
        self.assertTrue(rows_data)
        testplans_numbers = [row['Test Plan No.'] for row in rows_data]
        self.info(
            'Testplan numbers: {} will be archived'.format(testplans_numbers))
        self.info(
            'Archiving the selected items and navigating to the archived items table'
        )
        self.test_plan.archive_selected_items()
        self.test_plan.sleep_small()
        self.info('Checking if testplans are archived correctly')
        self.test_plan.get_archived_items()
        archived_rows = self.test_plan.filter_multiple_rows_by_testplans_numbers(
            testplans_numbers)
        self.assertIsNotNone(archived_rows)
        self.assertEqual(len(archived_rows), len(testplans_numbers))
        self.info('Testplan numbers: {} are archived correctly'.format(
            testplans_numbers))

    def test006_restore_test_plan_multiple_records(self):
        """
        Rstore multiple records

        LIMS-3506 Case 2
        """
        self.info("Navigate to archived test plan table")
        self.test_plan.sleep_tiny()
        self.test_plan.get_archived_items()
        self.info('Choosing random multiple test plans table rows')
        self.test_plan.sleep_tiny()
        rows_data, rows = self.test_plan.select_random_multiple_table_rows()
        self.assertTrue(rows_data)
        testplans_numbers = [row['Test Plan No.'] for row in rows_data]
        self.info(
            'Restore Test plans with numbers: {}'.format(testplans_numbers))
        self.test_plan.restore_selected_items()
        self.test_plan.sleep_small()
        self.info('Navigate to active table and make sure test plans restored')
        self.test_plan.get_active_items()
        restored_rows = self.test_plan.filter_multiple_rows_by_testplans_numbers(
            testplans_numbers)
        self.assertIsNotNone(restored_rows)
        self.assertEqual(len(restored_rows), len(testplans_numbers))
        self.info('Test plans numbers: {} are restored correctly'.format(
            testplans_numbers))

    @skip('https://modeso.atlassian.net/browse/LIMS-6403')
    def test007_exporting_test_plan_one_record(self):
        """
        Exporting one record

        LIMS-3508 Case 1
        """
        self.info('choosing a random testplan table row')
        row = self.test_plan.get_random_table_row('general:table')
        row_data = self.base_selenium.get_row_cells_dict_related_to_header(
            row=row)
        testplan_number = row_data['Test Plan No.']
        self.info(
            'testplan number: {} will be exported'.format(testplan_number))
        self.info('Selecting the test plan row')
        self.test_plan.click_check_box(source=row)
        self.info('download XSLX sheet of selected test plan')
        self.test_plan.download_xslx_sheet()
        row_data_list = list(row_data.values())
        self.info('comparing the testplan no. {} '.format(testplan_number))
        values = self.test_plan.sheet.iloc[0].values
        fixed_sheet_row_data = self.fix_data_format(values)
        fixed_row_data_list = self.fix_data_format(row_data_list)
        for item in fixed_row_data_list:
            self.assertIn(item, fixed_sheet_row_data)

    @skip('https://modeso.atlassian.net/browse/LIMS-6403')
    def test008_exporting_test_plan_multiple_records(self):
        """
        Exporting multiple records

        LIMS-3508 Case 2
        """
        self.info('choosing random multiple testplans table rows')
        row_data_list = self.test_plan.select_random_multiple_table_rows(
            element='general:table')[0]
        self.test_plan.download_xslx_sheet()

        row_data = []
        sheet_data = []
        for index in range(len(row_data_list)):
            row_data.append(self.fix_data_format(
                row_data_list[index].values()))
            sheet_data.append(
                self.fix_data_format(self.test_plan.sheet.iloc[index].values))

        row_data = sorted(row_data)
        sheet_data = sorted(sheet_data)
        for index in range(len(row_data)):
            for item in row_data[index]:
                self.assertIn(item, sheet_data[index])

    def test009_test_plan_duplicate(self):
        """
        Duplicate a test plan

        LIMS-3679
        """
        self.info('Choosing a random testplan table row')
        testPlan = random.choice(self.test_plan_api.get_completed_testplans())
        self.assertTrue(testPlan, "No completed test plan selected")
        testunits = self.test_plan_api.get_testunits_in_testplan(
            id=testPlan['id'])
        self.assertTrue(
            testunits,
            "Completed test plan with id {} has no testunits!!".format(
                testPlan['id']))
        self.info("select test plan {}".format(testPlan['testPlanName']))
        self.test_plan.filter_by_testplan_number(testPlan['number'])
        row = self.test_plan.result_table()[0]
        self.test_plan.click_check_box(source=row)
        self.info('Duplicating testplan number: {}'.format(testPlan['number']))
        self.test_plan.duplicate_selected_item()
        duplicated_test_plan_number = self.test_plan.duplicate_testplan(
            change=['name'])
        self.info('testplan duplicated with number: {}'.format(
            duplicated_test_plan_number))
        self.info('get duplicated test plan data and child table data')
        duplicated_testplan_data, duplicated_testplan_childtable_data = \
            self.test_plan.get_specific_testplan_data_and_childtable_data(
                filter_by='number', filter_text=duplicated_test_plan_number)
        duplicated_test_units = []
        for testunit in duplicated_testplan_childtable_data:
            duplicated_test_units.append(testunit['Test Unit Name'])

        self.info('Asserting that the data is duplicated correctly')
        self.assertEqual(testPlan['materialTypes'][0],
                         duplicated_testplan_data['Material Type'])
        self.assertEqual(testPlan['article'][0],
                         duplicated_testplan_data['Article Name'])
        self.assertEqual(testPlan['articleNo'][0],
                         duplicated_testplan_data['Article No.'])
        for testunit in testunits:
            self.assertIn(testunit['name'], duplicated_test_units)

    def test010_test_plan_completed_to_inprogress(self):
        """
        When the test plan status is converted from completed to in progress a new version is created

        LIMS-3503
        """
        self.info('get random completed test plan')
        completed_testplan = random.choice(
            self.test_plan_api.get_completed_testplans())
        self.assertTrue(completed_testplan, "There's no completed test plans!")
        self.info(
            'Navigating to edit page of testplan: {} with version: {}'.format(
                completed_testplan['testPlanName'],
                completed_testplan['version']))
        self.test_plan.get_test_plan_edit_page_by_id(completed_testplan['id'])
        self.info('Going to step 2 to remove all the test units from it')
        self.test_plan.navigate_to_testunits_selection_page()
        self.test_plan.sleep_tiny()
        self.test_plan.delete_all_testunits()
        self.test_plan.save_and_confirm_popup()

        self.info("go back to active table")
        self.test_plan.get_test_plans_page()

        self.info(
            'Getting the currently changed testplan to check its status and version'
        )
        inprogress_testplan_version, testplan_row_data_status = \
            self.test_plan.get_testplan_version_and_status(search_text=completed_testplan['testPlanName'])

        self.assertEqual(completed_testplan['version'] + 1,
                         int(inprogress_testplan_version))
        self.assertEqual(testplan_row_data_status, 'In Progress')

    @parameterized.expand(['same', 'All'])
    def test011_create_testplans_same_name_article_materialtype(self, same):
        """
        Testing the creation of two testplans with the same name, material type
        and article, this shouldn't happen

        LIMS-3499

        New: Test plan: Creation Approach: I can't create two test plans
        with the same name & same materiel type & one with any article
        and the other one all

        LIMS-3500
        """
        payload = self.test_plan_api.create_completed_testplan_random_data()
        self.test_plan.click_create_test_plan_button()
        self.test_plan.set_test_plan(name=payload['testPlan']['text'])
        self.assertFalse(
            self.test_plan.is_material_type_existing(
                material_type=payload['materialType'][0]['text']))

    def test012_create_testplans_same_name_different_materialtype(self):
        """
        Testing the creation of two testplans with the same name, but different material type
        and article. It should be created successfully.

        LIMS-3498
        """
        self.info('create complete test plan')
        payload = self.test_plan_api.create_completed_testplan_random_data()
        self.assertTrue(payload, 'can not create a tesplan')
        articles = self.article_api.get_all_articles_json()
        for article in articles:
            if article['name'] != payload['selectedArticles'][0]['text'] and article['materialType'] != \
                    payload['materialType'][0]['text']:
                self.info(
                    'create another testplan with the same name, but with different material type and article name'
                )
                second_testplan_name = self.test_plan.create_new_test_plan(
                    name=payload['testPlan']['text'],
                    material_type=article['materialType'],
                    article=article['name'])
                self.info(
                    'new testplan is created successfully with name: {}, article name: {} and material type: {}'
                    .format(second_testplan_name, self.test_plan.article,
                            self.test_plan.material_type))

                self.assertEqual(payload['testPlan']['text'],
                                 second_testplan_name)
                data = self.test_plan.search(second_testplan_name)
                self.assertGreaterEqual(len(data), 2)
                break

    def test013_delete_used_testplan(self):
        """
        If a test plan is used, it can't be deleted

        LIMS-3509
        """
        self.info("create order with test plan")
        response, payolad = OrdersAPI().create_new_order()
        self.assertEqual(response['status'], 1, payolad)
        self.info("created order no {} has testplan name {}".format(
            payolad[0]['orderNo'], payolad[0]['testPlans'][0]['name']))
        self.info('testplan name: {} will be archived'.format(
            payolad[0]['testPlans'][0]['name']))
        self.test_plan.base_selenium.refresh()
        testplan_deleted = self.test_plan.delete_selected_item_from_active_table_and_from_archived_table(
            item_name=payolad[0]['testPlans'][0]['name'])

        self.info(
            "check for the error popup that this testplan is used and can't be deleted"
        )
        self.assertFalse(testplan_deleted)

    def test014_archived_testplan_shouldnot_appear_in_order(self):
        """
        In case a testplan is archived, it shouldn't appear when creating a new order

        LIMS-3708
        """
        self.info("navigate to orders page")
        self.order_page = Order()
        self.info("get random archived testplan")
        response, payload = self.test_plan_api.get_all_test_plans()
        self.assertEqual(response['status'], 1, payload)
        archived_test_plan = random.choice(response['testPlans'])
        self.test_plan_api.archive_testplans(
            ids=[str(archived_test_plan['id'])])
        self.order_page.get_orders_page()

        self.info("archived test plan data {}".format(archived_test_plan))
        self.info(
            "create a new order with material type and article of archived testplan"
        )
        if archived_test_plan['article'] != ['all']:
            self.order_page.create_new_order(
                material_type=archived_test_plan['materialTypes'][0],
                article=archived_test_plan['article'][0],
                test_plans=[archived_test_plan['testPlanName']])
        else:
            self.order_page.create_new_order(
                material_type=archived_test_plan['materialTypes'][0],
                test_plans=[archived_test_plan['testPlanName']])
        order_data = self.order_page.get_suborder_data()
        self.info(
            "get the first suborder's testplan and make sure it's an empty string"
        )
        self.assertCountEqual(order_data['suborders'][0]['testplans'], [''])

    def test015_testunit_sub_super_scripts(self):
        """
        Create a testunit with sub/super scripts, use this testunit to create a testplan
        and check the sub/super scripts in the card view

        LIMS-5796
        """
        self.info("create test unit with sub and super scripts")
        response, payload = TestUnitAPI().create_qualitative_testunit(
            unit='mg[2]{o}')
        self.assertEqual(response['status'], 1, payload)
        self.info("created test unit data {}".format(payload))
        self.info("create test plan with same created test unit data")
        if payload['selectedMaterialTypes'][0]['text'] == 'All':
            self.test_plan.create_new_test_plan(test_unit=payload['name'],
                                                save=False)
        else:
            self.test_plan.create_new_test_plan(
                material_type=payload['selectedMaterialTypes'][0]['text'],
                test_unit=payload['name'],
                save=False)

        unit = self.base_selenium.find_element('test_plan:testunit_unit').text
        self.assertEqual(unit, 'mg2o')

    def test016_filter_by_testplan_number(self):
        """
        User can filter with testplan number

        LIMS-6473
        """
        self.info("select random test plan")
        random_testplan = random.choice(
            self.test_plan_api.get_all_test_plans_json())
        self.info("selected_test_plan No {}".format(random_testplan['number']))
        self.test_plan.filter_by_testplan_number(random_testplan['number'])
        testplan_found = self.test_plan.result_table()
        self.assertIn(str(random_testplan['number']),
                      (testplan_found[0].text).replace("'", ""))
        self.info('Filtering by number was done successfully')

    def test017_filter_by_testplan_name(self):
        """
        User can filter with testplan name

        LIMS-6470
        """
        random_testplan = random.choice(
            self.test_plan_api.get_all_test_plans_json())
        self.assertTrue(random_testplan, "can't select random test plan !")
        testplans_found_text = self.test_plan.filter_by_element_and_get_text(
            'Testplan Name', 'test_plans:testplan_name_filter',
            random_testplan['testPlanName'], 'drop_down')

        for tp_text in testplans_found_text:
            self.assertIn(str(random_testplan['testPlanName']),
                          tp_text.replace("'", ""))

    @parameterized.expand(['Completed', 'In Progress'])
    def test018_filter_by_testplan_status(self, status):
        """
        User can filter with status

        LIMS-6474
        """
        testplans_found_text = \
            self.test_plan.filter_by_element_and_get_text('Status', 'test_plans:testplan_status_filter',
                                                          status, 'drop_down')
        for tp_text in testplans_found_text:
            self.assertIn(status, tp_text)
            if status == "In Progress":
                self.assertNotIn('Completed', tp_text)
            else:
                self.assertNotIn('In Progress', tp_text)

    def test019_filter_by_testplan_changed_by(self):
        """
        User can filter with changed by field

        LIMS-6475
        """
        self.login_page = Login()
        self.info('Calling the users api to create a new user with username')
        response, payload = UsersAPI().create_new_user()
        self.assertEqual(response['status'], 1, payload)
        self.test_plan.sleep_tiny()
        self.login_page.logout()
        self.test_plan.sleep_tiny()
        self.login_page.login(username=payload['username'],
                              password=payload['password'])
        self.base_selenium.wait_until_page_url_has(text='dashboard')
        self.test_plan.get_test_plans_page()
        self.test_plan.sleep_tiny()
        testplan_name = self.test_plan.create_new_test_plan()

        self.info('New testplan is created successfully with name: {}'.format(
            testplan_name))
        self.test_plan.set_all_configure_table_columns_to_specific_value(
            value=True)

        testplan_found = self.test_plan.filter_by_element_and_get_results(
            'Changed By', 'test_plans:testplan_changed_by_filter',
            payload['username'], 'drop_down')
        self.assertEqual(len(testplan_found), 2)
        self.assertIn(payload['username'], testplan_found[0].text)
        self.assertIn(testplan_name, testplan_found[0].text)

    def test020_filter_by_testplan_material_type(self):
        """
        User can filter with material type field

        LIMS-6471
        """
        random_testplan = random.choice(
            self.test_plan_api.get_all_test_plans_json())
        testplans_found_text = self.test_plan.filter_by_element_and_get_text(
            'Material Type', 'test_plans:testplan_material_type_filter',
            random_testplan['materialTypes'][0], 'drop_down')

        for tp_text in testplans_found_text:
            self.assertIn(str(random_testplan['materialTypes'][0]), tp_text)

    def test021_filter_by_testplan_article(self):
        """
        User can filter with article field

        LIMS-6472
        """
        random_testplan = random.choice(
            self.test_plan_api.get_all_test_plans_json())
        if random_testplan['article'][0] == 'all':
            testplans_found_text = self.test_plan.filter_by_element_and_get_text(
                'Article', 'test_plans:testplan_article_filter', 'All',
                'drop_down')
        else:
            testplans_found_text = self.test_plan.filter_by_element_and_get_text(
                'Article', 'test_plans:testplan_article_filter',
                random_testplan['articleNo'][0], 'drop_down')

        for tp_text in testplans_found_text:
            self.assertIn(str(random_testplan['article'][0]), tp_text)

    def test022_filter_by_testplan_created_on(self):
        """
        User can filter with created on field

        LIMS-6476
        """
        random_testplan = random.choice(
            self.test_plan_api.get_all_test_plans_json())
        date = datetime.datetime.strptime(random_testplan['createdAt'],
                                          "%Y-%m-%dT%H:%M:%S.%fZ")
        date_formatted = datetime.datetime.strftime(date, '%d.%m.%Y')

        testplans_found_text = self.test_plan.filter_by_element_and_get_text(
            'Created On', 'test_plans:testplan_created_on_filter',
            date_formatted, 'date')

        for tp_text in testplans_found_text:
            self.assertIn(date_formatted, tp_text)

    @parameterized.expand(['ok', 'cancel'])
    def test023_create_approach_overview_button(self, ok):
        """
        Master data: Create: Overview button Approach: Make sure
        after I press on the overview button, it redirects me to the active table

        LIMS-6203
        """
        self.info("click on create test plan button")
        self.test_plan.click_create_test_plan_button()
        self.info("click on Overview, this will display an alert to the user")
        self.test_plan.click_overview()
        # switch to the alert
        if 'ok' == ok:
            self.info("confirm pop-up")
            self.test_plan.confirm_overview_pop_up()
            self.assertEqual(self.base_selenium.get_url(),
                             '{}testPlans'.format(self.base_selenium.url))
            self.info('clicking on Overview confirmed')
        else:
            self.info("cancel pop-up")
            self.test_plan.cancel_overview_pop_up()
            self.assertEqual(self.base_selenium.get_url(),
                             '{}testPlans/add'.format(self.base_selenium.url))
            self.info('clicking on Overview cancelled')

    def test024_edit_approach_overview_button(self):
        """
        Edit: Overview Approach: Make sure after I press on
        the overview button, it redirects me to the active table

        LIMS-6202
        """
        testplan = random.choice(self.test_plan_api.get_all_test_plans_json())
        self.info('Navigate to edit page of test plan: {} '.format(
            testplan['testPlanName']))
        self.test_plan.get_test_plan_edit_page_by_id(testplan['id'])
        testplans_url = self.base_selenium.get_url()
        self.info('testplans_url : {}'.format(testplans_url))
        self.info('click on Overview, it will redirect you to test plans page')
        self.test_plan.click_overview()
        self.test_plan.sleep_tiny()
        self.assertEqual(self.base_selenium.get_url(),
                         '{}testPlans'.format(self.base_selenium.url))
        self.info('clicking on Overview confirmed')

    def test025_testplans_search_then_navigate(self):
        """
        Search Approach: Make sure that you can search then navigate to any other page

        LIMS-6201
        """
        testplan = random.choice(self.test_plan_api.get_all_test_plans_json())
        search_results = self.test_plan.search(testplan['testPlanName'])
        self.assertGreater(
            len(search_results), 1,
            " * There is no search results for it, Report a bug.")
        # Navigate to articles page
        self.info('navigate to articles page')
        Articles().get_articles_page()
        self.assertEqual(self.base_selenium.get_url(),
                         '{}articles'.format(self.base_selenium.url))

    def test026_hide_all_table_configurations(self):
        """
        Table configuration: Make sure that you can't hide all the fields from the table configuration

        LIMS-6288
        """
        self.assertFalse(self.test_plan.deselect_all_configurations())

    def test027_test_unit_update_version_in_testplan(self):
        """
        Test plan: Test unit Approach: In case I update category & iteration of
        test unit that used in test plan with new version, when  go to test plan
        to add the same test unit , I found category & iteration updated

        LIMS-3703
        """
        self.test_unit_page = TstUnit()
        self.info("select random test unit to create the test plan with it")
        testunit = random.choice(TestUnitAPI().get_testplan_valid_test_unit())

        self.info(
            'A random test unit is chosen, its name: {}, category: {} and number of iterations: {}'
            .format(testunit['name'], testunit['categoryName'],
                    testunit['iterations']))

        self.info("create the first testplan")
        first_testplan_name, payload1 = self.test_plan_api.create_testplan()
        self.info('First test plan create with name: {}'.format(
            payload1['testPlan']['text']))

        self.info(
            "go to testplan edit to get the number of iterations and test unit category"
        )
        first_testplan_testunit_category, first_testplan_testunit_iteration = \
            self.test_plan.get_testunit_category_iterations(payload1['testPlan']['text'], testunit['name'])

        self.info(
            "go to test units' active table and search for this test unit")
        self.test_unit_page.get_test_units_page()
        self.info('Navigating to test unit {} edit page'.format(
            testunit['name']))
        self.test_unit_page.open_test_unit_edit_page_by_id(testunit['id'])
        self.test_unit_page.sleep_small()
        new_iteration = str(int(first_testplan_testunit_iteration) + 1)
        new_category = self.generate_random_string()
        self.info("update the iteration to {} and category to {}".format(
            new_iteration, new_category))
        self.test_unit_page.set_category(new_category)
        self.test_unit_page.set_testunit_iteration(new_iteration)
        self.info("press save and complete to create a new version")
        self.test_unit_page.save_and_create_new_version()

        self.info(" go back to test plans active table")
        self.test_plan.get_test_plans_page()
        self.info(
            " create new testplan with this testunit after creating the new version"
        )
        response, payload2 = self.test_plan_api.create_testplan()
        self.assertEqual(response["status"], 1)
        second_testplan_name = payload2['testPlan']['text']
        self.info('Second test plan create with name: {}'.format(
            second_testplan_name))

        self.info(
            "check the iteration and category to be the same as the new version"
        )
        self.info(
            "go to testplan edit to get the number of iterations and testunit category"
        )
        second_testplan_testunit_category, second_testplan_testunit_iteration = \
            self.test_plan.get_testunit_category_iterations(second_testplan_name, testunit['name'])

        self.info(
            'Asserting that the category of the test unit in the first test plan is not updated'
        )
        self.assertNotEqual(first_testplan_testunit_category, new_category)
        self.info(
            'Asserting that the iterations of the test unit in the first test plan is not updated'
        )
        self.assertNotEqual(first_testplan_testunit_iteration,
                            second_testplan_testunit_iteration)
        self.info(
            'Asserting that the category of the test unit in the second new_iteration is the '
            'same as the updated category')
        self.assertEqual(second_testplan_testunit_category, new_category)
        self.info(
            'Asserting that the iterations of the test unit in the second testplan is the '
            'same as the updated iterations')
        self.assertEqual(second_testplan_testunit_iteration, new_iteration)

    def test028_childtable_limits_of_quantification(self):
        """
        Limits of quantification should be viewed in the testplan's child table

        LIMS-4179

        New: Test plan: Limits of quantification Approach: In case I update the limits
        of quantification this will trigger new version in the active table & version table

        LIMS-4426
        """
        self.info(
            "Create new quantitative test unit with quantification limits")
        self.test_unit_api = TestUnitAPI()
        oldUpperLimit = self.generate_random_number(lower=50, upper=100)
        oldLowerLimit = self.generate_random_number(lower=1, upper=49)
        tu_response, tu_payload = self.test_unit_api.create_quantitative_testunit(
            quantificationUpperLimit=oldUpperLimit,
            quantificationLowerLimit=oldLowerLimit,
            useQuantification=True,
            useSpec=False)
        self.assertEqual(tu_response['status'], 1, tu_payload)
        testunit_display_old_quantification_limit = '{}-{}'.format(
            tu_payload['quantificationLowerLimit'],
            tu_payload['quantificationUpperLimit'])

        test_plan = self.test_plan_api.create_testplan_from_test_unit_id(
            tu_response['testUnit']['testUnitId'])
        self.assertTrue(test_plan, "failed to create test plan")
        testplan_childtable_data = self.test_plan.search_and_get_childtable_data_for_testplan(
            test_plan['testPlanEntity']['name'])
        self.info('Asserting the limits of quantification viewed correctly')
        self.assertIn(testunit_display_old_quantification_limit,
                      testplan_childtable_data[0].values())

        new_quantification_lower_limit, new_quantification_upper_limit = \
            self.test_plan.update_upper_lower_limits_of_testunit(test_plan['id'])

        testunit_display_new_quantification_limit = '{}-{}'.format(
            new_quantification_lower_limit, new_quantification_upper_limit)

        self.test_plan.get_test_plans_page()
        testplan_childtable_data = self.test_plan.search_and_get_childtable_data_for_testplan(
            test_plan['testPlanEntity']['name'])
        self.info('Asserting the limits of quantification viewed correctly')
        self.assertIn(testunit_display_new_quantification_limit,
                      testplan_childtable_data[0].values())
        test_plan_data = self.test_plan.get_the_latest_row_data()
        self.info('Asserting that new version created')
        self.assertEqual(test_plan_data['Version'], '2')