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 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_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")