def test_get_class_objects(stc):
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    port = ctor.Create("Port", project)
    rx_port = ctor.Create("Port", project)
    stream_block = ctor.Create("StreamBlock", port)
    stream_block.AddObject(rx_port, RelationType("ExpectedRx"))
    tag_utils.add_tag_to_object(stream_block, "ttStreamBlock")
    proto_mix = ctor.Create("StmProtocolMix", project)
    template_config = ctor.Create("StmTemplateConfig", proto_mix)
    template_config.AddObject(port, RelationType("GeneratedObject"))
    tag_utils.add_tag_to_object(template_config, "ttTemplateConfig")
    em_device = ctor.Create("EmulatedDevice", project)
    bgp_router_config = ctor.Create("BgpRouterConfig", em_device)

    # No target object for class type
    target_objs = dm_utils.get_class_objects([], [], ["StreamBlock"])
    assert len(target_objs) == 0

    # Handle passed in is of class type
    target_objs = dm_utils.get_class_objects([stream_block.GetObjectHandle()], [], ["StreamBlock"])
    assert len(target_objs) == 1
    assert target_objs[0].IsTypeOf("StreamBlock")

    # Handle passed in has child of class type
    target_objs = dm_utils.get_class_objects([proto_mix.GetObjectHandle()], [], ["StreamBlock"])
    assert len(target_objs) == 1
    assert target_objs[0].IsTypeOf("StreamBlock")

    # ProtocolMix
    target_objs = dm_utils.get_class_objects([proto_mix.GetObjectHandle()], [], ["StreamBlock"])
    assert len(target_objs) == 1
    assert target_objs[0].IsTypeOf("StreamBlock")

    # TemplateConfig
    target_objs = dm_utils.get_class_objects([], ["ttTemplateConfig"], ["StreamBlock"])
    assert len(target_objs) == 1
    assert target_objs[0].IsTypeOf("StreamBlock")

    # Verify that only one streamblock is returned and there aren't duplicates
    target_objs = dm_utils.get_class_objects([proto_mix.GetObjectHandle()], ["ttTemplateConfig"], ["StreamBlock"])
    assert len(target_objs) == 1
    assert target_objs[0].IsTypeOf("StreamBlock")

    # Multiple class types
    target_objs = dm_utils.get_class_objects([], ["ttTemplateConfig"], ["StreamBlock", "Port"])
    assert len(target_objs) == 2
    for obj in target_objs:
        assert obj.IsTypeOf("StreamBlock") or obj.IsTypeOf("Port")

    # Handle passed in is of class type
    target_objs = dm_utils.get_class_objects([bgp_router_config.GetObjectHandle()], [], ["RouterConfig"])
    assert len(target_objs) == 1
    assert target_objs[0].IsTypeOf("BgpRouterConfig")
def tag_wizgenerated_as_created(param_obj, CreatedRoutesTagName):
    wizGenRoutes = param_obj.GetObjects("Scriptable",
                                        RelationType("WizardGenerated"))
    wizGenRoutes += param_obj.GetObjects("Scriptable",
                                         RelationType("WizardGeneratedObject"))
    for obj in wizGenRoutes:
        # Tag all the "WizardGenerated" routes with the tag name requested via
        # this command's CreatedRoutesTagName property.
        if CreatedRoutesTagName:
            tag_utils.add_tag_to_object(obj, CreatedRoutesTagName)
    return True
def test_run_with_tag(stc):
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    proj = stc_sys.GetObject('Project')
    port = ctor.Create('Port', proj)
    seq = stc_sys.GetObject('Sequencer')
    # Create and tag the traffic mix
    traf_mix = ctor.Create('StmTrafficMix', proj)
    traf_mix.Set('MixInfo', mix_info_2_components())
    tag_utils.add_tag_to_object(traf_mix, 'MixTag')

    cmd = ctor.Create(PKG + '.AllocateTrafficMixLoadCommand', seq)
    cmd.Set('StmTrafficMix', traf_mix.GetObjectHandle())

    tmpl_list = []
    sb_list = []

    tmpl_list.append(ctor.Create('StmTemplateConfig', traf_mix))
    sb1 = ctor.Create('StreamBlock', port)
    sb_list.append(sb1)
    tmpl_list[-1].AddObject(sb1, RelationType('GeneratedObject'))

    tmpl_list.append(ctor.Create('StmTemplateConfig', traf_mix))
    sb2 = ctor.Create('StreamBlock', port)
    sb_list.append(sb2)
    tmpl_list[-1].AddObject(sb2, RelationType('GeneratedObject'))

    assert command.run(None, 'MixTag', 4, 'FRAMES_PER_SECOND')

    lp_list = [sb.GetObject('StreamBlockLoadProfile',
                            RelationType('AffiliationStreamBlockLoadProfile'))
               for sb in sb_list]
    load_list = [lp.Get('Load') for lp in lp_list]
    assert [3, 1] == load_list
    gen = port.GetObject("Generator")
    assert gen is not None
    gen_conf = gen.GetObject("GeneratorConfig")
    assert gen_conf is not None
    assert gen_conf.Get('schedulingmode') == 'RATE_BASED'

    roots = traf_mix.Get('MixInfo')
    assert roots
    err_str, root = json_utils.load_json(roots)
    assert err_str == ""
    assert 'loadUnits' in root
    assert root['loadUnits'] == 'FRAMES_PER_SECOND'
    assert 'components' in root
    assert len(root['components']) == 2
    assert 'appliedValue' in root['components'][0]
    assert root['components'][0]['appliedValue'] == 3
    assert 'appliedValue' in root['components'][1]
    assert root['components'][1]['appliedValue'] == 1
def test_get_obj_list_from_handles_and_tags(stc):
    obj_list = []
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    port = ctor.Create("Port", project)
    tag_utils.add_tag_to_object(port, "ttPort")
    rx_port = ctor.Create("Port", project)
    stream_block = ctor.Create("StreamBlock", port)
    stream_block.AddObject(rx_port, RelationType("ExpectedRx"))
    tag_utils.add_tag_to_object(stream_block, "ttStreamBlock")

    # Empty lists
    obj_list = dm_utils.get_obj_list_from_handles_and_tags([], [])
    assert obj_list == []

    # Only handles
    obj_list = dm_utils.get_obj_list_from_handles_and_tags([port.GetObjectHandle(), stream_block.GetObjectHandle()], [])
    assert len(obj_list) == 2
    for obj in obj_list:
        assert obj.IsTypeOf("StreamBlock") or obj.IsTypeOf("Port")

    # Only tags
    obj_list = dm_utils.get_obj_list_from_handles_and_tags([], ["ttPort", "ttStreamBlock"])
    assert len(obj_list) == 2
    for obj in obj_list:
        assert obj.IsTypeOf("StreamBlock") or obj.IsTypeOf("Port")

    # Handle and tag mix duplicate
    obj_list = dm_utils.get_obj_list_from_handles_and_tags(
        [port.GetObjectHandle(), stream_block.GetObjectHandle()], ["ttPort", "ttStreamBlock"]
    )
    assert len(obj_list) == 2
    for obj in obj_list:
        assert obj.IsTypeOf("StreamBlock") or obj.IsTypeOf("Port")

    # Handle and tag mix different
    obj_list = dm_utils.get_obj_list_from_handles_and_tags([rx_port.GetObjectHandle()], ["ttPort", "ttStreamBlock"])
    assert len(obj_list) == 3
    for obj in obj_list:
        assert obj.IsTypeOf("StreamBlock") or obj.IsTypeOf("Port")

    # Handle and tag that doesn't exist
    obj_list = dm_utils.get_obj_list_from_handles_and_tags(
        [port.GetObjectHandle(), stream_block.GetObjectHandle()], ["ttBlah"]
    )
    assert len(obj_list) == 2
    for obj in obj_list:
        assert obj.IsTypeOf("StreamBlock") or obj.IsTypeOf("Port")
def create_traffic_mix(tag_name):
    proj = CStcSystem.Instance().GetObject('Project')
    ctor = CScriptableCreator()
    # Using default values from traffic mix, assume only a single mix/template
    mix_info = {'Load': '10.0',
                'LoadUnit': 'PERCENT_LINE_RATE',
                'WeightList': '100'}
    mix_elem = etree.Element('MixInfo', mix_info)
    traf_mix = ctor.Create('StmTrafficMix', proj)
    if traf_mix is None:
        return traf_mix
    traf_mix.Set('MixInfo', etree.tostring(mix_elem))
    if tag_name:
        tag_utils.add_tag_to_object(traf_mix, tag_name)
    return traf_mix
def test_run_scalar_multi(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)
    tag_utils.add_tag_to_object(dev_list[0], 'Group A')
    tag_utils.add_tag_to_object(dev_list[1], 'Group A')
    tag_utils.add_tag_to_object(dev_list[2], 'Group B')
    tag_utils.add_tag_to_object(dev_list[3], 'Group B')

    # Most of the parameters from the base class are ignored
    cmd = ctor.CreateCommand(CMD)
    cmd.SetCollection('TagNameList', ['Group A', 'Group B'])
    cmd.Set('ObjectOrder', 'SCALAR')
    cmd.Execute()
    # Pass 1
    assert 1 == cmd.Get('Iteration')
    assert str(dev_list[0].GetObjectHandle()) == cmd.Get('CurrVal')
    assert 'PASSED' == cmd.Get('PassFailState')
    # Need reset for next run
    cmd.Reset()
    cmd.Execute()
    # Pass 2
    assert 2 == cmd.Get('Iteration')
    assert str(dev_list[1].GetObjectHandle()) == cmd.Get('CurrVal')
    assert 'PASSED' == cmd.Get('PassFailState')
    cmd.Reset()
    cmd.Execute()
    # Pass 3
    assert 3 == cmd.Get('Iteration')
    assert str(dev_list[2].GetObjectHandle()) == cmd.Get('CurrVal')
    assert 'PASSED' == cmd.Get('PassFailState')
    cmd.Reset()
    cmd.Execute()
    # Pass 4
    assert 4 == cmd.Get('Iteration')
    assert str(dev_list[3].GetObjectHandle()) == cmd.Get('CurrVal')
    assert 'PASSED' == cmd.Get('PassFailState')
    cmd.Reset()
    cmd.Execute()
    # Pass 5
    assert 4 == cmd.Get('Iteration')
    assert str(dev_list[3].GetObjectHandle()) == cmd.Get('CurrVal')
    assert 'FAILED' == cmd.Get('PassFailState')
    cmd.MarkDelete()
def tag_wizgenerated_as_created(routeGenParamObj, CreatedRoutesTagName):

    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogDebug(" RoutePrefixDistributionCommand tag_wizgenerated_as_created start")
    wizGenRoutes = routeGenParamObj.GetObjects("Scriptable",
                                               RelationType("WizardGenerated"))
    wizGenRoutes += routeGenParamObj.GetObjects("Scriptable",
                                                RelationType("WizardGeneratedObject"))
    for obj in wizGenRoutes:
        # Tag all the "WizardGenerated" routes with the tag name requested via this
        # command's CreatedRoutesTagName property.
        if CreatedRoutesTagName:
            tag_utils.add_tag_to_object(obj, CreatedRoutesTagName)
            plLogger.LogDebug("Adding tag " + CreatedRoutesTagName + " to " + obj.Get("Name"))

    plLogger.LogDebug(" RoutePrefixDistributionCommand tag_wizgenerated_as_created end")
    return True
def run(Load, LoadUnit, MixTagName, AutoExpandTemplateMix):
    # plLogger = PLLogger.GetLogger("CreateTrafficMix1Command")
    hnd_reg = CHandleRegistry.Instance()
    this_cmd = get_this_cmd()
    proj = CStcSystem.Instance().GetObject('Project')
    ctor = CScriptableCreator()
    # Notes on element tree data storage:
    # We are using the attributes within a single MixInfo element, and each of
    # the values are stored as attributes of the single element. Note that
    # non-string values are not allowed in ElementTree, so the appropriate
    # casts are needed:
    # Set float: str(value)
    # Get float: float(value)
    # Enums, act as strings already
    # Append to list of float:
    #   list = list + ' ' + str(val) if len(list) != 0 else str(val)
    # Retrieve from list of float:
    #   float_list = [float(x) for x in list.split()]

    mix_info = {'Load': str(Load),
                'LoadUnit': LoadUnit,
                'WeightList': ''}
    # This is a one-node tree
    mix_elem = etree.Element('MixInfo', mix_info)
    traf_mix = ctor.Create('StmTrafficMix', proj)
    if traf_mix is None:
        plLogger.LogError('Failed to create StmTrafficMix')
        return False
    traf_mix.Set('MixInfo', etree.tostring(mix_elem))
    traf_mix_hdl = traf_mix.GetObjectHandle()
    this_cmd.Set('StmTemplateMix', traf_mix_hdl)
    # Create tag if it doesn't exist, else associate existing tag
    if MixTagName:
        tag_utils.add_tag_to_object(traf_mix, MixTagName)

    # Configure all contained commands, note that validate should have ensured
    # the correct types were passed in, so they are not checked here
    for cmd_hnd in this_cmd.GetCollection('CommandList'):
        cmd = hnd_reg.Find(cmd_hnd)
        if cmd is None:
            continue
        if cmd.IsTypeOf(TPKG + ".SetTrafficEndpointTagsCommand"):
            cmd.Set('TrafficMix', traf_mix_hdl)
        if cmd.IsTypeOf(TPKG + ".LoadTrafficTemplateCommand"):
            cmd.Set("StmTemplateMix", traf_mix_hdl)
    return True
Example #9
0
def test_add_tag_to_object(stc):
    ctor = CScriptableCreator()
    proj = CStcSystem.Instance().GetObject('project')
    port = ctor.Create('Port', proj)
    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 = proj.GetObject('EmulatedDevice')
    assert dev
    tag_utils.add_tag_to_object(dev, 'Random')
    tag = dev.GetObject('Tag', RelationType('UserTag'))
    assert tag
    assert 'Random' == tag.Get('Name')
def test_run(stc):
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    ctor = CScriptableCreator()

    port = ctor.Create("Port", project)
    ethCopper = ctor.Create("EthernetCopper", port)
    port.AddObject(ethCopper, RelationType("ActivePhy"))

    # Create and tag router
    emDevice = ctor.Create("EmulatedDevice", project)
    emDevice.AddObject(port, RelationType("AffiliationPort"))
    ipv4If = ctor.Create("Ipv4If", emDevice)
    ethIf = ctor.Create("EthIIIf", emDevice)
    emDevice.AddObject(ipv4If, RelationType("TopLevelIf"))
    emDevice.AddObject(ipv4If, RelationType("PrimaryIf"))
    ipv4If.AddObject(ethIf, RelationType("StackedOnEndpoint"))
    ctor.Create("BgpRouterConfig", emDevice)
    tag_utils.add_tag_to_object(emDevice, "ttEmulatedDevice")

    # Create and tag wizard object
    bgpParamObj = ctor.Create("BgpRouteGenParams", project)
    tag_utils.add_tag_to_object(bgpParamObj, "ttBgpRouteGenParams")
    ipv4ParamObj = ctor.Create("Ipv4RouteGenParams", bgpParamObj)
    ipv4ParamObj.SetCollection("PrefixLengthDist", [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                               0.0, 0.0, 0.0, 0.0, 0.0, 50.0, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                               0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
    ipv4ParamObj.Set("Count", 2)
    ipv4ParamObj.Set("PrefixLengthDistType", "CUSTOM")
    ctor.Create("BgpRouteGenRouteAttrParams", ipv4ParamObj)

    # Run the command
    PrefixCmd.run(["ttEmulatedDevice"], "ttBgpRouteGenParams", "ttBgpRoutes")

    routeObjs = tag_utils.get_tagged_objects_from_string_names("ttBgpRoutes")
    assert len(routeObjs) == 2

    for routeObj in routeObjs:
        assert routeObj.IsTypeOf("BgpIpv4RouteConfig")

    return
def test_run_with_tag(stc):
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    proj = stc_sys.GetObject('Project')
    port = ctor.Create('Port', proj)
    seq = stc_sys.GetObject('Sequencer')
    # Create the traffic mix
    traf_mix = ctor.Create('StmTrafficMix', proj)
    traf_mix.Set('MixInfo',
                 '<MixInfo Load="10.0" LoadUnit="PERCENT_LINE_RATE" WeightList="" />')
    mix_elem = etree.fromstring(traf_mix.Get('MixInfo'))
    mix_elem.set('WeightList', "10.0")
    traf_mix.Set('MixInfo', etree.tostring(mix_elem))
    tag_utils.add_tag_to_object(traf_mix, 'MixTag')
    cmd = ctor.Create(PKG + '.AllocateTrafficMixLoad1Command', seq)
    cmd.Set('TagName', 'MixTag')
    ret = command.run(cmd.Get('StmTrafficMix'), cmd.Get('TagName'),
                      cmd.Get('Load'), cmd.Get('LoadUnit'))
    # This will fail because we have 1 weight with zero templates
    assert False is ret
    mix_elem.set('WeightList', "15.0 25.0")
    traf_mix.Set('MixInfo', etree.tostring(mix_elem))
    tmpl_list = []
    sb_list = []
    tmpl_list.append(ctor.Create('StmTemplateConfig', traf_mix))
    sb1 = ctor.Create('StreamBlock', port)
    sb_list.append(sb1)
    tmpl_list[-1].AddObject(sb1, RelationType('GeneratedObject'))
    tmpl_list.append(ctor.Create('StmTemplateConfig', traf_mix))
    sb2 = ctor.Create('StreamBlock', port)
    sb_list.append(sb2)
    tmpl_list[-1].AddObject(sb2, RelationType('GeneratedObject'))
    ret = command.run(cmd.Get('StmTrafficMix'), cmd.Get('TagName'),
                      cmd.Get('Load'), cmd.Get('LoadUnit'))
    assert True is ret
    lp_list = [sb.GetObject('StreamBlockLoadProfile',
                            RelationType('AffiliationStreamBlockLoadProfile'))
               for sb in sb_list]
    load_list = [lp.Get('Load') for lp in lp_list]
    assert [1.5, 2.5] == load_list
def test_command_params(stc):
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    port = ctor.Create("Port", project)
    handle_list = [port.GetObjectHandle()]
    rx_port = ctor.Create("Port", project)
    stream_block = ctor.Create("StreamBlock", port)
    stream_block.AddObject(rx_port, RelationType("ExpectedRx"))
    tag_utils.add_tag_to_object(stream_block, "ttStreamBlock")

    # Validate L2LearningStartCommand params
    cmd = learningCmd.l2_learning_start(handle_list, "RX_ONLY")
    assert cmd.GetCollection("HandleList") == handle_list
    assert cmd.Get("L2LearningOption") == "RX_ONLY"
    cmd.MarkDelete()

    # Validate L2LearningStopCommand params
    cmd = learningCmd.l2_learning_stop(handle_list)
    assert cmd.GetCollection("HandleList") == handle_list
    cmd.MarkDelete()

    # Validate ArpNdStartCommand params
    cmd = learningCmd.l3_learning_start(handle_list, False, True)
    assert cmd.GetCollection("HandleList") == handle_list
    assert not cmd.Get("WaitForArpToFinish")
    assert cmd.Get("ForceArp")
    cmd.MarkDelete()

    # Validate ArpNdStopCommand params
    cmd = learningCmd.l3_learning_stop(handle_list)
    assert cmd.GetCollection("HandleList") == handle_list
    cmd.MarkDelete()

    # Validate ArpNdVerifyResolvedCommand params
    cmd = learningCmd.verify_arp(handle_list)
    assert cmd.GetCollection("HandleList") == handle_list
    cmd.MarkDelete()

    return
def test_run_tuple_invalid(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)
    tag_utils.add_tag_to_object(dev_list[0], 'Group A')
    tag_utils.add_tag_to_object(dev_list[1], 'Group A')
    tag_utils.add_tag_to_object(dev_list[2], 'Group B')
    tag_utils.add_tag_to_object(dev_list[3], 'Group B')

    # Most of the parameters from the base class are ignored
    cmd = ctor.CreateCommand(CMD)
    cmd.SetCollection('TagNameList', ['Group A'])
    cmd.Set('ObjectOrder', 'TUPLE')
    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 'only got one' not in fail_msg:
        raise AssertionError('Command failed with unexpected exception: "' +
                             fail_msg + '"')
def create_tagged_devices(port, name, count, tag_name):
    ret_hnd_list = []
    with AutoCommand('DeviceCreateCommand') as cmd:
        if_stack = ['Ipv4If', 'EthIIIf']
        cmd.Set('Port', port.GetObjectHandle())
        cmd.Set('DeviceCount', 1)
        cmd.Set('CreateCount', count)
        cmd.Set('DeviceType', 'EmulatedDevice')
        cmd.SetCollection('IfStack', if_stack)
        cmd.SetCollection('IfCount', [1] * len(if_stack))
        cmd.Execute()
        ret_hnd_list = cmd.GetCollection('ReturnList')
    hnd_reg = CHandleRegistry.Instance()
    obj_list = [hnd_reg.Find(hnd) for hnd in ret_hnd_list]
    for num, obj in enumerate(obj_list, start=1):
        obj.Set('Name', '{} {}'.format(name, num))
        tag_utils.add_tag_to_object(obj, tag_name)
        ipv4If = obj.GetObject('ipv4if')
        if ipv4If:
            tag_utils.add_tag_to_object(ipv4If, tag_name + "_ttIpv4If")
        ethIf = obj.GetObject('ethiiif')
        if ethIf:
            tag_utils.add_tag_to_object(ethIf, tag_name + "_ttEthIIIf")
    return obj_list
def run(TargetObjectList, TargetObjectTagList, MixInfo, MixTagName, AutoExpandTemplateMix):
    # TODO: Add sample JSON

    plLogger = PLLogger.GetLogger("methodology")
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    this_cmd = get_this_cmd()
    ctor = CScriptableCreator()

    # Validate the input MixInfo against its schema
    res = json_utils.validate_json(MixInfo, this_cmd.Get('MixInfoJsonSchema'))
    if res != '':
        plLogger.LogError(res)
        this_cmd.Set("Status", res)
        return False

    # Validate the hierarchy against our current command list...
    msg = mix_utils.run_validate_hierarchy(this_cmd, [hierarchy()])
    if msg != '':
        err_str = 'Invalid Sequence: ' + msg
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False
    # Tag the commands in our command list according to our hierarchy information...
    tag_dict = mix_utils.run_tag_hierarchy(this_cmd, [hierarchy()])

    # Setup for property chaining / outputting the tag dictionary...
    this_cmd.Set('GroupCommandTagInfo', json.dumps(tag_dict))
    plLogger.LogInfo('GroupCommandTagInfo: ' + this_cmd.Get('GroupCommandTagInfo'))

    # Create the StmTemplateMix object...
    plLogger.LogInfo('Creating the route mix object...')
    mix = ctor.Create('StmTemplateMix', project)
    this_cmd.Set('StmTemplateMix', mix.GetObjectHandle())
    # If a MixTagName was specified, then tag the mix with it...
    if MixTagName:
        tag_utils.add_tag_to_object(mix, MixTagName)
    # Copy the entire MixInfo into StmTemplateMix object...
    mix.Set('MixInfo', MixInfo)

    # Load the MixInfo...
    err_str, mix_info = json_utils.load_json(MixInfo)
    if err_str != "":
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    # Directly configure all tagged commands in our hierarchy...
    plLogger.LogDebug('setting up commands in the group based on ' + str(tag_dict))

    plLogger.LogDebug('loading json from MixInfo: ' + str(MixInfo))
    num_rows = len(mix_info.get('components', []))
    plLogger.LogDebug('Number of Rows: ' + str(num_rows))

    # Pass table to configurator - this guy will configure other commands per iteration...
    conf_cmd = tag_utils.get_tagged_objects_from_string_names([tag_dict['rowConfigurator']])[0]
    conf_cmd.Set('StmTemplateMix', mix.GetObjectHandle())
    conf_cmd.Set('TagData', this_cmd.Get('GroupCommandTagInfo'))

    # Pass the StmTemplateMix to the CreateTemplateConfigCommand...
    ctc_cmd = tag_utils.get_tagged_objects_from_string_names([tag_dict['templateConfigurator']])[0]
    ctc_cmd.Set('StmTemplateMix', mix.GetObjectHandle())
    ctc_cmd.Set('AutoExpandTemplate', False)

    # Setup Row Iterator (pass in number of rows) - the While command's expression command...
    iter_cmd = tag_utils.get_tagged_objects_from_string_names([tag_dict['rowIterator']])[0]
    iter_cmd.Set('IterMode', 'STEP')
    iter_cmd.Set('StepVal', '1')
    iter_cmd.Set('ValueType', 'RANGE')
    iter_cmd.Set('MinVal', 0.0)
    iter_cmd.Set('MaxVal', (float(num_rows) - 1.0))

    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(stc):
    sequencer = CStcSystem.Instance().GetObject("Sequencer")
    ctor = CScriptableCreator()
    cmd = ctor.Create("spirent.methodology.L2L3LearningCommand", sequencer)
    gtc_p = patch("spirent.methodology.L2L3LearningCommand.get_this_cmd",
                  new=MagicMock(return_value=cmd))
    gtc_p.start()

    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    port = ctor.Create("Port", project)
    handle_list = [port.GetObjectHandle()]

    rx_port = ctor.Create("Port", project)
    stream_block = ctor.Create("StreamBlock", port)
    stream_block.AddObject(rx_port, RelationType("ExpectedRx"))
    tag_utils.add_tag_to_object(stream_block, "ttStreamBlock")
    em_device = ctor.Create("EmulatedDevice", project)
    em_device.AddObject(port, RelationType("AffiliationPort"))
    tag_utils.add_tag_to_object(em_device, "ttEmulatedDevice")
    invalid = ctor.Create("BgpRouterConfig", em_device)

    # L2Learning
    assert learningCmd.run(handle_list, [], True, False,
                           "TX_RX", True, True, False)

    # L3Learning
    assert learningCmd.run([], ["ttStreamBlock"], False, True,
                           "TX_RX", False, False, False)

    # L2L3Learning
    assert learningCmd.run(handle_list, ["ttStreamBlock"], True, True,
                           "TX_RX", True, True, False)

    # L2Learning with invalid handle type and valid tag
    assert not learningCmd.run([em_device.GetObjectHandle()], ["ttStreamBlock"], True, False,
                               "TX_RX", True, False, False)
    assert "Invalid handle type: emulateddevice. L2 learning command " + \
        "only allows handles of type Port and StreamBlock" in cmd.Get('Status')

    # L2Learning with invalid handle type and valid handle
    assert not learningCmd.run([em_device.GetObjectHandle(), port.GetObjectHandle()],
                               ["ttStreamBlock"], True, False, "TX_RX", True, False, False)
    assert "Invalid handle type: emulateddevice. L2 learning command " + \
        "only allows handles of type Port and StreamBlock" in cmd.Get('Status')

    # L2L3Learning with invalid handle type and valid handle
    assert not learningCmd.run([invalid.GetObjectHandle(), port.GetObjectHandle()],
                               ["ttStreamBlock"], True, True, "TX_RX", True, False, False)
    assert "Invalid handle type: bgprouterconfig. Learning command " + \
        "only allows handles of type Port, StreamBlock, Host, Router, " + \
        "and EmulatedDevice" in cmd.Get('Status')

    # Empty ObjectList and TagNameList
    assert learningCmd.run([], [], True, True,
                           "TX_RX", True, True, False)

    # L2L3Learning with only valid handle for L3
    assert learningCmd.run([em_device.GetObjectHandle()], [], True, True,
                           "TX_RX", True, False, False)

    # L2L3Learning with only valid tag for L3
    assert learningCmd.run([], ["ttEmulatedDevice"], True, True,
                           "TX_RX", True, True, False)

    # L2Learning with only valid tag for L3
    assert learningCmd.run([], ["ttEmulatedDevice"], True, False,
                           "TX_RX", True, True, False)

    gtc_p.stop()
    return
def run(LeftTagName, RightTagName, EnableLearning,
        MicroburstMaxRate, MicroburstRateUnit, FrameSize, MaxDeltaCount,
        DeltaWidth, MaxUniqueAddrCount, MaxImg,
        NominalRate, NominalRateUnit,
        EnableRandomSeed, RandomSeedValue,
        BestEffortTagName, MicroburstTagName, MixTagName,
        MicroburstFileName):
    plLogger = PLLogger.GetLogger('Y.1564MicroburstSetup')
    plLogger.LogInfo('Initialize random number generator')
    this_cmd = get_this_cmd()
    # Initialize the random number generator
    if EnableRandomSeed:
        random.seed(RandomSeedValue)
    else:
        random.seed()
    # Rather than call the usual Traffic Mix and Template commands, we fake it
    # here to add the raw streamblocks based on the source port
    plLogger.LogInfo('Create dummy traffic mix')
    traf_mix = create_traffic_mix(MixTagName)
    if not traf_mix:
        raise RuntimeError('Failed to create Traffic Mix object')
    plLogger.LogInfo('Create dummy traffic template')
    tmpl_cfg = create_traffic_template(traf_mix)
    if not tmpl_cfg:
        raise RuntimeError('Failed to create Traffic Template Config object')
    this_cmd.Set('Status', 'Configure generator')
    # Initialize the persistent object
    cmd_dict = {
        'left_tag': LeftTagName,
        'right_tag': RightTagName,
        'stream_tag': MicroburstTagName,
        'max_img': MaxImg,
        'max_unique': MaxUniqueAddrCount,
        'last_unique': 1,
        'nom_rate': NominalRate,
        'nom_rate_unit': NominalRateUnit,
        'bur_max_rate': MicroburstMaxRate,
        'bur_rate_unit': MicroburstRateUnit,
        'frame_size': FrameSize,
        'delta_width': DeltaWidth,
        'gen_list': configure_generator(LeftTagName),
        'img_frame_list': [],
        'be_hdl_list': [],
        'delta_list': [],
        'uniq_map': {}}
    if len(cmd_dict['gen_list']) == 0:
        plLogger.LogError('Failed to retrieve a list of generators')
        return False
    this_cmd.Set('Status', 'Load Microburst configuration')
    plLogger.LogInfo('Read Microburst configuration')
    burst_cfg = read_microburst_cfg(MicroburstFileName)
    # Each burst configuration is stored as a dictionary in a list
    cmd_dict['burst_cfg'] = burst_cfg[:]
    total_delta = 0
    total_be_frame = 0
    plLogger.LogInfo('Configure ' + str(len(burst_cfg)) + ' bursts')
    for burst in cmd_dict['burst_cfg']:
        status = 'Create best effort stream for ' + burst['MicroburstName']
        this_cmd.Set('Status', status)
        plLogger.LogInfo(status)
        # create best effort stream
        be_stream, sched = create_manual_stream(cmd_dict, burst)
        if be_stream:
            tmpl_cfg.AddObject(be_stream, RelationType('GeneratedObject'))
            cmd_dict['be_hdl_list'].append(be_stream.GetObjectHandle())
        if sched:
            tmpl_cfg.AddObject(sched, RelationType('GeneratedObject'))
        if BestEffortTagName:
            tag_utils.add_tag_to_object(be_stream, BestEffortTagName)
        delta_count = random.randint(5, int(MaxDeltaCount))
        status = 'Creating ' + str(delta_count) + ' delta streams for ' + \
            burst['MicroburstName']
        this_cmd.Set('Status', status)
        plLogger.LogInfo(status)
        sb_hdl_list = []
        sb_rate_list = []
        sb_uniq_list = []
        for delta_idx in range(delta_count):
            status = 'Creating delta stream ' + str(delta_idx + 1) + \
                     ' of ' + str(delta_count) + \
                     ' for ' + burst['MicroburstName']
            this_cmd.Set('Status', status)
            plLogger.LogInfo(status)
            # Create delta stream
            del_stream, sched = create_manual_stream(cmd_dict, burst,
                                                     delta_idx)
            total_delta = total_delta + 1
            if del_stream:
                tmpl_cfg.AddObject(del_stream, RelationType('GeneratedObject'))
                sb_hdl_list.append(del_stream.GetObjectHandle())
                sb_rate_list.append(sched.Get('InterFrameGap'))
                sb_uniq_list.append(cmd_dict['last_unique'])
            if sched:
                tmpl_cfg.AddObject(sched, RelationType('GeneratedObject'))
            if MicroburstTagName:
                tag_utils.add_tag_to_object(del_stream, MicroburstTagName)
        # After all deltas per burst, store them
        cmd_dict['delta_list'].append({'handle': sb_hdl_list,
                                       'rate': sb_rate_list,
                                       'uniq': sb_uniq_list})
    # For each handle, map the unique count
    for hdl, uniq in zip(sum([i['handle'] for i in cmd_dict['delta_list']], []),
                         sum([i['uniq'] for i in cmd_dict['delta_list']], [])):
        cmd_dict['uniq_map'][hdl] = uniq
    total_be_frame = sum(cmd_dict['img_frame_list'])
    dur = float(DeltaWidth * total_delta + total_be_frame)

    plLogger.LogInfo('Setting generator duration to ' + str(dur))
    # Set generator's burst duration
    configure_generator(LeftTagName, dur)
    process_tagged_commands()

    # Overwrite if it already exists
    plLogger.LogInfo('Writing persistent object')
    CObjectRefStore.Put(OBJ_KEY, cmd_dict, True)

    if EnableLearning:
        this_cmd.Set('Status', 'Performing Learning...')
        with AutoCommand('ArpNdStartOnAllStreamBlocksCommand') as learning:
            port_list = \
                tag_utils.get_tagged_objects_from_string_names([tag_name])
            learning.SetCollection('PortList',
                                   [x.GetObjectHandle() for x in port_list])
            learning.Execute()
            # Note that whether it passes or fails, this command passes
    return True
def test_get_valid_handles(stc):
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    port = ctor.Create("Port", project)
    rx_port = ctor.Create("Port", project)
    stream_block = ctor.Create("StreamBlock", port)
    stream_block.AddObject(rx_port, RelationType("ExpectedRx"))
    tag_utils.add_tag_to_object(stream_block, "ttStreamBlock")
    em_device = ctor.Create("EmulatedDevice", project)
    em_device.AddObject(port, RelationType("AffiliationPort"))
    tag_utils.add_tag_to_object(em_device, "ttEmulatedDevice")
    proto_mix = ctor.Create("StmProtocolMix", project)
    template_config = ctor.Create("StmTemplateConfig", proto_mix)
    template_config.AddObject(stream_block, RelationType("GeneratedObject"))
    tag_utils.add_tag_to_object(template_config, "ttTemplateConfig")

    bgp_config = ctor.Create("BgpRouterConfig", em_device)
    tag_utils.add_tag_to_object(bgp_config, "ttBgpRouterConfig")

    # Empty handle list
    handle_list = []
    l2_handles, l3_handles = learningCmd.get_valid_handles(handle_list, [])
    assert l2_handles == []
    assert l3_handles == []

    # Port valid for L2 and L3
    handle_list = [port.GetObjectHandle()]
    l2_handles, l3_handles = learningCmd.get_valid_handles(handle_list, [])
    assert l2_handles == handle_list
    assert l3_handles == handle_list

    # EmulatedDevice valid for L3 only
    handle_list = [em_device.GetObjectHandle()]
    l2_handles, l3_handles = learningCmd.get_valid_handles(handle_list, [])
    assert l2_handles == []
    assert l3_handles == handle_list

    # BgpRouterConfig not valid for L2 or L3
    handle_list = [bgp_config.GetObjectHandle()]
    l2_handles, l3_handles = learningCmd.get_valid_handles(handle_list, [])
    assert l2_handles == []
    assert l3_handles == []

    # Valid L2L3 tagged object
    tag_name_list = ['ttStreamBlock']
    l2_handles, l3_handles = learningCmd.get_valid_handles([], tag_name_list)
    assert l2_handles == [stream_block.GetObjectHandle()]
    assert l3_handles == [stream_block.GetObjectHandle()]

    # Valid L2L3 tagged object and empty tag
    tag_name_list = ['ttStreamBlock', 'ttBlah']
    l2_handles, l3_handles = learningCmd.get_valid_handles([], tag_name_list)
    assert l2_handles == [stream_block.GetObjectHandle()]
    assert l3_handles == [stream_block.GetObjectHandle()]

    # Valid L3 tagged object
    tag_name_list = ['ttEmulatedDevice']
    l2_handles, l3_handles = learningCmd.get_valid_handles([], tag_name_list)
    assert l2_handles == []
    assert l3_handles == [em_device.GetObjectHandle()]

    # Valid L3 tagged object and valid L2L3 tagged object
    tag_name_list = ['ttStreamBlock', 'ttEmulatedDevice']
    l2_handles, l3_handles = learningCmd.get_valid_handles([], tag_name_list)
    assert l2_handles == [stream_block.GetObjectHandle()]
    assert l3_handles == [stream_block.GetObjectHandle(), em_device.GetObjectHandle()]

    # Shouldn't ever happen because of validate_handle_types being called
    # but testing anyway
    tag_name_list = ['ttBgpRouterConfig']
    l2_handles, l3_handles = learningCmd.get_valid_handles([], tag_name_list)
    assert l2_handles == []
    assert l3_handles == []

    # Valid template config tagged object
    tag_name_list = ['ttTemplateConfig']
    l2_handles, l3_handles = learningCmd.get_valid_handles([], tag_name_list)
    assert len(l2_handles) == 1
    assert l2_handles == [stream_block.GetObjectHandle()]
    assert len(l3_handles) == 1
    assert l3_handles == [stream_block.GetObjectHandle()]

    # Valid protocolmix object
    tag_name_list = ['ttTemplateConfig']
    l2_handles, l3_handles = learningCmd.get_valid_handles([proto_mix.GetObjectHandle()], [])
    assert len(l2_handles) == 1
    assert l2_handles == [stream_block.GetObjectHandle()]
    assert len(l3_handles) == 1
    assert l3_handles == [stream_block.GetObjectHandle()]

    return