gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_existing(module):
    existing = []
    netcfg = get_config(module)

    if module.params["mode"] == "maintenance":
        parents = ["configure maintenance profile maintenance-mode"]
    else:
        parents = ["configure maintenance profile normal-mode"]

    config = netcfg.get_section(parents)
    if config:
        existing = config.splitlines()
        existing = [cmd.strip() for cmd in existing]
        existing.pop(0)

    return existing


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def get_existing(module):
    existing = []
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    if module.params["mode"] == "maintenance":
        parents = ["configure maintenance profile maintenance-mode"]
    else:
        parents = ["configure maintenance profile normal-mode"]

    config = netcfg.get_section(parents)
    if config:
        existing = config.splitlines()
        existing = [cmd.strip() for cmd in existing]
        existing.pop(0)

    return existing
# Buggy code
def get_existing(module, args):
    existing = {}
    netcfg = get_config(module)
    parents = ["interface {0}".format(module.params["interface"].capitalize())]
    config = netcfg.get_section(parents)
    if "ospf" in config:
        for arg in args:
            if arg not in ["interface"]:
                existing[arg] = get_value(arg, config, module)
        existing["interface"] = module.params["interface"]
    return existing


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = ["interface {0}".format(module.params["interface"].capitalize())]
    config = netcfg.get_section(parents)
    if "ospf" in config:
        for arg in args:
            if arg not in ["interface"]:
                existing[arg] = get_value(arg, config, module)
        existing["interface"] = module.params["interface"]
    return existing
# Buggy code
def get_portchannel_mode(interface, protocol, module, netcfg):
    if protocol != "LACP":
        mode = "on"
    else:
        netcfg = get_config(module)
        parents = ["interface {0}".format(interface.capitalize())]
        body = netcfg.get_section(parents)

        mode_list = body.split("\n")

        for line in mode_list:
            this_line = line.strip()
            if this_line.startswith("channel-group"):
                find = this_line
        if "mode" in find:
            if "passive" in find:
                mode = "passive"
            elif "active" in find:
                mode = "active"

    return mode


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def get_portchannel_mode(interface, protocol, module, netcfg):
    if protocol != "LACP":
        mode = "on"
    else:
        netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
        parents = ["interface {0}".format(interface.capitalize())]
        body = netcfg.get_section(parents)

        mode_list = body.split("\n")

        for line in mode_list:
            this_line = line.strip()
            if this_line.startswith("channel-group"):
                find = this_line
        if "mode" in find:
            if "passive" in find:
                mode = "passive"
            elif "active" in find:
                mode = "active"

    return mode
# Buggy code
def get_existing(module, args):
    existing = {}
    netcfg = get_config(module)

    interface_exist = check_interface(module, netcfg)
    if interface_exist:
        parents = ["interface port-channel{0}".format(module.params["group"])]
        config = netcfg.get_section(parents)

        if config:
            existing["min_links"] = get_value("min_links", config, module)
            existing.update(get_portchannel(module, netcfg=netcfg))

    return existing, interface_exist


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    interface_exist = check_interface(module, netcfg)
    if interface_exist:
        parents = ["interface port-channel{0}".format(module.params["group"])]
        config = netcfg.get_section(parents)

        if config:
            existing["min_links"] = get_value("min_links", config, module)
            existing.update(get_portchannel(module, netcfg=netcfg))

    return existing, interface_exist
# Buggy code
def state_absent(module, candidate, prefix):
    netcfg = get_config(module)
    commands = list()
    parents = "vrf context {0}".format(module.params["vrf"])
    invoke("set_route", module, commands, prefix)
    if module.params["vrf"] == "default":
        config = netcfg.get_section(commands[0])
        if config:
            invoke("remove_route", module, commands, config, prefix)
            candidate.add(commands, parents=[])
    else:
        config = netcfg.get_section(parents)
        splitted_config = config.split("\n")
        splitted_config = map(str.strip, splitted_config)
        if commands[0] in splitted_config:
            invoke("remove_route", module, commands, config, prefix)
            candidate.add(commands, parents=[parents])


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def state_absent(module, candidate, prefix):
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    commands = list()
    parents = "vrf context {0}".format(module.params["vrf"])
    invoke("set_route", module, commands, prefix)
    if module.params["vrf"] == "default":
        config = netcfg.get_section(commands[0])
        if config:
            invoke("remove_route", module, commands, config, prefix)
            candidate.add(commands, parents=[])
    else:
        config = netcfg.get_section(parents)
        splitted_config = config.split("\n")
        splitted_config = map(str.strip, splitted_config)
        if commands[0] in splitted_config:
            invoke("remove_route", module, commands, config, prefix)
            candidate.add(commands, parents=[parents])
# Buggy code
def get_existing(module, args):
    existing = {}
    netcfg = get_config(module)

    interface_string = "interface {0}".format(module.params["interface"].lower())
    parents = [interface_string]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            existing[arg] = get_value(arg, config, module)

        existing["interface"] = module.params["interface"].lower()
    else:
        if interface_string in str(netcfg):
            existing["interface"] = module.params["interface"].lower()
            for arg in args:
                existing[arg] = ""
    return existing


# Traceback (AttributeError)
ok: [s-srv1leaf2-2] => {
"purge_vnis": [
9999
]
}
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 589, in <module>
main()
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 533, in main
existing, interface_exist = invoke('get_existing', module, args)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 316, in invoke
return func(*args, **kwargs)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 377, in get_existing
temp_config = netcfg.get_section(parents)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 192, in get_section
section = self.get_section_objects(path)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 203, in get_section_objects
return self.expand_section(obj)
File "/tmp/ansible_yZvBEZ/ansible_module_nxos_vxlan_vtep_vni.py", line 175, in expand_section
if child in S:
File "/tmp/ansible_yZvBEZ/ansible_modlib.zip/ansible/module_utils/netcfg.py", line 47, in __eq__
AttributeError: 'str' object has no attribute 'line'

failed: [s-srv1leaf2-2] (item=9999) => {
"failed": true,
"invocation": {
"module_name": "nxos_vxlan_vtep_vni"
},
"item": 9999,

# Fixed code
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    interface_string = "interface {0}".format(module.params["interface"].lower())
    parents = [interface_string]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            existing[arg] = get_value(arg, config, module)

        existing["interface"] = module.params["interface"].lower()
    else:
        if interface_string in str(netcfg):
            existing["interface"] = module.params["interface"].lower()
            for arg in args:
                existing[arg] = ""
    return existing
# Buggy code
def checkpoint(filename, module):
    commands = ["terminal dont-ask", "checkpoint file %s" % filename]
    prepare_show_command(commands, module)


# Traceback (NameError)
Vault password:

PLAY [DRF_vxlan] ***********************************************************************************************************************************************************************************

TASK [checkpoint : Get backup] *********************************************************************************************************************************************************************
ok: [s-leaf]

TASK [checkpoint : DEBUG] **************************************************************************************************************************************************************************
ok: [s-leaf] => {
"changed": false,
"msg": "user.2017.04.12.13.57.03"
}

TASK [checkpoint : Set Checkpoint] *****************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: NameError: global name 'ShellError' is not defined
fatal: [s-leaf]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_aK1Nz9/ansible_module_nxos_rollback.py\", line 186, in <module>\n    main()\n  File \"/tmp/ansible_aK1Nz9/ansible_module_nxos_rollback.py\", line 178, in main\n    except ShellError:\nNameError: global name 'ShellError' is not defined\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}
to retry, use: --limit @/home/user/retry-files/site.retry

PLAY RECAP *****************************************************************************************************************************************************************************************
s-leaf : ok=2    changed=0    unreachable=0    failed=1

# Fixed code
def checkpoint(filename, module):
    commands = ["terminal dont-ask", "checkpoint file %s" % filename]
    run_commands(module, commands)
# Buggy code
def rollback(filename, module):
    commands = ["rollback running-config file %s" % filename]
    try:
        module.configure(commands)
    except AttributeError:
        try:
            module.cli.add_commands(commands, output="config")
            module.cli.run_commands()
        except ShellError:
            clie = get_exception()
            module.fail_json(
                msg="Error sending CLI commands", error=str(clie), commands=commands
            )


# Traceback (NameError)
Vault password:

PLAY [DRF_vxlan] ***********************************************************************************************************************************************************************************

TASK [checkpoint : Get backup] *********************************************************************************************************************************************************************
ok: [s-leaf]

TASK [checkpoint : DEBUG] **************************************************************************************************************************************************************************
ok: [s-leaf] => {
"changed": false,
"msg": "user.2017.04.12.13.57.03"
}

TASK [checkpoint : Set Checkpoint] *****************************************************************************************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: NameError: global name 'ShellError' is not defined
fatal: [s-leaf]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_aK1Nz9/ansible_module_nxos_rollback.py\", line 186, in <module>\n    main()\n  File \"/tmp/ansible_aK1Nz9/ansible_module_nxos_rollback.py\", line 178, in main\n    except ShellError:\nNameError: global name 'ShellError' is not defined\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}
to retry, use: --limit @/home/user/retry-files/site.retry

PLAY RECAP *****************************************************************************************************************************************************************************************
s-leaf : ok=2    changed=0    unreachable=0    failed=1

# Fixed code
def rollback(filename, module):
    commands = ["rollback running-config file %s" % filename]
    run_commands(module, commands)
# Buggy code
def is_pubkey(string):
    """Verifies if string is a pubkey"""
    pgp_regex = ".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*"
    return re.match(pgp_regex, string, re.DOTALL)


# Traceback (TypeError)
fatal: [xxx]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Shared connection to xxx closed.
", "module_stdout": "Traceback (most recent call last):
File "/tmp/ansible_sdddnvb2/ansible_module_rpm_key.py", line 209, in <module>
main()
File "/tmp/ansible_sdddnvb2/ansible_module_rpm_key.py", line 201, in main
RpmKey(module)
File "/tmp/ansible_sdddnvb2/ansible_module_rpm_key.py", line 85, in __init__
keyfile = self.fetch_key(key)
File "/tmp/ansible_sdddnvb2/ansible_module_rpm_key.py", line 122, in fetch_key
if not is_pubkey(key):
File "/tmp/ansible_sdddnvb2/ansible_module_rpm_key.py", line 70, in is_pubkey
return re.match(pgp_regex, string, re.DOTALL)
File "/usr/lib64/python3.5/re.py", line 163, in match
return _compile(pattern, flags).match(string)
TypeError: cannot use a string pattern on a bytes-like object
", "msg": "MODULE FAILURE"}

# Fixed code
def is_pubkey(string):
    """Verifies if string is a pubkey"""
    pgp_regex = ".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*"
    return bool(
        re.match(pgp_regex, to_native(string, errors="surrogate_or_strict"), re.DOTALL)
    )
# Buggy code
def __init__(self):
    super(CallbackModule, self).__init__()

    self.logger = logging.getLogger("ansible logger")
    self.logger.setLevel(logging.DEBUG)

    self.handler = logging.handlers.SysLogHandler(
        address=(
            os.getenv("SYSLOG_SERVER", "localhost"),
            os.getenv("SYSLOG_PORT", 514),
        ),
        facility=os.getenv("SYSLOG_FACILITY", logging.handlers.SysLogHandler.LOG_USER),
    )
    self.logger.addHandler(self.handler)
    self.hostname = socket.gethostname()


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib64/python2.6/logging/handlers.py", line 806, in emit
self.socket.sendto(msg, self.address)
TypeError: an integer is required

# Fixed code
def __init__(self):
    super(CallbackModule, self).__init__()

    self.logger = logging.getLogger("ansible logger")
    self.logger.setLevel(logging.DEBUG)

    self.handler = logging.handlers.SysLogHandler(
        address=(
            os.getenv("SYSLOG_SERVER", "localhost"),
            int(os.getenv("SYSLOG_PORT", 514)),
        ),
        facility=os.getenv("SYSLOG_FACILITY", logging.handlers.SysLogHandler.LOG_USER),
    )
    self.logger.addHandler(self.handler)
    self.hostname = socket.gethostname()
# Buggy code
def has_expired(self, key):
    if self._timeout == 0:
        return False

    cachefile = "%s/%s" % (self._cache_dir, key)
    try:
        st = os.stat(cachefile)
    except (OSError, IOError) as e:
        if e.errno == errno.ENOENT:
            return False
        else:
            display.warning(
                "error in '%s' cache plugin while trying to stat %s : %s"
                % (self.plugin_name, cachefile, to_bytes(e))
            )
            pass

    if time.time() - st.st_mtime <= self._timeout:
        return False

    if key in self._cache:
        del self._cache[key]
    return True


# Traceback (UnboundLocalError)
fatal: [my-host] => Traceback (most recent call last):
File "/home/david/.pip/ansible/lib/ansible/runner/__init__.py", line 586, in _executor
exec_rc = self._executor_internal(host, new_stdin)
File "/home/david/.pip/ansible/lib/ansible/runner/__init__.py", line 668, in _executor_internal
inject = self.get_inject_vars(host)
File "/home/david/.pip/ansible/lib/ansible/runner/__init__.py", line 611, in get_inject_vars
combined_cache = self.get_combined_cache()
File "/home/david/.pip/ansible/lib/ansible/runner/__init__.py", line 606, in get_combined_cache
combined_cache = self.setup_cache.copy()
File "/home/david/.pip/ansible/lib/ansible/cache/__init__.py", line 54, in copy
return dict([(k, v) for (k, v) in self.iteritems()])
File "/usr/lib/python2.7/_abcoll.py", line 406, in iteritems
yield (key, self[key])
File "/home/david/.pip/ansible/lib/ansible/cache/__init__.py", line 35, in __getitem__
return self._plugin.get(key)
File "/home/david/.pip/ansible/lib/ansible/cache/jsonfile.py", line 69, in get
f.close()
UnboundLocalError: local variable 'f' referenced before assignment

# Fixed code
def has_expired(self, key):
    if self._timeout == 0:
        return False

    cachefile = "%s/%s" % (self._cache_dir, key)
    try:
        st = os.stat(cachefile)
    except (OSError, IOError) as e:
        if e.errno == errno.ENOENT:
            return False
        else:
            display.warning(
                "error in '%s' cache plugin while trying to stat %s : %s"
                % (self.plugin_name, cachefile, to_bytes(e))
            )
            return False

    if time.time() - st.st_mtime <= self._timeout:
        return False

    if key in self._cache:
        del self._cache[key]
    return True
# Buggy code
def run_commands(module, commands, check_rc=True):
    responses = list()

    for cmd in to_list(commands):
        rc, out, err = exec_command(module, cmd)
        if check_rc and rc != 0:
            module.fail_json(msg=err, rc=rc)
        responses.append(out)
    return responses


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_YEHiix/ansible_module_iosxr_system.py", line 269, in <module>
main()
File "/tmp/ansible_YEHiix/ansible_module_iosxr_system.py", line 262, in main
if response.get('diff') and module._diff:
AttributeError: 'str' object has no attribute 'get'

# Fixed code
def run_commands(module, commands, check_rc=True):
    responses = list()
    commands = to_commands(module, to_list(commands))
    for cmd in to_list(commands):
        rc, out, err = exec_command(module, cmd)
        if check_rc and rc != 0:
            module.fail_json(msg=err, rc=rc)
        responses.append(out)
    return responses
# Buggy code
def load_config(module, commands, commit=False, replace=False, comment=None):
    rc, out, err = exec_command(module, "configure terminal")
    if rc != 0:
        module.fail_json(msg="unable to enter configuration mode", err=err)

    failed = False
    for command in to_list(commands):
        if command == "end":
            pass

        rc, out, err = exec_command(module, command)
        if rc != 0:
            failed = True
            break

    if failed:
        exec_command(module, "abort")
        module.fail_json(msg=err, commands=commands, rc=rc)

    rc, diff, err = exec_command(module, "show commit changes diff")
    if commit:
        cmd = "commit"
        if comment:
            cmd += " comment {0}".format(comment)
    else:
        cmd = "abort"
        diff = None
    exec_command(module, cmd)

    return diff


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_YEHiix/ansible_module_iosxr_system.py", line 269, in <module>
main()
File "/tmp/ansible_YEHiix/ansible_module_iosxr_system.py", line 262, in main
if response.get('diff') and module._diff:
AttributeError: 'str' object has no attribute 'get'

# Fixed code
def load_config(module, commands, commit=False, replace=False, comment=None):
    rc, out, err = exec_command(module, "configure terminal")
    if rc != 0:
        module.fail_json(msg="unable to enter configuration mode", err=err)

    failed = False
    for command in to_list(commands):
        if command == "end":
            continue

        rc, out, err = exec_command(module, command)
        if rc != 0:
            failed = True
            break

    if failed:
        exec_command(module, "abort")
        module.fail_json(msg=err, commands=commands, rc=rc)

    rc, diff, err = exec_command(module, "show commit changes diff")
    if commit:
        cmd = "commit"
        if comment:
            cmd += " comment {0}".format(comment)
    else:
        cmd = "abort"
        diff = None
    exec_command(module, cmd)

    return diff
# Buggy code
def main():
    """Main entry point for Ansible module execution"""
    argument_spec = dict(
        hostname=dict(),
        domain_name=dict(),
        domain_search=dict(type="list"),
        name_servers=dict(type="list"),
        lookup_source=dict(),
        lookup_enabled=dict(type="bool"),
        state=dict(choices=["present", "absent"], default="present"),
    )

    argument_spec.update(iosxr_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)

    result = {"changed": False, "warnings": warnings}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(want, have, module)
    result["commands"] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get("diff") and module._diff:
            result["diff"] = {"prepared": response.get("diff")}
        result["changed"] = True

    module.exit_json(**result)


# Traceback (AttributeError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_YEHiix/ansible_module_iosxr_system.py", line 269, in <module>
main()
File "/tmp/ansible_YEHiix/ansible_module_iosxr_system.py", line 262, in main
if response.get('diff') and module._diff:
AttributeError: 'str' object has no attribute 'get'

# Fixed code
def main():
    """Main entry point for Ansible module execution"""
    argument_spec = dict(
        hostname=dict(),
        domain_name=dict(),
        domain_search=dict(type="list"),
        name_servers=dict(type="list"),
        lookup_source=dict(),
        lookup_enabled=dict(type="bool"),
        state=dict(choices=["present", "absent"], default="present"),
    )

    argument_spec.update(iosxr_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)

    result = {"changed": False, "warnings": warnings}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(want, have, module)
    result["commands"] = commands

    if commands:
        if not module.check_mode:
            load_config(module, commands, commit=True)
        result["changed"] = True

    module.exit_json(**result)
# Buggy code
def __init__(self, conditional, encoding=None):
    self.raw = conditional
    self.encoding = encoding or "json"

    try:
        key, op, val = shlex.split(conditional)
    except ValueError:
        raise ValueError("failed to parse conditional")

    self.key = key
    self.func = self._func(op)
    self.value = self._cast_value(val)


# Traceback (ValueError)
[WARNING]: Removed unexpected internal key in module return: _ansible_parsed = False

An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 250, in <module>
main()
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 208, in main
commands = parse_commands(module, warnings)
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 164, in parse_commands
commands = transform(module.params['commands'])
File "/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py", line 150, in __call__
File "/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py", line 135, in __call__
ValueError: output must be one of text, json, got xml

fatal: [vsrx01]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 250, in <module>\n    main()\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 208, in main\n    commands = parse_commands(module, warnings)\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 164, in parse_commands\n    commands = transform(module.params['commands'])\n  File \"/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py\", line 150, in __call__\n  File \"/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py\", line 135, in __call__\nValueError: output must be one of text, json, got xml\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def __init__(self, conditional, encoding=None):
    self.raw = conditional

    try:
        key, op, val = shlex.split(conditional)
    except ValueError:
        raise ValueError("failed to parse conditional")

    self.key = key
    self.func = self._func(op)
    self.value = self._cast_value(val)
# Buggy code
def get_value(self, result):
    if self.encoding in ["json", "text"]:
        try:
            return self.get_json(result)
        except (IndexError, TypeError, AttributeError):
            msg = "unable to apply conditional to result"
            raise FailedConditionalError(msg, self.raw)

    elif self.encoding == "xml":
        return self.get_xml(result.get("result"))


# Traceback (ValueError)
[WARNING]: Removed unexpected internal key in module return: _ansible_parsed = False

An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 250, in <module>
main()
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 208, in main
commands = parse_commands(module, warnings)
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 164, in parse_commands
commands = transform(module.params['commands'])
File "/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py", line 150, in __call__
File "/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py", line 135, in __call__
ValueError: output must be one of text, json, got xml

fatal: [vsrx01]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 250, in <module>\n    main()\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 208, in main\n    commands = parse_commands(module, warnings)\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 164, in parse_commands\n    commands = transform(module.params['commands'])\n  File \"/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py\", line 150, in __call__\n  File \"/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py\", line 135, in __call__\nValueError: output must be one of text, json, got xml\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def get_value(self, result):
    try:
        return self.get_json(result)
    except (IndexError, TypeError, AttributeError):
        msg = "unable to apply conditional to result"
        raise FailedConditionalError(msg, self.raw)
# Buggy code
def _sanitize(self, resp, obj=None):
    """Removes elements from the response before returning to the caller"""
    cleaned = []
    command = obj.get("command") if obj else None
    for line in resp.splitlines():
        if (command and line.startswith(command.strip())) or self._find_prompt(line):
            continue
        cleaned.append(line)
    return str("\n".join(cleaned)).strip()


# Traceback (ValueError)
[WARNING]: Removed unexpected internal key in module return: _ansible_parsed = False

An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 250, in <module>
main()
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 208, in main
commands = parse_commands(module, warnings)
File "/tmp/ansible_CHppt1/ansible_module_junos_command.py", line 164, in parse_commands
commands = transform(module.params['commands'])
File "/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py", line 150, in __call__
File "/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py", line 135, in __call__
ValueError: output must be one of text, json, got xml

fatal: [vsrx01]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 250, in <module>\n    main()\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 208, in main\n    commands = parse_commands(module, warnings)\n  File \"/tmp/ansible_CHppt1/ansible_module_junos_command.py\", line 164, in parse_commands\n    commands = transform(module.params['commands'])\n  File \"/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py\", line 150, in __call__\n  File \"/tmp/ansible_CHppt1/ansible_modlib.zip/ansible/module_utils/network_common.py\", line 135, in __call__\nValueError: output must be one of text, json, got xml\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def _sanitize(self, resp, obj=None):
    """Removes elements from the response before returning to the caller"""
    cleaned = []
    command = obj.get("command") if obj else None
    for line in resp.splitlines():
        if (
            command and line.startswith(command.strip())
        ) or self._matched_prompt.strip() in line:
            continue
        cleaned.append(line)
    return str("\n".join(cleaned)).strip()
# Buggy code
def get_connection(module):
    global _DEVICE_CONNECTION
    if not _DEVICE_CONNECTION:
        load_params(module)
        if "transport" not in module.params:
            conn = Cli(module)
        elif module.params["transport"] == "eapi":
            conn = Eapi(module)
        else:
            conn = Cli(module)
        _DEVICE_CONNECTION = conn
    return _DEVICE_CONNECTION


# Traceback (TypeError)
[WARNING]: Removed unexpected internal key in module return: _ansible_parsed = False

An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_dG8x1A/ansible_module_eos_command.py", line 240, in <module>
main()
File "/tmp/ansible_dG8x1A/ansible_module_eos_command.py", line 210, in main
responses = run_commands(module, commands)
File "/tmp/ansible_dG8x1A/ansible_modlib.zip/ansible/module_utils/eos.py", line 426, in run_commands
File "/tmp/ansible_dG8x1A/ansible_modlib.zip/ansible/module_utils/eos.py", line 145, in run_commands
File "/tmp/ansible_dG8x1A/ansible_modlib.zip/ansible/module_utils/eos.py", line 110, in exec_command
File "/tmp/ansible_dG8x1A/ansible_modlib.zip/ansible/module_utils/connection.py", line 60, in exec_command
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
TypeError: argument must be string or read-only character buffer, not None

fatal: [veos01]: FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_dG8x1A/ansible_module_eos_command.py\", line 240, in <module>\n    main()\n  File \"/tmp/ansible_dG8x1A/ansible_module_eos_command.py\", line 210, in main\n    responses = run_commands(module, commands)\n  File \"/tmp/ansible_dG8x1A/ansible_modlib.zip/ansible/module_utils/eos.py\", line 426, in run_commands\n  File \"/tmp/ansible_dG8x1A/ansible_modlib.zip/ansible/module_utils/eos.py\", line 145, in run_commands\n  File \"/tmp/ansible_dG8x1A/ansible_modlib.zip/ansible/module_utils/eos.py\", line 110, in exec_command\n  File \"/tmp/ansible_dG8x1A/ansible_modlib.zip/ansible/module_utils/connection.py\", line 60, in exec_command\n  File \"/usr/lib/python2.7/socket.py\", line 228, in meth\n    return getattr(self._sock,name)(*args)\nTypeError: argument must be string or read-only character buffer, not None\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def get_connection(module):
    global _DEVICE_CONNECTION
    if not _DEVICE_CONNECTION:
        load_params(module)
        transport = module.params["transport"]
        provider_transport = (module.params["provider"] or {}).get("transport")
        if "eapi" in (transport, provider_transport):
            conn = Eapi(module)
        else:
            conn = Cli(module)
        _DEVICE_CONNECTION = conn
    return _DEVICE_CONNECTION
# Buggy code
def create(module):
    vdc_name = module.params["vdc_name"]
    vapp_name = module.params["vapp_name"]
    template_name = module.params["template_name"]
    catalog_name = module.params["catalog_name"]
    network_name = module.params["network_name"]
    network_mode = module.params["network_mode"]
    vm_name = module.params["vm_name"]
    vm_cpus = module.params["vm_cpus"]
    vm_memory = module.params["vm_memory"]
    deploy = module.params["state"] == "deploy"
    poweron = module.params["operation"] == "poweron"

    task = module.vca.create_vapp(
        vdc_name,
        vapp_name,
        template_name,
        catalog_name,
        network_name,
        network_mode,
        vm_name,
        vm_cpus,
        vm_memory,
        deploy,
        poweron,
    )

    module.vca.block_until_completed(task)


# Traceback (AttributeError)
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/var/folders/ws/r0hq3mp13hj6bz9gy0tkwt580000gr/T/ansible_MJF6FG/ansible_module_vca_vapp.py", line 282, in <module>
main()
File "/var/folders/ws/r0hq3mp13hj6bz9gy0tkwt580000gr/T/ansible_MJF6FG/ansible_module_vca_vapp.py", line 263, in main
create(module)
File "/var/folders/ws/r0hq3mp13hj6bz9gy0tkwt580000gr/T/ansible_MJF6FG/ansible_module_vca_vapp.py", line 188, in create
module.vca.block_until_completed(task)
File "/usr/local/lib/python2.7/site-packages/pyvcloud/vcloudair.py", line 959, in block_until_completed
progress = task.get_Progress()
AttributeError: 'bool' object has no attribute 'get_Progress'

# Fixed code
def create(module):
    vdc_name = module.params["vdc_name"]
    vapp_name = module.params["vapp_name"]
    template_name = module.params["template_name"]
    catalog_name = module.params["catalog_name"]
    network_name = module.params["network_name"]
    network_mode = module.params["network_mode"]
    vm_name = module.params["vm_name"]
    vm_cpus = module.params["vm_cpus"]
    vm_memory = module.params["vm_memory"]
    deploy = module.params["state"] == "deploy"
    poweron = module.params["operation"] == "poweron"

    task = module.vca.create_vapp(
        vdc_name,
        vapp_name,
        template_name,
        catalog_name,
        network_name,
        network_mode,
        vm_name,
        vm_cpus,
        vm_memory,
        deploy,
        poweron,
    )

    if task is False:
        module.fail("Failed to create vapp: " + vapp_name)

    module.vca.block_until_completed(task)
# Buggy code
def read_sysctl_file(self):
    lines = []
    if os.path.isfile(self.sysctl_file):
        try:
            f = open(self.sysctl_file, "r")
            lines = f.readlines()
            f.close()
        except IOError:
            e = get_exception()
            self.module.fail_json(
                msg="Failed to open %s: %s" % (self.sysctl_file, str(e))
            )

    for line in lines:
        line = line.strip()
        self.file_lines.append(line)

        # don't split empty lines or comments
        if not line or line.startswith("#"):
            continue

        k, v = line.split("=", 1)
        k = k.strip()
        v = v.strip()
        self.file_values[k] = v.strip()


# Traceback (ValueError)
Traceback (most recent call last):
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 371, in <module>
main()
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 364, in main
result = SysctlModule(module)
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 124, in __init__
self.process()
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 144, in process
self.read_sysctl_file()
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 296, in read_sysctl_file
k, v = line.split('=',1)
ValueError: need more than 1 value to unpack

# Fixed code
def read_sysctl_file(self):
    lines = []
    if os.path.isfile(self.sysctl_file):
        try:
            f = open(self.sysctl_file, "r")
            lines = f.readlines()
            f.close()
        except IOError:
            e = get_exception()
            self.module.fail_json(
                msg="Failed to open %s: %s" % (self.sysctl_file, str(e))
            )

    for line in lines:
        line = line.strip()
        self.file_lines.append(line)

        # don't split empty lines or comments
        if not line or line.startswith(("#", ";")):
            continue

        k, v = line.split("=", 1)
        k = k.strip()
        v = v.strip()
        self.file_values[k] = v.strip()
# Buggy code
def fix_lines(self):
    checked = []
    self.fixed_lines = []
    for line in self.file_lines:
        if not line.strip() or line.strip().startswith("#"):
            self.fixed_lines.append(line)
            continue
        tmpline = line.strip()
        k, v = line.split("=", 1)
        k = k.strip()
        v = v.strip()
        if k not in checked:
            checked.append(k)
            if k == self.args["name"]:
                if self.args["state"] == "present":
                    new_line = "%s=%s\n" % (k, self.args["value"])
                    self.fixed_lines.append(new_line)
            else:
                new_line = "%s=%s\n" % (k, v)
                self.fixed_lines.append(new_line)

    if self.args["name"] not in checked and self.args["state"] == "present":
        new_line = "%s=%s\n" % (self.args["name"], self.args["value"])
        self.fixed_lines.append(new_line)


# Traceback (ValueError)
Traceback (most recent call last):
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 371, in <module>
main()
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 364, in main
result = SysctlModule(module)
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 124, in __init__
self.process()
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 144, in process
self.read_sysctl_file()
File \"/tmp/ansible_skBeie/ansible_module_sysctl.py\", line 296, in read_sysctl_file
k, v = line.split('=',1)
ValueError: need more than 1 value to unpack

# Fixed code
def fix_lines(self):
    checked = []
    self.fixed_lines = []
    for line in self.file_lines:
        if not line.strip() or line.strip().startswith(("#", ";")):
            self.fixed_lines.append(line)
            continue
        tmpline = line.strip()
        k, v = line.split("=", 1)
        k = k.strip()
        v = v.strip()
        if k not in checked:
            checked.append(k)
            if k == self.args["name"]:
                if self.args["state"] == "present":
                    new_line = "%s=%s\n" % (k, self.args["value"])
                    self.fixed_lines.append(new_line)
            else:
                new_line = "%s=%s\n" % (k, v)
                self.fixed_lines.append(new_line)

    if self.args["name"] not in checked and self.args["state"] == "present":
        new_line = "%s=%s\n" % (self.args["name"], self.args["value"])
        self.fixed_lines.append(new_line)