def test_expand_run_validate(stc):
    plLogger = PLLogger.GetLogger("methodology")
    plLogger.LogInfo("start.test_ExpandProtocolMixCommand2.test_expand_run_validate")
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")

    test_xml = get_basic_template()
    north_test_xml = xml_utils.add_prefix_to_tags("North_", test_xml)
    south_test_xml = xml_utils.add_prefix_to_tags("South_", test_xml)

    cmd = ctor.CreateCommand(PKG + ".ExpandProtocolMixCommand2")
    ExpProtoMixCmd.get_this_cmd = MagicMock(return_value=cmd)

    # Test no StmTemplateMix
    res = ExpProtoMixCmd.run(0, "", 100)
    assert res is False

    # Create the StmTemplateMix
    proto_mix = ctor.Create("StmProtocolMix", project)

    # Test empty MixInfo
    res = ExpProtoMixCmd.run(proto_mix.GetObjectHandle(), "", 100)
    assert res is False

    mi = {}
    n_ti_dict = {}
    n_ti_dict["weight"] = 40.0
    n_ti_dict["devicesPerBlock"] = 10
    n_ti_dict["portGroupTag"] = "North Port Group"
    # n_ti_dict["deviceTag"] = "North_ttEmulatedClient"
    s_ti_dict = {}
    s_ti_dict["weight"] = 60.0
    s_ti_dict["staticDeviceCount"] = 10
    s_ti_dict["useStaticDeviceCount"] = False
    s_ti_dict["useBlock"] = False
    s_ti_dict["portGroupTag"] = "South Port Group"
    # s_ti_dict["deviceTag"] = "South_ttEmulatedClient"
    mi["templateInfo"] = [n_ti_dict, s_ti_dict]

    proto_mix.Set("MixInfo", json.dumps(mi))

    # Test mismatched TemplateInfo against StmTemplateConfigs
    res = ExpProtoMixCmd.run(proto_mix.GetObjectHandle(), "", 100)
    assert res is False

    # Create a child StmTemplateConfigs
    north_template = ctor.Create("StmTemplateConfig", proto_mix)
    north_template.Set("TemplateXml", north_test_xml)
    south_template = ctor.Create("StmTemplateConfig", proto_mix)
    south_template.Set("TemplateXml", south_test_xml)

    # Test not enough devices to distribute
    res = ExpProtoMixCmd.run(proto_mix.GetObjectHandle(), "", 1)
    assert res is False
def test_expand_proto_mix_invalid_device_count(stc):
    sequencer = CStcSystem.Instance().GetObject("Sequencer")
    project = CStcSystem.Instance().GetObject("Project")
    ctor = CScriptableCreator()
    hnd_reg = CHandleRegistry.Instance()

    test_xml = get_basic_template()
    west_test_xml = xml_utils.add_prefix_to_tags("West_", test_xml)

    # Create Port
    port1 = ctor.Create("Port", project)
    port1.Set("Location", "//10.14.16.27/2/1")
    tags = project.GetObject("Tags")
    if tags is None:
        tags = ctor.Create("Tags", project)
    assert tags is not None
    
    west_port_group_tag = ctor.Create("Tag", tags)
    west_port_group_tag.Set("Name", "West Port Group")
    port1.AddObject(west_port_group_tag, RelationType("UserTag"))
    tags.AddObject(west_port_group_tag, RelationType("UserTag"))

    # Create StmProtocolMix
    proto_mix = ctor.Create("StmProtocolMix", project)
    stm_temp_mix = proto_mix.GetObjectHandle()

    # Copy the MixInfo into StmProtocolMix object...
    mix_info = get_example_mix_info_devices_per_block()
    proto_mix.Set('MixInfo', mix_info)

    # Create a child StmTemplateConfig
    west_template = ctor.Create("StmTemplateConfig", proto_mix)
    west_template.Set("TemplateXml", west_test_xml)
    east_template = ctor.Create("StmTemplateConfig", proto_mix)
    east_template.Set("TemplateXml", west_test_xml)
    north_template = ctor.Create("StmTemplateConfig", proto_mix)
    north_template.Set("TemplateXml", west_test_xml)
    south_template = ctor.Create("StmTemplateConfig", proto_mix)
    south_template.Set("TemplateXml", west_test_xml)

    # Call Expand
    cmd = ctor.CreateCommand(PKG + ".ExpandProtocolMix2Command")
    cmd.Set("StmTemplateMix", stm_temp_mix)
    cmd.Set("TagName", "")
    cmd.Set("DeviceCount", 1)
    cmd.SetCollection("PortGroupTagList", ["West Port Group"])
    cmd.Execute()
    assert cmd.Get("Status") != ''
    assert cmd.Get("PassFailState") == 'FAILED'

    cmd.MarkDelete()
def run(StmTemplateMix, InputJson, AutoExpandTemplate,
        CopiesPerParent, SrcTagList, TargetTagList):
    plLogger = PLLogger.GetLogger('methodology')
    plLogger.LogDebug("CreateTemplateConfigCommand.run")

    hnd_reg = CHandleRegistry.Instance()
    ctor = CScriptableCreator()
    this_cmd = get_this_cmd()
    project = CStcSystem.Instance().GetObject("Project")

    if InputJson == "":
        err_str = "InputJson is an empty string."
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    # Validate the InputJson against the schema
    res = json_utils.validate_json(InputJson,
                                   this_cmd.Get("InputJsonSchema"))
    if res != "":
        err_str = "InputJson is invalid or does not conform to the " + \
            "schema: " + res
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    if StmTemplateMix != "" and StmTemplateMix != 0:
        mix = hnd_reg.Find(StmTemplateMix)
        if mix is None:
            err_str = "StmTemplateMix with given handle: " + \
                str(StmTemplateMix) + " is invalid."
            plLogger.LogError(err_str)
            this_cmd.Set("Status", err_str)
            return False
        elif not mix.IsTypeOf("StmTemplateMix"):
            err_str = "Object with given handle: " + \
                str(StmTemplateMix) + " is a " + \
                mix.GetType() + ".  If StmTemplateMix is " + \
                "specified, object must be an StmTemplateMix."
            plLogger.LogError(err_str)
            this_cmd.Set("Status", err_str)
            return False
        parent = mix
    else:
        parent = project

    template = ctor.Create("StmTemplateConfig", parent)
    this_cmd.Set("StmTemplateConfig", template.GetObjectHandle())

    # Breakdown the json
    err_str, conf_data = json_utils.load_json(InputJson)
    if err_str != "":
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    plLogger.LogDebug("conf_data: " + str(conf_data))

    # Do the load first
    if "baseTemplateFile" not in conf_data.keys():
        plLogger.LogError("InputJson is missing a baseTemplateFile.")
        return False
    xml_file = conf_data["baseTemplateFile"]

    xml_val = xml_utils.load_xml_from_file(xml_file)
    if xml_val is None:
        err_str = "Was unable to load template XML from " + xml_file
        plLogger.LogError(err_str)
        this_cmd.Set("Status", err_str)
        return False

    # Update the prefixes
    tag_prefix = ""
    if ("tagPrefix" in conf_data.keys() and conf_data["tagPrefix"] != ""):
        tag_prefix = conf_data["tagPrefix"]
    plLogger.LogDebug("using tag_prefix: " + tag_prefix)

    xml_val = xml_utils.add_prefix_to_tags(tag_prefix, xml_val)
    template.Set("TemplateXml", xml_val)
    plLogger.LogDebug("conf_data: " + str(conf_data))

    # Iterate over the objects in the array and apply the appropriate
    # template modification.  Order is determined by the list order.
    for mod_data in conf_data.get("modifyList", []):
        plLogger.LogDebug("mod_data: " + str(mod_data))
        plLogger.LogDebug("mod_data.keys(): " + str(mod_data.keys()))
        err_str = ""
        res = True

        # Merge stuff in mergeList
        for merge_data in mod_data.get("mergeList", []):
            res = run_merge(template, tag_prefix, merge_data)
            err_str = "Failed to merge XML into the StmTemplateConfig " + \
                "given JSON specified as: " + str(merge_data)

        # Process objects in the addObjectList
        for obj_data in mod_data.get("addObjectList", []):
            res = run_objectlist(template, tag_prefix, obj_data)
            err_str = "Failed to add object into the StmTemplateConfig " + \
                "given JSON specified as: " + str(obj_data)

        # Modify the stuff in the PropertyValueList
        for prop_set in mod_data.get('propertyValueList', []):
            res = run_modify(template, tag_prefix, prop_set)
            err_str = "Failed to modify properties in the " + \
                "StmTemplateConfig given JSON specified as: " + \
                str(prop_set)

        # Modify the stuff in the StmPropertyModifierList
        for prop_set in mod_data.get("stmPropertyModifierList", []):
            res = run_config_prop_modifier(template, tag_prefix, prop_set)
            err_str = "Failed to add or configure " + \
                "StmPropertyModifier objects in the StmTemplateConfig " + \
                "given JSON specified as: " + str(prop_set)

        # Modify PDUs
        for pdu_mod in mod_data.get("pduModifierList", []):
            res = run_config_pdu(template, tag_prefix, pdu_mod)
            err_str = "Failed to modify PDU data in a streamblock's " + \
                "FrameConfig in the StmTemplateConfig given JSON " + \
                "specified as: " + str(pdu_mod)

        # Modify the stuff in the RelationList
        for rel_mod in mod_data.get("relationList", []):
            res = run_config_relation(template, tag_prefix, rel_mod)
            err_str = "Failed to add or remove a relation in the " + \
                "StmTemplateConfig given JSON specified as " + str(rel_mod)

        if not res:
            plLogger.LogError(err_str)
            this_cmd.Set("Status", err_str)
            return False

    # Handle Expand if necessary
    if AutoExpandTemplate:
        res = run_expand(template, TargetTagList,
                         SrcTagList, CopiesPerParent)
        if not res:
            err_str = "Failed to expand the StmTemplateConfig."
            plLogger.LogError(err_str)
            this_cmd.Set("Status", err_str)
            return False

    this_cmd.Set("Status", "")
    return True
예제 #4
0
def run(
    CopiesPerParent,
    TargetTagList,
    TemplateXml,
    TemplateXmlFileName,
    TagPrefix,
    AutoExpandTemplate,
    EnableLoadFromFileName,
    StmTemplateMix,
):
    plLogger = PLLogger.GetLogger("methodology")
    plLogger.LogDebug("run LoadTemplateCommand")

    did_expand = False
    ctor = CScriptableCreator()
    stc_sys = CStcSystem.Instance()
    project = stc_sys.GetObject("Project")
    hnd_reg = CHandleRegistry.Instance()

    # Look up the StmTemplateMix
    parent_obj = hnd_reg.Find(StmTemplateMix)
    if parent_obj is None:
        plLogger.LogDebug("Was unable to find a StmTemplateMix with " + str(StmTemplateMix) + " using project ")
        parent_obj = project
    else:
        if not parent_obj.IsTypeOf("StmTemplateMix"):
            plLogger.LogError(
                "Incorrect handle passed in for "
                + "StmTemplateMix.  Expected an "
                + "object of type StmTemplateMix, "
                + "instead received a(n) "
                + parent_obj.GetType()
            )
            return False
        plLogger.LogDebug(
            "Was able to find a StmTemplateMix, using " + parent_obj.Get("Name") + " with id: " + str(StmTemplateMix)
        )

    # Create an empty TemplateConfig object
    temp_conf = ctor.Create("StmTemplateConfig", parent_obj)

    if temp_conf is None:
        plLogger.LogError("ERROR: Failed to create an StmTemplateConfig")
        return False

    xml_value = None
    if not EnableLoadFromFileName:
        xml_value = TemplateXml
    elif TemplateXmlFileName != "":
        xml_value = xml_utils.load_xml_from_file(TemplateXmlFileName)
    if xml_value is None:
        plLogger.LogError("ERROR: No valid template source.")
        return False

    if TagPrefix != "":
        xml_value = xml_utils.add_prefix_to_tags(TagPrefix, xml_value)
    temp_conf.Set("TemplateXml", xml_value)

    # Pass the handles to the commands contained in this group
    cmd_count = config_contained_cmds(get_this_cmd(), temp_conf)

    # Set the output handle (since we already have the object)
    this_cmd = get_this_cmd()
    this_cmd.Set("StmTemplateConfig", temp_conf.GetObjectHandle())

    # FIXME: WORKAROUND: on_last_command_complete() doesn't get called if
    # no children commands exist...
    if cmd_count == 0:
        on_complete([])
        did_expand = True
    if did_expand:
        pass
    # END FIXME: WORKAROUND
    return True
def test_expand_proto_mix_invalid_device_count(stc):
    test_xml = get_basic_template()
    north_test_xml = xml_utils.add_prefix_to_tags("North_", test_xml)
    south_test_xml = xml_utils.add_prefix_to_tags("South_", test_xml)

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

    plLogger = PLLogger.GetLogger("test_expand_proto_mix")
    plLogger.LogDebug("start")

    port1 = ctor.Create("Port", project)
    port1.Set("Location", "//10.14.16.27/2/1")
    port2 = ctor.Create("Port", project)
    port2.Set("Location", "//10.14.16.27/2/2")

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

    north_port_group_tag = ctor.Create("Tag", tags)
    north_port_group_tag.Set("Name", "North Port Group")
    south_port_group_tag = ctor.Create("Tag", tags)
    south_port_group_tag.Set("Name", "South Port Group")
    port1.AddObject(north_port_group_tag, RelationType("UserTag"))
    port2.AddObject(south_port_group_tag, RelationType("UserTag"))
    tags.AddObject(north_port_group_tag, RelationType("UserTag"))
    tags.AddObject(south_port_group_tag, RelationType("UserTag"))

    # Create the StmTemplateMix
    proto_mix = ctor.Create("StmProtocolMix", project)
    mi = {}
    n_ti_dict = {}
    n_ti_dict["weight"] = 50.0
    n_ti_dict["staticDeviceCount"] = 30
    n_ti_dict["useStaticDeviceCount"] = True
    n_ti_dict["useBlock"] = False
    n_ti_dict["portGroupTag"] = "North Port Group"
    n_ti_dict["deviceTag"] = "North_ttEmulatedClient"
    s_ti_dict = {}
    s_ti_dict["weight"] = 50.0
    s_ti_dict["staticDeviceCount"] = 20
    s_ti_dict["useStaticDeviceCount"] = True
    s_ti_dict["useBlock"] = False
    s_ti_dict["portGroupTag"] = "South Port Group"
    s_ti_dict["deviceTag"] = "South_ttEmulatedClient"
    mi["templateInfo"] = [n_ti_dict, s_ti_dict]

    proto_mix.Set("MixInfo", json.dumps(mi))

    # Create a child StmTemplateConfig for North
    north_template = ctor.Create("StmTemplateConfig", proto_mix)
    north_template.Set("TemplateXml", north_test_xml)

    # Create a child StmTemplateConfig for South
    south_template = ctor.Create("StmTemplateConfig", proto_mix)
    south_template.Set("TemplateXml", south_test_xml)

    # Call Expand
    res = ExpProtoMixCmd.run(proto_mix.GetObjectHandle(), "", 10)
    assert res is False
    assert cmd.GetStatus("")
def test_expand_proto_mix(stc):
    plLogger = PLLogger.GetLogger("methodology")
    plLogger.LogInfo("start.test_CreateProtocolMixCommand2.test_expand_proto_mix")
    test_xml = get_basic_template()
    north_test_xml = xml_utils.add_prefix_to_tags("North_", test_xml)
    south_test_xml = xml_utils.add_prefix_to_tags("South_", test_xml)

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

    plLogger = PLLogger.GetLogger("test_expand_proto_mix")
    plLogger.LogDebug("start")

    port1 = ctor.Create("Port", project)
    port1.Set("Location", "//10.14.16.27/2/1")
    port2 = ctor.Create("Port", project)
    port2.Set("Location", "//10.14.16.27/2/2")

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

    north_port_group_tag = ctor.Create("Tag", tags)
    north_port_group_tag.Set("Name", "North Port Group")
    south_port_group_tag = ctor.Create("Tag", tags)
    south_port_group_tag.Set("Name", "South Port Group")
    port1.AddObject(north_port_group_tag, RelationType("UserTag"))
    port2.AddObject(south_port_group_tag, RelationType("UserTag"))
    tags.AddObject(north_port_group_tag, RelationType("UserTag"))
    tags.AddObject(south_port_group_tag, RelationType("UserTag"))

    # Create the StmTemplateMix
    proto_mix = ctor.Create("StmProtocolMix", project)
    mi = {}
    n_ti_dict = {}
    n_ti_dict["weight"] = 40.0
    n_ti_dict["useBlock"] = False
    n_ti_dict["staticDeviceCount"] = 0
    n_ti_dict["useStaticDeviceCount"] = False
    n_ti_dict["portGroupTag"] = "North Port Group"
    n_ti_dict["deviceTag"] = "North_ttEmulatedClient"
    s_ti_dict = {}
    s_ti_dict["weight"] = 60.0
    s_ti_dict["staticDeviceCount"] = 0
    s_ti_dict["useStaticDeviceCount"] = False
    s_ti_dict["useBlock"] = True
    s_ti_dict["portGroupTag"] = "South Port Group"
    s_ti_dict["deviceTag"] = "South_ttEmulatedClient"
    mi["templateInfo"] = [n_ti_dict, s_ti_dict]

    proto_mix.Set("MixInfo", json.dumps(mi))

    # Create a child StmTemplateConfig for North
    north_template = ctor.Create("StmTemplateConfig", proto_mix)
    north_template.Set("TemplateXml", north_test_xml)

    # Create a child StmTemplateConfig for South
    south_template = ctor.Create("StmTemplateConfig", proto_mix)
    south_template.Set("TemplateXml", south_test_xml)

    # Call Expand
    cmd = ctor.CreateCommand(PKG + ".ExpandProtocolMixCommand2")
    cmd.Set("StmTemplateMix", proto_mix.GetObjectHandle())
    cmd.Execute()
    cmd.MarkDelete()

    # Check the expanded protocol mix
    dev_list = north_template.GetObjects("EmulatedDevice",
                                         RelationType("GeneratedObject"))
    assert len(dev_list) == 4
    for dev in dev_list:
        assert dev.Get("DeviceCount") == 1
    dev_list = south_template.GetObjects("EmulatedDevice",
                                         RelationType("GeneratedObject"))
    assert len(dev_list) == 1
    for dev in dev_list:
        assert dev.Get("DeviceCount") == 6

    # Check the MixInfo
    mi_str = proto_mix.Get("MixInfo")
    plLogger.LogInfo("traffic mix info: " + mi_str)
    mi_dict = json.loads(mi_str)
    assert mi_dict["deviceCount"] == 10
    found_north = False
    found_south = False
    for ti_dict in mi_dict["templateInfo"]:
        if ti_dict["portGroupTag"] == "North Port Group":
            assert ti_dict["deviceCount"] == 4
            found_north = True
        elif ti_dict["portGroupTag"] == "South Port Group":
            assert ti_dict["deviceCount"] == 6
            found_south = True
    assert found_north
    assert found_south
def test_devices_per_block(stc):
    project = CStcSystem.Instance().GetObject("Project")
    ctor = CScriptableCreator()

    test_xml = get_basic_template()
    west_test_xml = xml_utils.add_prefix_to_tags("West_", test_xml)

    # Create Port
    port1 = ctor.Create("Port", project)
    port1.Set("Location", "//10.14.16.27/2/1")
    tags = project.GetObject("Tags")
    if tags is None:
        tags = ctor.Create("Tags", project)
    assert tags is not None

    west_port_group_tag = ctor.Create("Tag", tags)
    west_port_group_tag.Set("Name", "West Port Group")
    port1.AddObject(west_port_group_tag, RelationType("UserTag"))
    tags.AddObject(west_port_group_tag, RelationType("UserTag"))

    # Create StmProtocolMix
    proto_mix = ctor.Create("StmProtocolMix", project)
    stm_temp_mix = proto_mix.GetObjectHandle()

    # Copy the MixInfo into StmProtocolMix object...
    mix_info = get_example_mix_info_devices_per_block()
    proto_mix.Set('MixInfo', mix_info)

    # Create a child StmTemplateConfig
    w_temp = ctor.Create("StmTemplateConfig", proto_mix)
    w_temp.Set("TemplateXml", west_test_xml)
    e_temp = ctor.Create("StmTemplateConfig", proto_mix)
    e_temp.Set("TemplateXml", west_test_xml)
    n_temp = ctor.Create("StmTemplateConfig", proto_mix)
    n_temp.Set("TemplateXml", west_test_xml)
    s_temp = ctor.Create("StmTemplateConfig", proto_mix)
    s_temp.Set("TemplateXml", west_test_xml)

    # Call Expand
    cmd = ctor.CreateCommand(PKG + ".ExpandProtocolMixCommand")
    cmd.Set("StmTemplateMix", stm_temp_mix)
    cmd.Set("TagName", "")
    cmd.Set("DeviceCount", 100)
    cmd.SetCollection("PortGroupTagList", ["West Port Group"])
    cmd.Execute()
    assert cmd.Get("Status") == ''
    assert cmd.Get("PassFailState") == 'PASSED'

    cmd.MarkDelete()

    # Check the expanded protocol mix
    w_dev_list = w_temp.GetObjects("EmulatedDevice", RelationType("GeneratedObject"))
    e_dev_list = e_temp.GetObjects("EmulatedDevice", RelationType("GeneratedObject"))
    n_dev_list = n_temp.GetObjects("EmulatedDevice", RelationType("GeneratedObject"))
    s_dev_list = s_temp.GetObjects("EmulatedDevice", RelationType("GeneratedObject"))

    assert len(w_dev_list) == 1
    assert len(e_dev_list) == 9
    assert len(n_dev_list) == 8
    assert len(s_dev_list) == 1

    # DeviceCount = 100
    # {
    #     "devicesPerBlock": 0,
    #     "weight": 10,
    # }
    # 1 Block of 10
    assert w_dev_list[0].Get("DeviceCount") == 10

    # DeviceCount = 100 - 10
    # {
    #     "devicesPerBlock": 5,
    #     "weight": 50%,
    # }
    # 90 * 50% = 45 --> 9 Blocks of 5
    for e_dev in e_dev_list:
        assert e_dev.Get("DeviceCount") == 5

    # DeviceCount = 100 - 10
    # {
    #     "devicesPerBlock": 5,
    #     "weight": 40%,
    # }
    # 90 * 40% = 36 --> 7 Blocks of 5; 1 Block of 1
    for idx, n_dev in enumerate(n_dev_list):
        if idx == len(n_dev_list)-1:
            assert n_dev.Get("DeviceCount") == 1
        else:
            assert n_dev.Get("DeviceCount") == 5

    # DeviceCount = 100 - 10
    # {
    #     "devicesPerBlock": 10,
    #     "weight": 10%,
    # }
    # 90 * 10% = 9 --> 1 Block of 9
    assert s_dev_list[0].Get("DeviceCount") == 9