def test_find_file_across_common_paths(stc):
    common_data_path = meth_man_utils.get_common_data_path()

    cleanup_info = UnitTestUtils.create_meth_tree_test_files()
    try:
        p1 = meth_man_utils.find_file_across_common_paths('file1')
        assert p1 == os.path.normpath(os.path.join(common_data_path, 'file1'))

        p2 = meth_man_utils.find_file_across_common_paths('file2')
        assert p2 == os.path.normpath(os.getcwd() + '/file2')

        p3 = meth_man_utils.find_file_across_common_paths('file3')
        assert p3 == ''
        p3 = meth_man_utils.find_file_across_common_paths('file3', True)
        assert p3 == ''
        p3 = meth_man_utils.find_file_across_common_paths('file3', True, True)
        assert p3 == ''

        p4 = meth_man_utils.find_file_across_common_paths('file4')
        assert p4 == ''
        p4 = meth_man_utils.find_file_across_common_paths('file4', False, True)
        assert p4 == ''
        p4 = meth_man_utils.find_template_across_common_paths('file4')
        assert p4 == ''
        p4 = meth_man_utils.find_file_across_common_paths('file4', True, False)
        expected = os.path.normpath(os.path.join(
            common_data_path, mgr_const.MM_SCRIPTS_DIR, 'file4'))
        assert p4 == expected
        p4 = meth_man_utils.find_script_across_common_paths('file4')
        assert p4 == expected

        p5 = meth_man_utils.find_file_across_common_paths('file5')
        assert p5 == ''
        p5 = meth_man_utils.find_file_across_common_paths('file5', False, True)
        expected = os.path.normpath(
            os.path.join(common_data_path, mgr_const.MM_TEMPLATE_DIR, 'file5'))
        assert p5 == expected
        p5 = meth_man_utils.find_template_across_common_paths('file5')
        assert p5 == expected
        p5 = meth_man_utils.find_file_across_common_paths('file5', True, False)
        assert p5 == ''
        p5 = meth_man_utils.find_script_across_common_paths('file5')
        assert p5 == ''
    finally:
        UnitTestUtils.cleanup_meth_tree_test_files(cleanup_info)
    return
def test_delete(stc):
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogInfo("test_delete.begin")

    ctor = CScriptableCreator()
    hnd_reg = CHandleRegistry.Instance()

    meth_key = "UNITTEST_DEL"
    UnitTestUtils.create_fake_installed_test_meth(meth_key, [])

    UnitTestUtils.add_fake_test_case(meth_key, [], meth_key + "-1")
    UnitTestUtils.add_fake_test_case(meth_key, [], meth_key + "-2")

    # Update the BLL objects
    meth_man_utils.build_test_methodology_manager(use_txml=True)

    meth_handle = UnitTestUtils.get_methodology_handle(meth_key)
    assert meth_handle
    meth_obj = hnd_reg.Find(meth_handle)
    assert meth_obj is not None

    tc_obj_list = meth_obj.GetObjects("StmTestCase")
    assert len(tc_obj_list) == 2
    tc_obj1 = None
    tc_obj2 = None
    for tc_obj in tc_obj_list:
        if tc_obj.Get("TestCaseKey") == meth_key + "-1":
            tc_obj1 = tc_obj
        elif tc_obj.Get("TestCaseKey") == meth_key + "-2":
            tc_obj2 = tc_obj
    assert tc_obj1
    tc_obj1_path = tc_obj1.Get("Path")
    assert tc_obj2
    tc_obj2_path = tc_obj2.Get("Path")

    # Delete an installed test case
    cmd = ctor.CreateCommand(PKG + ".DeleteTestCaseCommand")
    cmd.Set("StmTestCase", tc_obj2.GetObjectHandle())
    cmd.Execute()
    cmd.MarkDelete()

    # Check the path
    assert os.path.exists(tc_obj1_path)
    assert not os.path.exists(tc_obj2_path)

    # Delete installed test methodology
    cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
    cmd.Set("StmMethodology", meth_obj.GetObjectHandle())
    cmd.Execute()
    cmd.MarkDelete()

    stc_sys = CStcSystem.Instance()
    common_data_path = stc_sys.GetApplicationCommonDataPath()
    install_dir = os.path.join(common_data_path, mgr_const.MM_TEST_METH_DIR)
    test_meth_dir = os.path.join(install_dir, meth_key)

    assert os.path.exists(test_meth_dir) is False
    plLogger.LogInfo("test_delete.end")
def test_create_new_testcase(stc):
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogInfo("test_create_new_testcase")

    # Test empty meth key
    err_msg, tc_key, tc_obj_hnd = meth_man_utils.create_new_testcase("", "")
    assert err_msg == "Methodology key appears to be invalid."
    assert tc_key is None
    assert tc_obj_hnd is None

    # Create a fresh copy of the UnitTestMeth methodology...
    meth_man_utils.methodology_rmdir("UnitTestMeth")
    meth_path = meth_man_utils.methodology_mkdir("UnitTestMeth")
    UnitTestUtils.create_fake_installed_test_meth("UnitTestMeth", [])
    meth_man_utils.build_test_methodology(meth_path, True)

    err_msg, tc_key, tc_obj_hnd = meth_man_utils.create_new_testcase("UnitTestMeth", "tcx")
    assert err_msg == ""
    assert tc_key is not None
    assert tc_obj_hnd is not None

    # Clean up...
    meth_man_utils.methodology_rmdir("UnitTestMeth")
    return
def test_run_pass_in_json(stc):
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogInfo("begin test_run")

    stc_sys = CStcSystem.Instance()
    sequencer = stc_sys.GetObject("Sequencer")
    ctor = CScriptableCreator()
    common_data_path = stc_sys.GetApplicationCommonDataPath()

    # Create exposed properties for the ports
    project = stc_sys.GetObject('Project')
    left_tag = tag_utils.get_tag_object('Left_Port_Group')
    ep_cfg = ctor.Create('ExposedConfig', project)
    ep = ctor.Create('ExposedProperty', ep_cfg)
    ep.Set('EPNameId', 'LeftPortGroup')
    ep.Set('EPClassId', 'tag')
    ep.Set('EPPropertyId', 'scriptable.name')
    ep.AddObject(left_tag, RelationType('ScriptableExposedProperty'))

    meth_name = "RFC2544THROUGHPUT_SAMPLE_BASIC"
    test_name = "test_run"

    # Clean up the fake installed methodology (if it exists)
    if os.path.exists(os.path.join(common_data_path,
                                   mgr_const.MM_TEST_METH_DIR,
                                   meth_name)):
        meth_man_utils.methodology_rmdir(meth_name)

    # Create a fake installed methodology
    home_dir = meth_man_utils.get_methodology_home_dir()
    assert home_dir is not None
    meth_dir = meth_man_utils.methodology_mkdir(meth_name)
    assert meth_dir is not None
    test_dir = meth_man_utils.methodology_test_case_mkdir(meth_name, test_name)
    assert test_dir is not None

    # Add a fake sequence file
    seq_file = os.path.join(meth_dir, mgr_const.MM_SEQUENCER_FILE_NAME)
    f = open(seq_file, "w")
    f.write("<?xml version=\"1.0\" encoding=\"windows-1252\"?>")
    f.close()

    # Add a fake TXML file
    meta_file = os.path.join(meth_dir, mgr_const.MM_META_FILE_NAME)
    f = open(meta_file, "w")
    data = UnitTestUtils.gen_test_info_header("unit test meth disp name",
                                              meth_name,
                                              "unit test meth test case",
                                              "")
    data = data + UnitTestUtils.UTU_FOOTER
    f.write(data)
    f.close()

    # Initialize the methodology manager by calling update
    cmd = ctor.CreateCommand(PKG +
                             ".UpdateTestMethodologyManagerCommand")
    cmd.Execute()
    cmd.MarkDelete()

    # meth_man = meth_man_utils.get_meth_manager()
    # assert meth_man
    # test_meth_obj_list = meth_man.GetObjects("StmMethodology")
    # assert len(test_meth_obj_list) > 0

    # test_meth = None
    # for test_meth_obj in test_meth_obj_list:
    #     act_meth_key = test_meth_obj.Get("MethodologyKey")
    #     plLogger.LogDebug("meth_name: " + test_meth_obj.Get("Name"))
    #     plLogger.LogDebug("meth_key: " + test_meth_obj.Get("MethodologyKey"))
    #     if act_meth_key == meth_name:
    #         test_meth = test_meth_obj
    #         break

    # Add MethodologyGroupCommand to the sequencer
    meth_group_cmd = ctor.Create(PKG + ".MethodologyGroupCommand", sequencer)
    sequencer.SetCollection("CommandList", [meth_group_cmd.GetObjectHandle()])
    key_value_json = meth_group_cmd.Get("KeyValueJson")
    assert key_value_json == ""

    cmd = ctor.Create(PKG + ".RunMethodologyTestCommand", sequencer)
    RunCmd.get_this_cmd = MagicMock(return_value=cmd)
    RunCmd.load_config = MagicMock()
    # TODO: set it up so we don't have to mock this function
    RunCmd.set_active_test_case = MagicMock()

    # Call run with all empty
    # res = RunCmd.run("", "", "", "", False)
    # assert not res
    # assert 'MethodologyJson does not conform to the schema' in cmd.Get("Status")
    # assert cmd.Get("OutputTestCaseKey") == ''
    # cmd.Set("Status", '')

    # Call run with invalid meth key
    # res = RunCmd.run("", "", "blah", "", False)
    # assert not res
    # assert 'MethodologyJson does not conform to the schema' in cmd.Get("Status")
    # assert cmd.Get("OutputTestCaseKey") == ''
    # cmd.Set("Status", '')

    # Call run with empty json
    # res = RunCmd.run("", "", meth_name, "", False)
    # assert not res
    # assert 'MethodologyJson does not conform to the schema' in cmd.Get("Status")
    # assert cmd.Get("OutputTestCaseKey") == ''
    # cmd.Set("Status", '')

    # Call run with invalid json
    # res = RunCmd.run("", "", meth_name, "invalid json", False)
    # assert not res
    # assert 'MethodologyJson does not conform to the schema' in cmd.Get("Status")
    # assert cmd.Get("OutputTestCaseKey") == ''
    # cmd.Set("Status", '')

    # Call the run function with valid meth key and json
    res = RunCmd.run("", "", meth_name, get_sample_2544_json_basic(), False)
    assert res
    assert cmd.Get("Status") == ''
    assert cmd.Get("OutputTestCaseKey") == meth_name + '-1'

    # The KeyValueJson should be populated after running the command
    key_value_json = meth_group_cmd.Get("KeyValueJson")
    assert key_value_json != ""
    err_str, key_value_dict = json_utils.load_json(key_value_json)
    assert err_str == ""
    assert key_value_dict is not None

    assert len(key_value_dict.items()) == 1
    assert key_value_dict["AddressStartValue"] == "1.1.1.1"

    # Clean up the fake installed methodology
    if os.path.exists(os.path.join(common_data_path,
                                   mgr_const.MM_TEST_METH_DIR,
                                   meth_name)):
        meth_man_utils.methodology_rmdir(meth_name)
def disabled_test_load_with_json(stc):
    plLogger = PLLogger.GetLogger("test_load_with_json")
    plLogger.LogInfo("begin")
    ctor = CScriptableCreator()
    project = CStcSystem.Instance().GetObject("Project")
    sequencer = CStcSystem.Instance().GetObject("Sequencer")
    hnd_reg = CHandleRegistry.Instance()

    cmd_name = "Ipv4NetworkProfileGroupCommand"
    pkg_name = "spirent.methodology."
    create_cmd = ctor.CreateCommand(pkg_name + cmd_name)

    insert_cmd = ctor.CreateCommand("SequencerInsertCommand")
    insert_cmd.SetCollection("CommandList", [create_cmd.GetObjectHandle()])
    insert_cmd.Execute()

    exposedConfig = ctor.Create("ExposedConfig", project)

    prop1 = ctor.Create("ExposedProperty", exposedConfig)
    UnitTestUtils.bind(prop1, create_cmd, pkg_name + cmd_name, "DeviceCount")
    prop2 = ctor.Create("ExposedProperty", exposedConfig)
    UnitTestUtils.bind(prop2, create_cmd, pkg_name + cmd_name, "RouterId")
    prop3 = ctor.Create("ExposedProperty", exposedConfig)
    UnitTestUtils.bind(prop3, create_cmd, pkg_name + cmd_name, "Ipv4Addr")

    test_name = "TestLoadWithJson"
    test_key = "JsonTestKey"
    # Delete the methodology we are about to create just in case
    # there was an error on a previous run.
    test_meth_obj = meth_man_utils.get_stm_methodology_from_key(test_key)

    if test_meth_obj:
        # Delete installed test methodology
        cmd = ctor.CreateCommand("spirent.methodology.manager."
                                 "DeleteMethodologyCommand")
        cmd.Set("StmMethodology", test_meth_obj.GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()

    # Publish as a methodology
    cmd = ctor.CreateCommand("spirent.methodology.manager.PublishMethodologyCommand")
    cmd.Set("MethodologyName", test_name)
    cmd.Set("MethodologyKey", test_key)
    cmd.Set("MinPortCount", "0")
    cmd.Execute()
    cmd.MarkDelete()

    # Reset Config
    cmd = ctor.CreateCommand("ResetConfigCommand")
    cmd.Set("Config", CStcSystem.Instance().GetObjectHandle())
    cmd.Execute()
    cmd.MarkDelete()

    sequencer = CStcSystem.Instance().GetObject("Sequencer")
    cmd_list = sequencer.GetObjects("Command")
    assert len(cmd_list) == 0

    meth_handle = UnitTestUtils.get_methodology_handle(test_name)
    assert meth_handle

    # TODO: Create a test case instead of running the methodology
    # itself.

    # Set up JSON input
    json_input = "{ \"ports\": {}, \"params\" : {\"" + prop1.Get("EPNameId") + "\" : 101, " + \
                 "\"" + prop2.Get("EPNameId") + "\" : \"188.0.0.5\", " + \
                 "\"" + prop3.Get("EPNameId") + "\" : \"172.0.17.5\" } }"
    active_test = meth_man_utils.get_active_test_case()
    assert active_test is None
    # Load the test methodology created earlier
    # Set the JSON input
    cmd = ctor.CreateCommand("spirent.methodology.manager."
                             "LoadTestMethodologyCommand")
    meth = meth_man_utils.get_stm_methodology_from_key(test_key)
    assert meth is not None
    cmd.Set("StmMethodology", meth.GetObjectHandle())
    cmd.Set("InputJson", json_input)
    cmd.Execute()

    # Check the command sequence
    cmd_hnd_list = sequencer.GetCollection("CommandList")
    assert len(cmd_hnd_list) == 1

    tlgc = hnd_reg.Find(cmd_hnd_list[0])
    assert tlgc is not None
    assert tlgc.IsTypeOf(pkg_name + "manager.MethodologyGroupCommand") is True

    cmd_hnd_list = tlgc.GetCollection("CommandList")
    assert len(cmd_hnd_list) == 1

    create_cmd = hnd_reg.Find(cmd_hnd_list[0])
    assert create_cmd.IsTypeOf(pkg_name + cmd_name) is True

    # Check defaults
    assert create_cmd.Get("DeviceCount") == 1
    assert create_cmd.Get("RouterId") == "192.0.0.1"
    assert create_cmd.Get("Ipv4Addr") == "192.85.1.3"

    # Execute a MethodologyGroupCommand
    tlgc2 = ctor.CreateCommand(pkg_name + "manager.MethodologyGroupCommand")
    tlgc2.Set("InputJson", tlgc.Get("InputJson"))
    tlgc2.Execute()
    tlgc2.MarkDelete()

    # Check the new defaults
    assert create_cmd.Get("DeviceCount") == 101
    assert create_cmd.Get("RouterId") == "188.0.0.5"
    assert create_cmd.Get("Ipv4Addr") == "172.0.17.5"

    # Clean up
    meth = meth_man_utils.get_stm_methodology_from_key(test_key)
    cmd = ctor.CreateCommand("spirent.methodology.manager."
                             "DeleteMethodologyCommand")
    cmd.Set("StmMethodology", meth.GetObjectHandle())
    cmd.Execute()
    cmd.MarkDelete()
    plLogger.LogInfo("end")
    def d_test_save_as_test_case_with_ports(self, stc):
        plLogger = PLLogger.GetLogger('methodology')
        plLogger.LogInfo("begin")
        # TODO: Fix this once the test case work is finished
        if True:
            plLogger.LogWarn("Fix me after test cases have been repaired.")
            return
        ctor = CScriptableCreator()
        meth_name = "TestMeth_SaveAsTestCase"

        stc_sys = CStcSystem.Instance()
        meth_man_pkg = "spirent.methodology.manager"

        # Defaults
        port_loc = "//10.14.16.20/2/1"
        mac_addr = "00:01:94:00:00:01"
        enable_vlan = False
        vlan_id = 100
        ipv4_addr = "192.85.1.3"

        plLogger.LogInfo("Create a test package")
        test_name, name_dict = TestSaveTestCase.make_fake_test_pkg(mac_addr,
                                                                   enable_vlan,
                                                                   vlan_id,
                                                                   ipv4_addr,
                                                                   port_loc,
                                                                   meth_name)
        # Build a port_map for validation (flip the name_dict)
        port_map = {}
        port_map[name_dict[port_loc]] = port_loc

        plLogger.LogInfo("Import the methodology " + test_name)
        # Import the test methodology (make available)
        cmd = ctor.CreateCommand(meth_man_pkg + ".ImportTestCommand")
        cmd.Set("fileName", test_name + ".stm")
        cmd.Execute()
        cmd.MarkDelete()

        plLogger.LogInfo("Verify that the TXML file exists after import")
        # Check the TXML file exists
        install_dir = os.path.join(stc_sys.GetApplicationCommonDataPath(),
                                   mgr_const.MM_TEST_METH_DIR)
        test_meth_dir = os.path.join(install_dir, meth_name)
        assert os.path.exists(test_meth_dir)
        test_case_dir = os.path.join(test_meth_dir, mgr_const.MM_TEST_CASE_SUBDIR)
        assert os.path.exists(test_case_dir)
        file_list = os.listdir(test_case_dir)
        assert len(file_list) == 1
        meta_file = file_list[0]
        assert meta_file == mgr_const.MM_META_FILE_NAME

        plLogger.LogInfo("Verify the TXML file contents haven't changed")
        # Check TXML defaults
        TestSaveTestCase.check_txml_values(meta_file,
                                           meta_man.TEST_INSTANCE_ORIGINAL,
                                           mac_addr,
                                           enable_vlan,
                                           vlan_id, ipv4_addr,
                                           port_map,
                                           meth_name)

        new_port_loc = "//10.14.16.27/2/1"
        new_mac = "00:01:95:CC:CC:0s"
        new_enable_vlan = "true"
        new_vlan = "541"
        new_ip = "182.0.0.1"

        # New port_map (for validation)
        new_port_map = {}
        new_port_map[name_dict[port_loc]] = new_port_loc

        # Create JSON string with new defaults
        json_input = "{\"ports\" : {\"" + name_dict[port_loc] + "\" : \"" + \
                     new_port_loc + "\"},\"params\" : {\"" + \
                     name_dict["MacAddr"] + "\" : \"" + new_mac + "\"," + \
                     " \"" + name_dict["EnableVlan"] + "\" : \"" + new_enable_vlan + "\"," + \
                     " \"" + name_dict["VlanId"] + "\" : \"" + new_vlan + "\"," + \
                     " \"" + name_dict["Ipv4Addr"] + "\" : \"" + new_ip + "\" }}"

        plLogger.LogInfo("Execute SaveTestCaseCommand with json_input: \n" + json_input)

        # Create a new "instance" of the testcase
        new_test_case = "MyNewTestCase"
        cmd = ctor.CreateCommand(meth_man_pkg + ".SaveTestCaseCommand")
        cmd.Set("TestMethodologyName", test_name)
        cmd.Set("InputJson", json_input)
        cmd.Set("TestCaseName", new_test_case)
        cmd.Execute()

        # Get the TXML file path
        new_txml_file_path = cmd.Get("TxmlFileName")
        new_txml_file = os.path.split(new_txml_file_path)[-1]
        cmd.MarkDelete()

        # Check the TXML file exists
        install_dir = os.path.join(stc_sys.GetApplicationCommonDataPath(),
                                   mgr_const.MM_TEST_METH_DIR)
        test_meth_dir = os.path.join(install_dir, meth_name)
        assert os.path.exists(test_meth_dir)
        test_case_dir = os.path.join(test_meth_dir, mgr_const.MM_TEST_CASE_SUBDIR)
        assert os.path.exists(test_case_dir)
        file_list = os.listdir(test_case_dir)
        assert len(file_list) > 1
        assert new_txml_file in file_list
        assert mgr_const.MM_META_FILE_NAME in file_list

        plLogger.LogInfo("Check the new saved file")
        TestSaveTestCase.check_txml_values(new_txml_file, new_test_case, new_mac,
                                           new_enable_vlan, new_vlan, new_ip,
                                           new_port_map, meth_name)
        plLogger.LogInfo("Verify the original hasn't changed")
        TestSaveTestCase.check_txml_values(mgr_const.MM_META_FILE_NAME,
                                           meta_man.TEST_INSTANCE_ORIGINAL, mac_addr,
                                           enable_vlan, vlan_id,
                                           ipv4_addr, port_map, meth_name)
        # Clean up anything that might be left from a previous run
        meth_handle = UnitTestUtils.get_methodology_handle(meth_name)
        UnitTestUtils.cleanup_methodology(meth_handle)
        plLogger.LogInfo("end")
    def d_test_save_test_case(self, stc):
        plLogger = PLLogger.GetLogger('methodology')
        plLogger.LogInfo("begin")
        # TODO: Fix this once the test case work is finished
        if True:
            plLogger.LogWarn("Fix me after test cases have been repaired.")
            return
        ctor = CScriptableCreator()
        meth_name = "TestMeth_SaveTestCase"

        stc_sys = CStcSystem.Instance()
        meth_man_pkg = "spirent.methodology.manager"

        # Defaults
        mac_addr = "00:01:94:00:00:01"
        enable_vlan = False
        vlan_id = 100
        ipv4_addr = "192.85.1.3"

        plLogger.LogInfo("Create and export the test")
        test_name, name_dict = TestSaveTestCase.make_fake_test_pkg(mac_addr,
                                                                   enable_vlan,
                                                                   vlan_id,
                                                                   ipv4_addr,
                                                                   "",
                                                                   meth_name)
        plLogger.LogInfo("name_dict: " + str(name_dict))
        plLogger.LogInfo("test_name: " + test_name)

        new_mac = "00:01:95:CC:CC:05"
        new_enable_vlan = "true"
        new_vlan = "541"
        new_ip = "182.0.0.1"

        # Create JSON string with new defaults
        json_input = "{ \"ports\" : {}, \"params\" : {\"" + name_dict["MacAddr"] + "\" : \"" + \
                     new_mac + "\"," + \
                     " \"" + name_dict["EnableVlan"] + "\" : \"" + new_enable_vlan + "\"," + \
                     " \"" + name_dict["VlanId"] + "\" : \"" + new_vlan + "\"," + \
                     " \"" + name_dict["Ipv4Addr"] + "\" : \"" + new_ip + "\" } }"

        plLogger.LogInfo("Execute save test with json_input: \n" + json_input)

        # Change the defaults in "original" TXML by setting TestCaseName to ""
        cmd = ctor.CreateCommand(meth_man_pkg + ".SaveTestCaseCommand")
        cmd.Set("TestMethodologyName", test_name)
        cmd.Set("InputJson", json_input)
        cmd.Set("TestCaseName", "")
        cmd.Execute()
        cmd.MarkDelete()

        # Check the TXML file exists
        install_dir = os.path.join(stc_sys.GetApplicationCommonDataPath(),
                                   mgr_const.MM_TEST_METH_DIR)
        test_meth_dir = os.path.join(install_dir, meth_name)
        assert os.path.exists(test_meth_dir)
        test_case_dir = os.path.join(test_meth_dir, mgr_const.MM_TEST_CASE_SUBDIR)
        assert os.path.exists(test_case_dir)
        file_list = os.listdir(test_case_dir)
        assert len(file_list) == 1
        meta_file = file_list[0]
        assert meta_file == mgr_const.MM_META_FILE_NAME

        # Check TXML defaults
        plLogger.LogInfo("check original txml has new values")
        TestSaveTestCase.check_txml_values(meta_file,
                                           meta_man.TEST_INSTANCE_ORIGINAL,
                                           new_mac,
                                           new_enable_vlan,
                                           new_vlan,
                                           new_ip,
                                           None,
                                           meth_name)
        # Clean up anything that might be left
        meth_handle = UnitTestUtils.get_methodology_handle(meth_name)
        UnitTestUtils.cleanup_methodology(meth_handle)
        plLogger.LogInfo("end")
def test_delete_with_active_testcase(stc):
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogInfo("test_delete_active_test.begin")

    ctor = CScriptableCreator()
    hnd_reg = CHandleRegistry.Instance()

    meth_key = "UNITTEST_DEL"
    UnitTestUtils.create_fake_installed_test_meth(meth_key, [])
    UnitTestUtils.add_fake_test_case(meth_key, [], meth_key + "-1")

    # Update the BLL objects
    meth_man_utils.build_test_methodology_manager(use_txml=True)
    meth_man = meth_man_utils.get_meth_manager()

    meth_handle = UnitTestUtils.get_methodology_handle(meth_key)
    assert meth_handle
    meth_obj = hnd_reg.Find(meth_handle)
    assert meth_obj is not None
    meth_path = meth_obj.Get("Path")
    assert os.path.exists(meth_path)

    tc_obj = meth_obj.GetObject("StmTestCase")
    assert tc_obj
    tc_path = tc_obj.Get("Path")
    assert os.path.exists(tc_path)

    # Set up the test case to look as if it were active
    # Set the active test case
    meth_man_utils.set_active_test_case(tc_obj)

    # Create the results object and set its status
    res_obj = ctor.Create("StmTestResult", tc_obj)
    status_dict = {"execStatus": "running",
                   "verdict": "created",
                   "verdictExplanation": "Not Defined"}
    res_obj.Set("Status", json.dumps(status_dict))

    # Try to delete the methodology
    cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
    cmd.Set("StmMethodology", meth_obj.GetObjectHandle())
    cmd.Execute()
    assert cmd.Get("PassFailState") == "FAILED"
    cmd.MarkDelete()

    # Check the bll objects
    found_hnd = False
    for meth in meth_man.GetObjects("StmMethodology"):
        if meth.GetObjectHandle() == meth_handle:
            found_hnd = True
            break
    assert found_hnd

    # Check the active test case
    assert meth_man_utils.get_active_test_case().GetObjectHandle() == \
        tc_obj.GetObjectHandle()

    # Check the path
    assert os.path.exists(tc_path)
    assert os.path.exists(meth_path)

    # Set the testcase to completed
    status_dict = {"execStatus": "completed",
                   "verdict": "created",
                   "verdictExplanation": "Not Defined"}
    res_obj.Set("Status", json.dumps(status_dict))

    # Try to delete the methodology
    cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
    cmd.Set("StmMethodology", meth_obj.GetObjectHandle())
    cmd.Execute()
    assert cmd.Get("PassFailState") == "PASSED"
    cmd.MarkDelete()

    # Check the bll objects
    found_hnd = False
    for meth in meth_man.GetObjects("StmMethodology"):
        if meth.GetObjectHandle() == meth_handle:
            found_hnd = True
            break
    assert not found_hnd

    # Check the active test case
    assert meth_man_utils.get_active_test_case() is None

    # Check the path
    assert not os.path.exists(meth_path)
    assert not os.path.exists(tc_path)

    stc_sys = CStcSystem.Instance()
    common_data_path = stc_sys.GetApplicationCommonDataPath()
    install_dir = os.path.join(common_data_path, mgr_const.MM_TEST_METH_DIR)
    test_meth_dir = os.path.join(install_dir, meth_key)

    assert os.path.exists(test_meth_dir) is False
    plLogger.LogInfo("test_delete_active_test.end")
    def disabled_test_export_import_load_loose_ports(self, stc):
        plLogger = PLLogger.GetLogger('methodology')
        plLogger.LogInfo("begin.test_export_import_load_loose_ports")
        ctor = CScriptableCreator()
        stc_sys = CStcSystem.Instance()
        project = stc_sys.GetObject("Project")

        port = ctor.Create("Port", project)
        etcu = ctor.Create("EthernetCopper", port)
        port.AddObject(etcu, RelationType("ActivePhy"))
        port.Set("Location", "//10.14.18.4/1/1")
        port_id = get_unique_property_id(port, "Location")

        stak_cmd_name = "spirent.methodology.Ipv4NetworkProfileGroupCommand"
        stak_cmd = ctor.CreateCommand(stak_cmd_name)
        stak_cmd.SetCollection("PortList", [port.GetObjectHandle()])

        insert_cmd = ctor.CreateCommand("SequencerInsertCommand")
        insert_cmd.SetCollection("CommandList", [stak_cmd.GetObjectHandle()])
        insert_cmd.Execute()

        # Expose properties
        exposed_config = ctor.Create("ExposedConfig", project)

        # MacAddr
        mac_prop = ctor.Create("ExposedProperty", exposed_config)
        mac_prop_id = UnitTestUtils.bind(mac_prop, stak_cmd, stak_cmd_name, "MacAddr")

        # EnableVlan
        enable_prop = ctor.Create("ExposedProperty", exposed_config)
        enable_prop_id = UnitTestUtils.bind(enable_prop, stak_cmd, stak_cmd_name, "EnableVlan")

        # VlanId
        vlan_prop = ctor.Create("ExposedProperty", exposed_config)
        vlan_prop_id = UnitTestUtils.bind(vlan_prop, stak_cmd, stak_cmd_name, "VlanId")

        test_name = "TestLoosePorts"
        # Delete the methodology we are about to create just in case
        # there was an error on a previous run.
        test_meth_obj = meth_man_utils.get_stm_methodology_from_key(meth_key)

        if test_meth_obj:
            # Delete installed test methodology
            cmd = ctor.CreateCommand("spirent.methodology.manager."
                                     "DeleteMethodologyCommand")
            cmd.Set("StmMethodology", test_meth_obj.GetObjectHandle())
            cmd.Execute()
            cmd.MarkDelete()

        # Publish methodology
        cmd = ctor.CreateCommand(PKG + ".PublishMethodologyCommand")
        cmd.Set("MethodologyName", test_name)
        cmd.SetCollection("FeatureIdList", ["Feature1"])
        cmd.Execute()
        cmd.MarkDelete()

        # Reset Config
        cmd = ctor.CreateCommand("ResetConfigCommand")
        cmd.Set("Config", CStcSystem.Instance().GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()

        # Load the test methodology created earlier
        # Use mock to prevent the AttachPortsCommand in the LoadTestMethodologyCommand
        # from being executed.
        LoadTestMethodologyCommand.attach_ports = MagicMock()

        # JSON Input
        json_input = "{\"ports\" : {\"" + port_id + "\" : \"//10.14.16.27/2/2\"}, " + \
                     "\"params\" : {\"" + mac_prop_id + "\" : \"55:55:55:55:55:55\", " + \
                     "\"" + enable_prop_id + "\" : \"TRUE\", \"" + vlan_prop_id + "\" : 555} }"

        plLogger.LogInfo("json_input: " + json_input)

        # Call run directly
        # Note that 0 is an invalid STC handle.  Asking the HandleRegistry for
        # it will result in None.
        # Last arg "1" is to turn on TIE check. "0" will turn off the check
        meth = meth_man_utils.get_stm_methodology_from_key(meth_key)
        assert meth is not None
        LoadTestMethodologyCommand.run(meth.GetObjectHandle(), 0, json_input, 1)

        # Check the loaded objects
        project = CStcSystem.Instance().GetObject("Project")
        port_list = project.GetObjects("Port")
        assert len(port_list) == 1

        # Check the port location has been reconfigured properly
        assert port_list[0].Get("Location") == "//10.14.16.27/2/2"

        # Note that one of the exposed properties is the port location
        # that is tacked on automatically
        exp_conf = project.GetObject("ExposedConfig")
        exp_prop_list = exp_conf.GetObjects("ExposedProperty")
        assert len(exp_prop_list) == 4

        found_location_prop = False
        for exp_prop in exp_prop_list:
            if exp_prop.Get("EPNameId") == port_id:
                found_location_prop = True
        assert found_location_prop is True

        # Clean up
        meth_man_utils.remove_active_test_relation()
        meth = meth_man_utils.get_stm_methodology_from_key(meth_key)
        cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
        cmd.Set("StmMethodology", meth.GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()
        plLogger.LogInfo("end.test_export_import_load_loose_ports")
    def test_GetAllTestMethodologiesCommand(self, stc):
        ctor = CScriptableCreator()
        hnd_reg = CHandleRegistry.Instance()
        plLogger = PLLogger.GetLogger('methodology')
        plLogger.LogInfo("begin.test_GetAllTestMethodologiesCommand")

        test_pkg1 = "UNITTEST_GETALL1"
        test_pkg2 = "UNITTEST_GETALL2"
        test_pkg3 = "UNITTEST_GETALL3"
        UnitTestUtils.create_fake_installed_test_meth(test_pkg1, [])
        UnitTestUtils.create_fake_installed_test_meth(test_pkg2, [])
        UnitTestUtils.create_fake_installed_test_meth(test_pkg3, [])

        UnitTestUtils.add_fake_test_case(test_pkg1, [], "UNITTEST_GETALL1-1")
        UnitTestUtils.add_fake_test_case(test_pkg1, [], "UNITTEST_GETALL1-2")
        UnitTestUtils.add_fake_test_case(test_pkg1, [], "UNITTEST_GETALL1-3")

        UnitTestUtils.add_fake_test_case(test_pkg3, [], "UNITTEST_GETALL3-1")

        # Manually update TestMethodologyManager
        cmd = ctor.CreateCommand(PKG + ".UpdateTestMethodologyManagerCommand")
        cmd.Execute()
        cmd.MarkDelete()

        # Get all installed test methodologies
        list_cmd = ctor.CreateCommand(PKG + ".GetAllTestMethodologiesCommand")
        list_cmd.Execute()
        test_meth_handle_list = list_cmd.GetCollection("StmMethodologyList")
        list_cmd.MarkDelete()

        meth_key_list = []
        meth_obj1 = None
        meth_obj2 = None
        meth_obj3 = None
        for meth_handle in test_meth_handle_list:
            meth_obj = hnd_reg.Find(meth_handle)
            assert meth_obj is not None
            meth_key = meth_obj.Get("MethodologyKey")
            if meth_key == test_pkg1:
                meth_obj1 = meth_obj
            elif meth_key == test_pkg2:
                meth_obj2 = meth_obj
            elif meth_key == test_pkg3:
                meth_obj3 = meth_obj
        assert meth_obj1 is not None
        assert meth_obj2 is not None
        assert meth_obj3 is not None

        cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
        cmd.Set("StmMethodology", meth_obj1.GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()
        cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
        cmd.Set("StmMethodology", meth_obj2.GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()
        cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
        cmd.Set("StmMethodology", meth_obj3.GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()

        # Manually update TestMethodologyManager
        cmd = ctor.CreateCommand(PKG + ".UpdateTestMethodologyManagerCommand")
        cmd.Execute()
        cmd.MarkDelete()

        # Get all installed test methodologies
        list_cmd = ctor.CreateCommand(PKG + ".GetAllTestMethodologiesCommand")
        list_cmd.Execute()
        test_meth_handle_list = list_cmd.GetCollection("StmMethodologyList")
        list_cmd.MarkDelete()

        meth_key_list = []
        for meth_handle in test_meth_handle_list:
            meth_obj = hnd_reg.Find(meth_handle)
            meth_key_list.append(meth_obj.Get("MethodologyKey"))
        assert test_pkg1 not in meth_key_list
        assert test_pkg2 not in meth_key_list
        assert test_pkg3 not in meth_key_list
        list_cmd.MarkDelete()
        plLogger.LogInfo("end.test_GetAllTestMethodologiesCommand")
    def disabled_test_RemoveMethodologyGroupCommand(self, stc):
        plLogger = PLLogger.GetLogger('methodology')
        plLogger.LogInfo("begin.test_RemoveMethodologyGroupCommand")
        ctor = CScriptableCreator()
        project = CStcSystem.Instance().GetObject("Project")
        sequencer = CStcSystem.Instance().GetObject("Sequencer")

        cmd_name = "ArpNdStartCommand"
        stak_cmd_name = "spirent.methodology.Ipv4NetworkProfileGroupCommand"
        arp_cmd = ctor.CreateCommand(cmd_name)
        stak_cmd = ctor.CreateCommand(stak_cmd_name)
        insert_cmd = ctor.CreateCommand("SequencerInsertCommand")
        insert_cmd.SetCollection("CommandList", [arp_cmd.GetObjectHandle(),
                                                 stak_cmd.GetObjectHandle()])
        insert_cmd.Execute()

        exposedConfig = ctor.Create("ExposedConfig", project)

        prop1 = ctor.Create("ExposedProperty", exposedConfig)
        UnitTestUtils.bind(prop1, arp_cmd, cmd_name, "ArpNdOption")

        prop4 = ctor.Create("ExposedProperty", exposedConfig)
        UnitTestUtils.bind(prop4, stak_cmd, stak_cmd_name, "DeviceCount")

        test_name = "TestMethRemoveGroup"
        meth_key = "UNITTEST_RM_GRP"
        # Delete the methodology we are about to create just in case
        # there was an error on a previous run.
        test_meth_obj = meth_man_utils.get_stm_methodology_from_key(meth_key)

        if test_meth_obj:
            # Delete installed test methodology
            cmd = ctor.CreateCommand("spirent.methodology.manager."
                                     "DeleteMethodologyCommand")
            cmd.Set("StmMethodology", test_meth_obj.GetObjectHandle())
            cmd.Execute()
            cmd.MarkDelete()

        # Publish methodology
        cmd = ctor.CreateCommand(PKG + ".PublishMethodologyCommand")
        cmd.Set("MethodologyName", test_name)
        cmd.Set("MethodologyKey", meth_key)
        cmd.Set("MinPortCount", "0")
        cmd.SetCollection("FeatureIdList", ["Feature1"])
        cmd.Execute()
        cmd.MarkDelete()

        # Reset Config
        cmd = ctor.CreateCommand("ResetConfigCommand")
        cmd.Set("Config", CStcSystem.Instance().GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()

        sequencer = CStcSystem.Instance().GetObject("Sequencer")
        cmd_list = sequencer.GetObjects("Command")
        assert len(cmd_list) == 0

        meth_handle = UnitTestUtils.get_methodology_handle(meth_key)
        assert meth_handle

        # Load the test methodology created earlier
        cmd = ctor.CreateCommand(PKG + ".LoadTestMethodologyCommand")
        meth = meth_man_utils.get_stm_methodology_from_key(meth_key)
        cmd.Set("StmMethodology", meth.GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()

        cmd_list = sequencer.GetObjects("Command")
        assert len(cmd_list) == 3

        # Strip the MethodologyGroupCommand and make the test methodology editable again
        cmd = ctor.CreateCommand(PKG + ".RemoveMethodologyGroupCommand")
        cmd.Execute()
        cmd.MarkDelete()

        # Check the sequence
        for cmd in sequencer.GetObjects("Command"):
            assert cmd.IsTypeOf(PKG + ".MethodologyGroupCommand") is False
            scp = cmd.GetObject("SequenceableCommandProperties",
                                RelationType("SequenceableProperties"))
            assert scp is not None
            assert scp.Get("AllowDelete") is True
            assert scp.Get("AllowMove") is True
            assert scp.Get("AllowUngroup") is True
            assert scp.Get("AllowDisable") is True
            assert scp.Get("ShowEditor") is True

        # Clean up
        meth_man_utils.remove_active_test_relation()
        meth = meth_man_utils.get_stm_methodology_from_key(meth_key)
        cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
        cmd.Set("StmMethodology", meth.GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()
        plLogger.LogInfo("end.test_RemoveMethodologyGroupCommand")
    def d_test_publish_methodology(self, stc):
        plLogger = PLLogger.GetLogger('methodology')
        plLogger.LogInfo("test_publish_methodology.begin")
        test_name = "UnitTestMethPublishTest"
        meth_key = "UNITTEST_PUB"
        test_label_list = ["UnitTest", "Arp", "Ipv4"]
        min_num_ports = "2"
        max_num_ports = "4"
        port_speed_list = ["40", "100"]
        PORT1_LOCATION = "//10.14.16.20/2/1"
        PORT2_LOCATION = "//10.14.16.20/2/2"

        ctor = CScriptableCreator()
        project = CStcSystem.Instance().GetObject("Project")
        sequencer = CStcSystem.Instance().GetObject("Sequencer")

        # Delete the methodology we are about to create just in case
        # there was an error on a previous run.
        test_meth_obj = meth_man_utils.get_stm_methodology_from_key(meth_key)

        if test_meth_obj:
            # Delete installed test methodology
            cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
            cmd.Set("StmMethodology", test_meth_obj.GetObjectHandle())
            cmd.Execute()
            cmd.MarkDelete()

        # Clean up empty folders (if existing)
        meth_man_utils.methodology_rmdir(meth_key)

        # Create Untagged ports
        port1 = ctor.Create("Port", project)
        port1.Set("Location", PORT1_LOCATION)
        port2 = ctor.Create("Port", project)
        port2.Set("Location", PORT2_LOCATION)

        cmd_name = "ArpNdStartCommand"
        arp_cmd = ctor.CreateCommand(cmd_name)
        stak_cmd_name = "Ipv4NetworkProfileGroupCommand"
        stak_cmd = ctor.CreateCommand(PKG_BASE + ".Ipv4NetworkProfileGroup")

        insert_cmd = ctor.CreateCommand("SequencerInsertCommand")
        insert_cmd.SetCollection("CommandList", [arp_cmd.GetObjectHandle(),
                                                 stak_cmd.GetObjectHandle()])
        insert_cmd.Execute()

        exposedConfig = ctor.Create("ExposedConfig", project)

        prop1 = ctor.Create("ExposedProperty", exposedConfig)
        UnitTestUtils.bind(prop1, arp_cmd, cmd_name, "ArpNdOption")

        prop2 = ctor.Create("ExposedProperty", exposedConfig)
        UnitTestUtils.bind(prop2, arp_cmd, cmd_name, "ForceArp")

        prop3 = ctor.Create("ExposedProperty", exposedConfig)
        UnitTestUtils.bind(prop3, arp_cmd, cmd_name, "WaitForArpToFinish")

        prop4 = ctor.Create("ExposedProperty", exposedConfig)
        UnitTestUtils.bind(prop4, stak_cmd, PKG_BASE + "." +
                           stak_cmd_name, "DeviceCount")

        obj = prop1.GetObject("Scriptable", RelationType("ScriptableExposedProperty"))
        assert obj.GetObjectHandle() == arp_cmd.GetObjectHandle()

        cmd = ctor.CreateCommand(PKG + ".PublishMethodologyCommand")
        cmd.Set("MethodologyName", test_name)
        cmd.Set("MethodologyKey", meth_key)
        cmd.SetCollection("MethodologyLabelList", test_label_list)
        cmd.Set("MinPortCount", min_num_ports)
        cmd.Set("MaxPortCount", max_num_ports)
        cmd.SetCollection("PortSpeedList", port_speed_list)
        cmd.SetCollection("FeatureIdList", ["Feature1"])
        cmd.Set("EditableParams", get_tagged_xml())
        cmd.Execute()
        cmd.MarkDelete()

        sequencer = CStcSystem.Instance().GetObject("Sequencer")

        # Check the sequencer
        assert sequencer.Get("ErrorHandler") == "STOP_ON_ERROR"

        # Check the command sequencer
        cmd_list = sequencer.GetObjects("Command")
        assert len(cmd_list) == 3

        sp_list = sequencer.GetObjects("SequenceableCommandProperties")
        assert len(sp_list) > 0

        for cmd in cmd_list:
            if cmd.IsTypeOf(PKG + ".MethodologyGroupCommand"):
                found_tlgc = True
            else:
                sp = cmd.GetObject("SequenceableCommandProperties",
                                   RelationType("SequenceableProperties"))
                assert sp is not None
                assert sp.Get("AllowDelete") is False
                assert sp.Get("AllowMove") is False
                assert sp.Get("AllowUngroup") is False
                assert sp.Get("AllowDisable") is False
                assert sp.Get("ShowEditor") is False
        assert found_tlgc is True

        test_meth_obj = meth_man_utils.get_stm_methodology_from_key(meth_key)
        assert test_meth_obj

        # Delete installed test methodology
        cmd = ctor.CreateCommand(PKG + ".DeleteMethodologyCommand")
        cmd.Set("StmMethodology", test_meth_obj.GetObjectHandle())
        cmd.Execute()
        cmd.MarkDelete()

        plLogger.LogInfo("test_publish_methodology.end")
def test_UpdateMethodologyManagerCommand(stc):
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogInfo("test_UpdateMethodologyManagerCommand")

    test_pkg1 = "test_meth_1"
    test_pkg2 = "test_meth_2"
    test_pkg3 = "test_meth_3"
    label_list1 = ["benchmarking", "BGP", "CSMP"]
    label_list2 = ["OTV", "DHCPv6"]
    label_list3 = []

    # Clean up empty folders (if existing)
    meth_man_utils.methodology_rmdir(test_pkg1)
    meth_man_utils.methodology_rmdir(test_pkg2)
    meth_man_utils.methodology_rmdir(test_pkg3)

    UnitTestUtils.create_fake_installed_test_meth(test_pkg1, label_list1)
    UnitTestUtils.create_fake_installed_test_meth(test_pkg2, label_list2)
    UnitTestUtils.create_fake_installed_test_meth(test_pkg3, label_list3)

    # TODO: Uncomment the test case stuff once it's fixed.
    # UnitTestUtils.add_fake_test_case(test_pkg1, "test_case_1")
    # UnitTestUtils.add_fake_test_case(test_pkg1, "test_case_2")
    # UnitTestUtils.add_fake_test_case(test_pkg1, "test_case_3")

    # UnitTestUtils.add_fake_test_case(test_pkg3, "test_case_1")

    # Initialize the methodology manager by calling update
    cmd = ctor.CreateCommand(PKG_MGR + ".UpdateTestMethodologyManagerCommand")
    cmd.Execute()
    cmd.MarkDelete()

    meth_manager = meth_man_utils.get_meth_manager()

    test_meth_obj_list = meth_manager.GetObjects("StmMethodology")
    assert len(test_meth_obj_list) > 0

    meth1 = None
    meth2 = None
    meth3 = None
    for test_meth_obj in test_meth_obj_list:
        meth_key = test_meth_obj.Get("MethodologyKey")
        plLogger.LogInfo("meth_name: " + test_meth_obj.Get("Name"))
        plLogger.LogInfo("meth_key: " + test_meth_obj.Get("MethodologyKey"))
        # test_case_list = []
        label_list = []
        if meth_key == test_pkg1:
            meth1 = test_meth_obj
            # test_case_list = ["test_case_1", "test_case_2",
            #                   "test_case_3", "original"]
            label_list = label_list1
        elif meth_key == test_pkg2:
            meth2 = test_meth_obj
            # test_case_list = ["original"]
            label_list = label_list2
        elif meth_key == test_pkg3:
            meth3 = test_meth_obj
            # test_case_list = ["original", "test_case_1"]
            label_list = label_list3
        else:
            # No need to check this...anything here could be
            # from another unit test or other installed methodologies.
            continue

        # Check the path
        install_dir = os.path.join(stc_sys.GetApplicationCommonDataPath(),
                                   mgr_const.MM_TEST_METH_DIR)
        exp_path = os.path.join(install_dir, meth_key)
        assert test_meth_obj.Get("Path") == os.path.normpath(exp_path)

        # Check the test cases
        # if len(test_case_list) > 0:
        #     test_case_obj_list = test_meth_obj.GetObjects("StmTestCase")
        #     for test_case_obj in test_case_obj_list:
        #         test_case_name = test_case_obj.Get("TestCaseName")
        #         assert test_case_name in test_case_list
        #         test_case_list.remove(test_case_name)
        #     assert len(test_case_list) == 0

        # Check the labels
        exp_label_list = test_meth_obj.GetCollection("LabelList")
        plLogger.LogInfo("exp_label_list: " + str(exp_label_list))
        plLogger.LogInfo("act_label_list: " + str(label_list))
        assert len(label_list) == len(exp_label_list)
        if len(exp_label_list) > 0:
            for label in label_list:
                plLogger.LogInfo("  -> looking for label: " + str(label))
                assert label in exp_label_list

    assert meth1 is not None
    assert meth2 is not None
    assert meth3 is not None

    # Clean up
    cmd = ctor.CreateCommand(PKG_MGR + ".DeleteMethodologyCommand")
    cmd.Set("StmMethodology", meth1.GetObjectHandle())
    cmd.Execute()
    cmd = ctor.CreateCommand(PKG_MGR + ".DeleteMethodologyCommand")
    cmd.Set("StmMethodology", meth2.GetObjectHandle())
    cmd.Execute()
    cmd = ctor.CreateCommand(PKG_MGR + ".DeleteMethodologyCommand")
    cmd.Set("StmMethodology", meth3.GetObjectHandle())
    cmd.Execute()
def test_import_save_delete_bll_object_update(stc):
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogInfo("test_import_save_delete_bll_object_update.begin")
    meth_name = "TestMethManUtils"
    meth_key = "UNITTEST_METHMANUTILS"
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")

    # Clean up empty folder (if existing)
    meth_man_utils.methodology_rmdir(meth_key)

    stak_cmd_name = PKG + ".LoadTemplateCommand"
    stak_cmd = ctor.CreateCommand(stak_cmd_name)

    insert_cmd = ctor.CreateCommand("SequencerInsertCommand")
    insert_cmd.SetCollection("CommandList", [stak_cmd.GetObjectHandle()])
    insert_cmd.Execute()

    exposedConfig = ctor.Create("ExposedConfig", project)

    prop1 = ctor.Create("ExposedProperty", exposedConfig)
    UnitTestUtils.bind(prop1, stak_cmd, stak_cmd_name, "CopiesPerParent")

    # Export to a distributable zip file
    cmd = ctor.CreateCommand(PKG_MGR + ".PublishMethodologyCommand")
    cmd.Set("MethodologyName", meth_name)
    cmd.Set("MethodologyKey", meth_key)
    cmd.Set("MinPortCount", "0")
    cmd.Execute()
    cmd.MarkDelete()

    # Reset Config
    cmd = ctor.CreateCommand("ResetConfigCommand")
    cmd.Set("Config", CStcSystem.Instance().GetObjectHandle())
    cmd.Execute()
    cmd.MarkDelete()

    # Update the Methodology Manager
    cmd = ctor.CreateCommand(PKG_MGR + ".UpdateTestMethodologyManagerCommand")
    cmd.Execute()
    cmd.MarkDelete()

    meth_mgr = CStcSystem.Instance().GetObject("StmMethodologyManager")
    assert meth_mgr is not None
    meth_obj = None
    meth_obj_list = meth_mgr.GetObjects("StmMethodology")
    for obj in meth_obj_list:
        if obj.Get("MethodologyKey") == meth_key:
            meth_obj = obj
            break
    assert meth_obj is not None
    assert 0 == len(meth_obj.GetObjects("StmTestCase"))

    # Add a test case
    new_test_case = "MyNewTestCase"
    cmd = ctor.CreateCommand(PKG_MGR + ".CreateTestCaseCommand")
    cmd.Set("TestCaseSrc", meth_obj.GetObjectHandle())
    cmd.Set("TestCaseName", new_test_case)
    cmd.Execute()
    cmd.MarkDelete()

    # Check object update
    test_case_list = meth_obj.GetObjects("StmTestCase")
    assert len(test_case_list) == 1
    found_tc1 = False
    tc_key = None
    for test_case in test_case_list:
        tc_name = test_case.Get("Name")
        if tc_name == new_test_case:
            found_tc1 = True
            tc_key = test_case.Get("TestCaseKey")
    assert found_tc1
    assert tc_key == meth_key + "-1"

    # Check the path
    tc1_path = meth_man_utils.get_test_case_dir(meth_key, tc_key)
    assert os.path.exists(tc1_path)

    # Add a test case
    new_test_case2 = "MyNewTestCase2"
    cmd = ctor.CreateCommand(PKG_MGR + ".CreateTestCaseCommand")
    cmd.Set("TestCaseSrc", meth_obj.GetObjectHandle())
    cmd.Set("TestCaseName", new_test_case2)
    cmd.Execute()
    cmd.MarkDelete()

    # Check object update
    test_case_list = meth_obj.GetObjects("StmTestCase")
    assert len(test_case_list) == 2
    found_tc2 = False
    tc_key = None
    for test_case in test_case_list:
        tc_name = test_case.Get("Name")
        if tc_name == new_test_case2:
            found_tc2 = True
            tc_key = test_case.Get("TestCaseKey")
    assert found_tc2
    assert tc_key == meth_key + "-2"

    # Check the path
    tc1_path = meth_man_utils.get_test_case_dir(meth_key, tc_key)
    assert os.path.exists(tc1_path)

    # Clean up
    cmd = ctor.CreateCommand(PKG_MGR + ".DeleteMethodologyCommand")
    cmd.Set("StmMethodology", meth_obj.GetObjectHandle())
    cmd.Execute()

    found_meth = meth_man_utils.get_stm_methodology_from_key(meth_key)
    assert found_meth is None

    # Test empty meth key
    assert meth_man_utils.get_stm_methodology_from_key("") is None
def test_find_file_across_common_paths_no_active_meth(stc):
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogInfo("test_find_file_across_common_paths_no_active_meth")

    meth_key = "UT_FIND_FILES_TEST_ACTIVE"

    # Clean up empty folders (if existing)
    meth_man_utils.methodology_rmdir(meth_key)

    # Can't use unit_test_utils here to create fake methodologies
    # due to the custom requirements of this particular methodology.
    install_dir = meth_man_utils.get_methodology_home_dir()
    test_meth_dir = os.path.join(install_dir, meth_key)
    assert not os.path.exists(test_meth_dir)
    os.makedirs(test_meth_dir)

    # Add a fake sequence file
    seq_file = os.path.join(test_meth_dir, mgr_const.MM_SEQUENCER_FILE_NAME)
    f = open(seq_file, "w")
    f.write("<?xml version=\"1.0\" encoding=\"windows-1252\"?>")
    f.close()

    # Add a fake TXML file
    meta_file = os.path.join(test_meth_dir, mgr_const.MM_META_FILE_NAME)
    f = open(meta_file, "w")
    data = UnitTestUtils.gen_test_info_header("unit test meth disp name",
                                              meth_key,
                                              "unit test meth test case",
                                              "")
    data = data + UnitTestUtils.UTU_FOOTER
    f.write(data)
    f.close()

    # Add a fake data file
    data_file_name = "fake_data_file.txt"
    data_file_path = os.path.join(test_meth_dir, data_file_name)
    f = open(data_file_path, "w")
    f.write("Unit Test Data File (end)")
    f.close()

    # Initialize the methodology manager by calling update
    cmd = ctor.CreateCommand(PKG_MGR +
                             ".UpdateTestMethodologyManagerCommand")
    cmd.Execute()
    cmd.MarkDelete()

    meth_manager = meth_man_utils.get_meth_manager()

    test_meth_obj_list = meth_manager.GetObjects("StmMethodology")
    assert len(test_meth_obj_list) > 0

    test_meth = None
    for test_meth_obj in test_meth_obj_list:
        act_meth_key = test_meth_obj.Get("MethodologyKey")
        plLogger.LogInfo("meth_name: " + test_meth_obj.Get("Name"))
        plLogger.LogInfo("meth_key: " + test_meth_obj.Get("MethodologyKey"))
        if act_meth_key == meth_key:
            test_meth = test_meth_obj
            break

    assert test_meth is not None

    meth_key = test_meth.Get("MethodologyKey")
    plLogger.LogInfo("meth_name: " + test_meth_obj.Get("Name"))
    plLogger.LogInfo("meth_key: " + test_meth_obj.Get("MethodologyKey"))

    # Check the path
    install_dir = os.path.join(stc_sys.GetApplicationCommonDataPath(),
                               mgr_const.MM_TEST_METH_DIR)
    exp_path = os.path.join(install_dir, meth_key)
    assert test_meth.Get("Path") == os.path.normpath(exp_path)

    # Test the find_file_across_common_paths function
    # (no active, not loaded from file)
    active_tc = meth_manager.GetObject("StmTestCase",
                                       RelationType("ActiveStmTestCase"))
    assert active_tc is None

    ret_val = meth_man_utils.find_file_across_common_paths(data_file_name)
    assert ret_val == ""

    # Test the find_file_across_common_paths function
    # (no active, loaded from file)
    project.Set("ConfigurationFileName", seq_file)
    ret_val = meth_man_utils.find_file_across_common_paths(data_file_name)
    assert ret_val == os.path.normpath(data_file_path)

    # Clean up
    cmd = ctor.CreateCommand(PKG_MGR + ".DeleteMethodologyCommand")
    cmd.Set("StmMethodology", test_meth.GetObjectHandle())
    cmd.Execute()