def run(TagNameList, ObjectList, CurrVal, Iteration,
        TagList, IgnoreEmptyTags):
    if CurrVal != '':
        hdl_list = [int(s) for s in CurrVal.split(',')]
    else:
        hdl_list = []
    if len(TagNameList) < len(hdl_list):
        raise RuntimeError('Not enough tag names specified, expected at ' +
                           'least' + str(len(hdl_list)) + ' elements')
    hnd_reg = CHandleRegistry.Instance()
    # Before processing, remove any objects from tags
    for tag in TagNameList:
        tag_obj = tag_utils.get_tag_object(tag)
        # Clear anything the tag points to
        exist_list = tag_utils.get_tagged_objects([tag_obj])
        for rem_obj in exist_list:
            rem_obj.RemoveObject(tag_obj, RelationType('UserTag'))
    for tag, hdl in zip(TagNameList, hdl_list):
        tag_obj = tag_utils.get_tag_object(tag)
        obj = hnd_reg.Find(hdl)
        # Is this an error if we are getting an invalid handle?
        if obj is None:
            continue
        # Add the object to the tag (not using util, since it operates on str)
        obj.AddObject(tag_obj, RelationType('UserTag'))
    return True
def test_generate_tagged_ports_empty_port_list(stc):
    project = CStcSystem.Instance().GetObject('Project')
    ctor = CScriptableCreator()
    left_tag = tag_utils.get_tag_object('Left_Port_Group')
    right_tag = tag_utils.get_tag_object('Right_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'))
    ep = ctor.Create('ExposedProperty', ep_cfg)
    ep.Set('EPNameId', 'RightPortGroup')
    ep.Set('EPClassId', 'tag')
    ep.Set('EPPropertyId', 'scriptable.name')
    ep.AddObject(right_tag, RelationType('ScriptableExposedProperty'))

    # The sample didn't have everything, so this unit test will take the
    # minimum needed
    input_dict = {
        "port_groups": [
            {
                "prop_id": "LeftPortGroup",
                "name": "Left"
            },
            {
                "prop_id": "RightPortGroup",
                "name": "Right"
            }
        ],
    }

    port_hnd_list, offline, err_str = RunCmd.generate_tagged_ports(input_dict)
    assert port_hnd_list == []
    assert err_str == "Port group {} has empty port list"
def test_generate_tagged_ports_no_port_groups(stc):
    project = CStcSystem.Instance().GetObject('Project')
    ctor = CScriptableCreator()
    left_tag = tag_utils.get_tag_object('Left_Port_Group')
    right_tag = tag_utils.get_tag_object('Right_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'))
    ep = ctor.Create('ExposedProperty', ep_cfg)
    ep.Set('EPNameId', 'RightPortGroup')
    ep.Set('EPClassId', 'tag')
    ep.Set('EPPropertyId', 'scriptable.name')
    ep.AddObject(right_tag, RelationType('ScriptableExposedProperty'))

    # The sample didn't have everything, so this unit test will take the
    # minimum needed
    input_dict = {
    }

    port_hnd_list, offline, err_str = ConfigCmd.generate_tagged_ports(input_dict)
    assert port_hnd_list == []
    assert err_str == "Input missing required port_groups section"
Example #4
0
def test_get_tag_objects_blank(stc):
    fail_msg = ''
    try:
        tag_utils.get_tag_object('')
    except:
        exc_info = sys.exc_info()
        fail_list = traceback.format_exception_only(exc_info[0],
                                                    exc_info[1])
        fail_msg = fail_list[0] if len(fail_list) == 1 else '\n'.join(fail_list)
    if fail_msg == '':
        raise AssertionError('function did not fail as expected')
    if 'must not be blank' not in fail_msg:
        raise AssertionError('function failed with unexpected exception: "' +
                             fail_msg + '"')
    try:
        tag_utils.get_tag_object_list(['non-blank', ''])
    except:
        exc_info = sys.exc_info()
        fail_list = traceback.format_exception_only(exc_info[0],
                                                    exc_info[1])
        fail_msg = fail_list[0] if len(fail_list) == 1 else '\n'.join(fail_list)
    if fail_msg == '':
        raise AssertionError('function did not fail as expected')
    if 'must not be blank' not in fail_msg:
        raise AssertionError('function failed with unexpected exception: "' +
                             fail_msg + '"')
def test_run_tuple_empty(stc):
    ctor = CScriptableCreator()
    tag_utils.get_tag_object('Nothing')

    # Most of the parameters from the base class are ignored
    cmd = ctor.CreateCommand(CMD)
    cmd.SetCollection('TagNameList', ['Nothing', 'Nothing'])
    cmd.Set('ObjectOrder', 'SCALAR')
    cmd.Execute()
    # Pass 1
    assert 0 == cmd.Get('Iteration')
    assert '' == cmd.Get('CurrVal')
    assert 'FAILED' == cmd.Get('PassFailState')
    cmd.MarkDelete()
Example #6
0
def test_get_tag_object(stc):
    proj = CStcSystem.Instance().GetObject("Project")
    ctor = CScriptableCreator()

    tags = proj.GetObject('Tags')
    if tags is None:
        tags = ctor.Create('Tags', project)
    assert tags is not None

    exist_map = {obj.Get('Name'): obj for obj in tags.GetObjects('Tag')}
    # Create new
    tag = tag_utils.get_tag_object('Tag1')
    assert not isinstance(tag, list)
    assert tag.IsTypeOf('Tag')
    assert 'Tag1' == tag.Get('Name')
    assert 'Tag1' not in exist_map

    # Retrieve existing
    tag2 = tag_utils.get_tag_object('Tag1')
    assert tag.GetObjectHandle() == tag2.GetObjectHandle()
    assert 'Tag1' == tag2.Get('Name')
def test_run_scalar(stc):
    ctor = CScriptableCreator()
    proj = CStcSystem.Instance().GetObject('Project')
    # Set up tagged objects
    port = ctor.Create('Port', proj)
    for num in range(0, 4):
        with AutoCommand('DeviceCreateCommand') as cmd:
            cmd.Set('Port', port.GetObjectHandle())
            cmd.Set('DeviceCount', 1)
            cmd.Set('CreateCount', 1)
            cmd.Set('DeviceType', 'EmulatedDevice')
            cmd.SetCollection('IfStack', ['Ipv4If', 'EthIIIf'])
            cmd.SetCollection('IfCount', [1, 1])
            cmd.Execute()
    dev_list = proj.GetObjects('EmulatedDevice')
    assert 4 == len(dev_list)
    cmd = ctor.CreateCommand(CMD)
    curr_val = str(dev_list[0].GetObjectHandle())
    cmd.SetCollection('TagNameList', ['Sample'])
    cmd.Set('CurrVal', curr_val)
    cmd.Set('Iteration', 1)
    cmd.Execute()
    sample_tag = tag_utils.get_tag_object('Sample')
    targ_list = sample_tag.GetObjects('Scriptable',
                                      RelationType('UserTag', True))
    # Remove 'Tags'
    targ_list = [o.GetObjectHandle() for o in targ_list if not o.IsTypeOf('Tags')]
    assert 1 == len(targ_list)
    assert dev_list[0].GetObjectHandle() == targ_list[0]
    cmd.Reset()
    # Call it again, with another handle
    curr_val = str(dev_list[1].GetObjectHandle())
    cmd.SetCollection('TagNameList', ['Sample'])
    cmd.Set('CurrVal', curr_val)
    cmd.Set('Iteration', 2)
    cmd.Execute()
    targ_list = sample_tag.GetObjects('Scriptable',
                                      RelationType('UserTag', True))
    # Remove 'Tags'
    targ_list = [o.GetObjectHandle() for o in targ_list if not o.IsTypeOf('Tags')]
    assert 1 == len(targ_list)
    assert dev_list[1].GetObjectHandle() == targ_list[0]

    # Clean up
    cmd.MarkDelete()
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 test_run(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')
    right_tag = tag_utils.get_tag_object('Right_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'))
    ep = ctor.Create('ExposedProperty', ep_cfg)
    ep.Set('EPNameId', 'RightPortGroup')
    ep.Set('EPClassId', 'tag')
    ep.Set('EPPropertyId', 'scriptable.name')
    ep.AddObject(right_tag, RelationType('ScriptableExposedProperty'))

    meth_name = "test_RunMethodologyTestCommand_test_run"
    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

    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()

    # Create a valid JSON file
    json_content = get_sample_2544_json()
    meta_json_file = os.path.join(test_dir, mgr_const.MM_META_JSON_FILE_NAME)
    f = open(meta_json_file, "w")
    f.write(json_content)
    f.close()

    meth_man = stc_sys.GetObject("StmMethodologyManager")
    if meth_man is None:
        meth_man = ctor.Create("StmMethodologyManager", stc_sys)
    assert meth_man
    test_meth = ctor.Create("StmMethodology", meth_man)
    test_meth.Set("MethodologyKey", meth_name)
    test_case = ctor.Create("StmTestCase", test_meth)
    assert test_case is not None
    assert test_case.IsTypeOf("StmTestCase")
    test_case.Set("Path", test_dir)
    test_case.Set("TestCaseKey", test_name)

    # 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 == ""

    # Call the run function with invalid StmTestCase handle
    res = RunCmd.run("", test_meth.GetObjectHandle(), "", "", False)
    assert not res
    assert 'Was unable to find StmTestCase with handle' in cmd.Get("Status")
    cmd.Set("Status", '')

    # Call the run function with missing proc function script file
    res = RunCmd.run("", test_case.GetObjectHandle(), "", "", False)
    assert not res
    assert cmd.Get("Status") == 'Failed to find script: RunMethodologyTestCommandTestScript.py'
    cmd.Set("Status", '')

    # Create the proc function script file
    err_str, meta = json_utils.load_json(json_content)
    assert err_str == ""
    script_filename = meta["processing_functions"][0]["script_filename"]
    script_full_path = write_testscript(script_filename)
    assert script_full_path is not None

    # Call the run function with valid StmTestCaseHandle
    res = RunCmd.run("", test_case.GetObjectHandle(), "", "", False)
    assert res
    assert cmd.Get("Status") == ''

    # 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()) == 8
    assert key_value_dict["CommandAddressStartValue"] == "198.18.1.2"
    assert key_value_dict["CommandAddressStepValue"] == "0.0.1.0"
    assert key_value_dict["TrafficDuration"] == "60"
    vlist = key_value_dict["ObjectIteratorCommand.ValueList"]
    assert type(vlist) is list
    sitems = set(vlist) & set(["64", "128", "256", "512", "1024", "1280", "1518"])
    assert len(sitems) == 7
    assert key_value_dict["cmd1.bgp.count"] == "3"

    # Clear out KeyValueJson in the meth group command
    meth_group_cmd.Set("KeyValueJson", "")
    key_value_json = meth_group_cmd.Get("KeyValueJson")
    assert key_value_json == ""

    # Call the run function with invalid test case key
    res = RunCmd.run("InvalidTestCaseKey", 0, "", "", False)
    assert not res
    assert cmd.Get("Status") == 'Test case with key InvalidTestCaseKey not found'
    cmd.Set("Status", '')

    # Call the run function with valid test case key
    res = RunCmd.run(test_name, 0, "", "", False)
    assert res
    assert cmd.Get("Status") == ''

    # 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()) == 8

    assert remove_testscript(script_full_path)

    # 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 test_generate_tagged_ports(stc):
    project = CStcSystem.Instance().GetObject('Project')
    ctor = CScriptableCreator()
    left_tag = tag_utils.get_tag_object('Left_Port_Group')
    right_tag = tag_utils.get_tag_object('Right_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'))
    ep = ctor.Create('ExposedProperty', ep_cfg)
    ep.Set('EPNameId', 'RightPortGroup')
    ep.Set('EPClassId', 'tag')
    ep.Set('EPPropertyId', 'scriptable.name')
    ep.AddObject(right_tag, RelationType('ScriptableExposedProperty'))

    # The sample didn't have everything, so this unit test will take the
    # minimum needed
    input_dict_string = '''{
        "port_groups": [
            {
                "prop_id": "LeftPortGroup",
                "name": "Left",
                "bring_online": true,
                "ports": [
                    {
                        "location": "10.10.10.1/1/1"
                    }
                ]
            },
            {
                "prop_id": "RightPortGroup",
                "name": "Right",
                "ports": [
                    {
                        "location": "10.10.10.2/1/1"
                    }
                ]
            }
        ]
    }'''
    err_str, input_dict = json_utils.load_json(input_dict_string)
    assert err_str == ""

    port_hnd_list, offline, err_str = RunCmd.generate_tagged_ports(input_dict)

    assert 2 == len(port_hnd_list)
    assert False is offline
    assert err_str == ""
    hnd_reg = CHandleRegistry.Instance()
    port_list = [hnd_reg.Find(hnd) for hnd in port_hnd_list]
    tag0 = port_list[0].GetObject('Tag', RelationType('UserTag'))
    tag1 = port_list[1].GetObject('Tag', RelationType('UserTag'))
    assert left_tag.GetObjectHandle() == tag0.GetObjectHandle()
    assert port_list[0].Get('Name').startswith('Left 1')
    assert port_list[0].Get('Location') == '//10.10.10.1/1/1'
    assert right_tag.GetObjectHandle() == tag1.GetObjectHandle()
    assert port_list[1].Get('Name').startswith('Right 1')
    assert port_list[1].Get('Location') == '//10.10.10.2/1/1'

    # Test the bring_online parameter
    input_dict_string = '''{
        "port_groups": [
            {
                "prop_id": "LeftPortGroup",
                "name": "Left",
                "bring_online": false,
                "ports": [
                    {
                        "location": "10.10.10.1/1/1"
                    }
                ]
            },
            {
                "prop_id": "RightPortGroup",
                "name": "Right",
                "bring_online": true,
                "ports": [
                    {
                        "location": "10.10.10.2/1/1"
                    }
                ]
            }
        ]
    }'''
    err_str, input_dict = json_utils.load_json(input_dict_string)
    assert err_str == ""

    port_hnd_list, offline, err_str = RunCmd.generate_tagged_ports(input_dict)

    assert 2 == len(port_hnd_list)
    assert True is offline
    assert err_str == ""
def process_wizard_args(tmpl_cfg, wiz_list):
    '''
    Inputs: Template config and list of wizard dictionaries containing
    targetTagList, srcObjectTagName, createdRoutesTagName, commandName
    '''
    plLogger = PLLogger.GetLogger('methodology')
    this_cmd = get_this_cmd()
    for wiz in wiz_list:
        targ_tag_list = wiz.get('targetTagList')
        src_tag = wiz.get('srcObjectTagName')
        route_tag_name = wiz.get('createdRoutesTagName')
        command_name = wiz.get('commandName')
        # FIXME: It seems curious that the bllWizardExpand section has a
        # target tag list, when the command itself has the same list as a
        # input property -- evaluate whether this can be eliminated
        if not targ_tag_list:
            err = "No target tag list given"
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        if not src_tag:
            err = "No source object tag given"
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        if not command_name:
            err = "Command name not specified"
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        rtr_list = tag_utils.get_tagged_objects_from_string_names(targ_tag_list)
        # Remove duplicates by using an ordered dictionary
        rtr_list = dm_utils.remove_dup_scriptable(rtr_list)
        if len(rtr_list) == 0:
            err = "targetTagList results in an empty list"
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        pf_state, status = 'FAILED', ''
        with AutoCommand(PKG + '.ExpandTemplateCommand') as cmd:
            cmd.SetCollection('StmTemplateConfigList',
                              [tmpl_cfg.GetObjectHandle()])
            cmd.SetCollection('SrcTagList', [src_tag])
            cmd.Execute()
            pf_state = cmd.Get('PassFailState')
            status = cmd.Get('Status')
        if pf_state == 'FAILED':
            err = '{}.ExpandTemplateCommand failed: {}' \
                .format(PKG, status)
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        # Call the wizard once the configuration is loaded
        cfg_obj_list = tag_utils.get_tagged_objects_from_string_names([src_tag])
        if not cfg_obj_list:
            err = 'Failed to load expected configuration object for {}' \
                .format(tmpl_cfg.Get('Name'))
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        if len(cfg_obj_list) > 1:
            err = 'More than one configuration objects loaded from {}' \
                .format(tmpl_cfg.Get('Name'))
            plLogger.LogInfo(err)
        # We check the object list just to prevent bad input. The target
        # command operates on the tag only, so we don't need to manipulate the
        # objects beyond getting the count
        pf_state, status = 'FAILED', ''
        tag_created = False
        if not route_tag_name:
            route_tag_name = 'Tmp Imported Routes'
            tag_created = True
        with AutoCommand(command_name) as cmd:
            # Set the parameters depending on the command used
            if 'Import' in command_name:
                cmd.SetCollection('RouterTagList', targ_tag_list)
                cmd.Set('BgpImportParamsTagName', src_tag)
                cmd.Set('CreatedRoutesTagName', route_tag_name)
            elif 'Prefix' in command_name:
                cmd.SetCollection('RouterTagList', targ_tag_list)
                cmd.Set('SrcObjectTagName', src_tag)
                cmd.Set('CreatedRoutesTagName', route_tag_name)
            cmd.Execute()
            pf_state = cmd.Get('PassFailState')
            status = cmd.Get('Status')
        if pf_state == 'FAILED':
            err = '{} failed: {}'.format(command_name, status)
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        # After a successful run, we need to associate the newly-created
        # routes to the template with the GeneratedObject relation
        added_route_list = \
            tag_utils.get_tagged_objects_from_string_names([route_tag_name])
        for route in added_route_list:
            tmpl_cfg.AddObject(route, RelationType('GeneratedObject'))
        # If we created a temporary tag, delete it here
        if tag_created:
            tag_obj = tag_utils.get_tag_object(route_tag_name)
            tag_obj.MarkDelete()
    return True
def process_route_args(tmpl_cfg, routers_dict):
    '''
    Purpose: Calls the ExpandTemplateCommand for each protocol in the
    configuration
    Inputs: Template config and component section from the templatemix
    '''
    plLogger = PLLogger.GetLogger("methodology")
    this_cmd = get_this_cmd()

    root = etree.fromstring(tmpl_cfg.Get('TemplateXml'))

    # For each kind of RouterConfig, check this StmTemplateConfig's
    # XML tree for that classname.
    for router_type in routers_dict:
        # Remove serializationBase from the XML
        serial_ele_list = root.findall('.//*[@serializationBase="true"]')
        for ele in serial_ele_list:
            if 'serializationBase' in ele.attrib:
                ele.attrib.pop('serializationBase')
        ele_list = root.findall(".//" + router_type)
        if not ele_list:
            continue
        # We found, for instance, a BgpRouterConfig both in the
        # template XML, and in StmProtocolMix's objects, so we
        # expand this StmTemplateConfig onto all those objects

        if len(ele_list) != 1:
            err = "More than one {} found. That's weird." \
                .format(router_type)
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        router_ele = ele_list[0]

        # Mark all children with serializationBase
        for child in router_ele:
            plLogger.LogInfo("process element: " + str(child))
            if child.tag == "Relation":
                # Except for Relation elements
                continue
            # Check for Ipv4NetworkBlocks or Ipv6NetworkBlocks
            ipv4_net_block = child.find(".//Ipv4NetworkBlock")
            ipv6_net_block = child.find(".//Ipv6NetworkBlock")
            if (ipv4_net_block is not None and len(ipv4_net_block)) or \
               (ipv6_net_block is not None and len(ipv6_net_block)):
                child.attrib["serializationBase"] = "true"
            else:
                plLogger.LogWarn("Skipping object of type " +
                                 child.tag)

        # Make temporary tags for this instance of ExpandRouteMixCommand
        tag_obj = tag_utils.get_tag_object(TEMP_TRG_TAG)

        # Tag all routerConfigs in the dictionary of this type
        # with a temporary target tag, since ExpandTemplateCommand
        # needs that
        for router in routers_dict[router_type]:
            tag_utils.add_tag_to_object(router, TEMP_TRG_TAG)
        tmpl_cfg.Set("TemplateXml", etree.tostring(root))

        pf_state, status = 'FAILED', ''
        with AutoCommand(PKG + '.ExpandTemplateCommand') as cmd:
            cmd.SetCollection('StmTemplateConfigList',
                              [tmpl_cfg.GetObjectHandle()])
            cmd.SetCollection("TargetTagList", [TEMP_TRG_TAG])
            cmd.Execute()
            pf_state = cmd.Get('PassFailState')
            status = cmd.Get('Status')
        if pf_state == 'FAILED':
            err = '{}.ExpandTemplateCommand failed: {}' \
                .format(PKG, status)
            plLogger.LogError(err)
            this_cmd.Set('Status', err)
            return False
        # After expand of routes is done, remove the tag from the target
        # router objects
        tag_obj.MarkDelete()
    return True
def test_run_tuple_mismatch(stc):
    ctor = CScriptableCreator()
    proj = CStcSystem.Instance().GetObject('Project')
    # Set up tagged objects
    port = ctor.Create('Port', proj)
    for num in range(0, 4):
        with AutoCommand('DeviceCreateCommand') as cmd:
            cmd.Set('Port', port.GetObjectHandle())
            cmd.Set('DeviceCount', 1)
            cmd.Set('CreateCount', 1)
            cmd.Set('DeviceType', 'EmulatedDevice')
            cmd.SetCollection('IfStack', ['Ipv4If', 'EthIIIf'])
            cmd.SetCollection('IfCount', [1, 1])
            cmd.Execute()
    dev_list = proj.GetObjects('EmulatedDevice')
    assert 4 == len(dev_list)
    cmd = ctor.CreateCommand(CMD)
    curr_val = str(dev_list[0].GetObjectHandle()) + ',' + \
        str(dev_list[2].GetObjectHandle())
    # Only one tag value given
    cmd.SetCollection('TagNameList', ['Sample'])
    cmd.Set('CurrVal', curr_val)
    try:
        cmd.Execute()
    except:
        exc_info = sys.exc_info()
        fail_list = traceback.format_exception_only(*exc_info[0:2])
        fail_msg = fail_list[0] if len(fail_list) == 1 else '\n'.join(fail_list)
    finally:
        cmd.MarkDelete()
    if fail_msg == '':
        raise AssertionError('Command did not fail as expected')
    if 'Not enough tag names' not in fail_msg:
        raise AssertionError('Command failed with unexpected exception: "' +
                             fail_msg + '"')
    cmd.Reset()
    curr_val = str(dev_list[0].GetObjectHandle())
    # Only one tag value given
    cmd.SetCollection('TagNameList', ['Sample', 'Dest'])
    cmd.Set('CurrVal', curr_val)
    # Should be ok if we have more tags than values
    cmd.Execute()
    sample_tag = tag_utils.get_tag_object('Sample')
    dest_tag = tag_utils.get_tag_object('Dest')
    targ_list = sample_tag.GetObjects('Scriptable',
                                      RelationType('UserTag', True))
    # Remove 'Tags'
    targ_list = [o.GetObjectHandle() for o in targ_list if not o.IsTypeOf('Tags')]

    targ_list = sample_tag.GetObjects('Scriptable',
                                      RelationType('UserTag', True))
    # Remove 'Tags'
    targ_list = [o.GetObjectHandle() for o in targ_list if not o.IsTypeOf('Tags')]
    targ2_list = dest_tag.GetObjects('Scriptable',
                                     RelationType('UserTag', True))
    # Remove 'Tags'
    targ2_list = [o.GetObjectHandle() for o in targ2_list if not o.IsTypeOf('Tags')]

    # Verify
    assert 1 == len(targ_list)
    assert dev_list[0].GetObjectHandle() == targ_list[0]
    assert 0 == len(targ2_list)