gurudesh/pytracebugs huggingface dataset:
# Buggy code
def load_current_config(self):
    self._current_config = dict()
    lag_types = set([lag_obj["type"] for lag_obj in self._required_config])
    for lag_type in lag_types:
        if_type = self.IF_TYPE_MAP[lag_type]
        lag_summary = self._get_port_channels(if_type)
        if lag_summary:
            self._parse_port_channels_summary(lag_type, lag_summary)


# Traceback (AttributeError)
TASK [leaf1 : configure MLag port channel with server 1] *************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: AttributeError: 'list' object has no attribute 'get'
fatal: [leaf1]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n File \"/tmp/ansible_C2lxdf/ansible_module_onyx_linkagg.py\", line 338, in <module>\n main()\n File \"/tmp/ansible_C2lxdf/ansible_module_onyx_linkagg.py\", line 334, in main\n OnyxLinkAggModule.main()\n File \"/tmp/ansible_C2lxdf/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 240, in main\n File \"/tmp/ansible_C2lxdf/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 218, in run\n File \"/tmp/ansible_C2lxdf/ansible_module_onyx_linkagg.py\", line 248, in load_current_config\n self._parse_port_channels_summary(lag_type, lag_summary)\n File \"/tmp/ansible_C2lxdf/ansible_module_onyx_linkagg.py\", line 228, in _parse_port_channels_summary\n lag_summary = lag_summary.get('MLAG Port-Channel Summary', {})\nAttributeError: 'list' object has no attribute 'get'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
to retry, use: --limit @/etc/ansible/site.retry

# Fixed code
def load_current_config(self):
    self._current_config = dict()
    self._os_version = self._get_os_version()
    lag_types = set([lag_obj["type"] for lag_obj in self._required_config])
    for lag_type in lag_types:
        if_type = self.IF_TYPE_MAP[lag_type]
        lag_summary = self._get_port_channels(if_type)
        if lag_summary:
            self._parse_port_channels_summary(lag_type, lag_summary)
# Buggy code
def load_current_config(self):
    # called in base class in run function
    self._current_config = dict()
    pfc_config = self._get_pfc_config()
    if not pfc_config:
        return
    if "Table 2" in pfc_config:
        pfc_config = pfc_config["Table 2"]
    for if_name, if_pfc_data in iteritems(pfc_config):
        match = self.PFC_IF_REGEX.match(if_name)
        if not match:
            continue
        if if_pfc_data:
            if_pfc_data = if_pfc_data[0]
            self._current_config[if_name] = self._create_if_pfc_data(
                if_name, if_pfc_data
            )


# Traceback (AttributeError)
<swi60> EXEC /bin/sh -c 'rm -f -r /root/.ansible/tmp/ansible-tmp-1520431892.25-242550331138460/ > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_gof89B/ansible_module_onyx_pfc_interface.py", line 205, in <module>
main()
File "/tmp/ansible_gof89B/ansible_module_onyx_pfc_interface.py", line 201, in main
OnyxPfcInterfaceModule.main()
File "/tmp/ansible_gof89B/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py", line 229, in main
File "/tmp/ansible_gof89B/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py", line 207, in run
File "/tmp/ansible_gof89B/ansible_module_onyx_pfc_interface.py", line 149, in load_current_config
for if_name, if_pfc_data in iteritems(pfc_config):
File "/tmp/ansible_gof89B/ansible_modlib.zip/ansible/module_utils/six/__init__.py", line 610, in iteritems
AttributeError: 'list' object has no attribute 'iteritems'

# Fixed code
def load_current_config(self):
    # called in base class in run function
    self._os_version = self._get_os_version()
    self._current_config = dict()
    pfc_config = self._get_pfc_config()
    if not pfc_config:
        return
    if self._os_version >= self.ONYX_API_VERSION:
        if len(pfc_config) >= 3:
            pfc_config = pfc_config[2]
        else:
            pfc_config = dict()
    else:
        if "Table 2" in pfc_config:
            pfc_config = pfc_config["Table 2"]

    for if_name, if_pfc_data in iteritems(pfc_config):
        match = self.PFC_IF_REGEX.match(if_name)
        if not match:
            continue
        if if_pfc_data:
            if_pfc_data = if_pfc_data[0]
            self._current_config[if_name] = self._create_if_pfc_data(
                if_name, if_pfc_data
            )
# Buggy code
def execute(self, cmd, timeout=200, capture_output=True):
    """
    Executes a HAProxy command by sending a message to a HAProxy's local
    UNIX socket and waiting up to 'timeout' milliseconds for the response.
    """
    self.client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    self.client.connect(self.socket)
    self.client.sendall("%s\n" % cmd)
    result = ""
    buf = ""
    buf = self.client.recv(RECV_SIZE)
    while buf:
        result += buf
        buf = self.client.recv(RECV_SIZE)
    if capture_output:
        self.capture_command_output(cmd, result.strip())
    self.client.close()
    return result


# Traceback (nTypeError)
fatal: [managed-host]: FAILED! => {"changed": false, "failed": true, "module_stderr": "Connection to 192.168.57.101 closed.\r\n", "module_stdout": "\r\nTraceback (most recent call last):\r\n  File \"/tmp/ansible_28dmn_55/ansible_module_haproxy.py\", line 454, in <module>\r\n    main()\r\n  File \"/tmp/ansible_28dmn_55/ansible_module_haproxy.py\", line 450, in main\r\n    ansible_haproxy.act()\r\n  File \"/tmp/ansible_28dmn_55/ansible_module_haproxy.py\", line 399, in act\r\n    state_before = self.get_state_for(self.backend, self.host)\r\n  File \"/tmp/ansible_28dmn_55/ansible_module_haproxy.py\", line 330, in get_state_for\r\n    data = self.execute('show stat', 200, False).lstrip('# ')\r\n  File \"/tmp/ansible_28dmn_55/ansible_module_haproxy.py\", line 254, in execute\r\n    self.client.sendall('%s\\n' % cmd)\r\nTypeError: a bytes-like object is required, not 'str'\r\n", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def execute(self, cmd, timeout=200, capture_output=True):
    """
    Executes a HAProxy command by sending a message to a HAProxy's local
    UNIX socket and waiting up to 'timeout' milliseconds for the response.
    """
    self.client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    self.client.connect(self.socket)
    self.client.sendall(to_bytes("%s\n" % cmd))

    result = b""
    buf = b""
    buf = self.client.recv(RECV_SIZE)
    while buf:
        result += buf
        buf = self.client.recv(RECV_SIZE)
    result = to_text(result, errors="surrogate_or_strict")

    if capture_output:
        self.capture_command_output(cmd, result.strip())
    self.client.close()
    return result
# Buggy code
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            source_region=dict(required=True),
            source_image_id=dict(required=True),
            name=dict(default="default"),
            description=dict(default=""),
            encrypted=dict(type="bool", default=False, required=False),
            kms_key_id=dict(type="str", required=False),
            wait=dict(type="bool", default=False),
            wait_timeout=dict(default=1200),
            tags=dict(type="dict"),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
    ec2 = boto3_conn(
        module,
        conn_type="client",
        resource="ec2",
        region=region,
        endpoint=ec2_url,
        **aws_connect_params,
    )

    copy_image(module, ec2)


# Traceback (WaiterError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_8b2dUL/ansible_module_ec2_ami_copy.py", line 176, in copy_image
ec2.get_waiter('image_available').wait(ImageIds=[image_id])
File "/usr/lib/python2.7/site-packages/botocore/waiter.py", line 53, in wait
Waiter.wait(self, **kwargs)
File "/usr/lib/python2.7/site-packages/botocore/waiter.py", line 329, in wait
last_response=response
WaiterError: Waiter ImageAvailable failed: Max attempts exceeded

fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"invocation": {
"module_args": {
"aws_access_key": null,
"aws_secret_key": null,
"description": "",
"ec2_url": null,
"encrypted": false,
"kms_key_id": null,
"name": "test_ami",
"profile": null,
"region": "us-west-2",
"security_token": null,
"source_image_id": "ami-93fc00hh",
"source_region": "us-east-1",
"validate_certs": true,
"wait": true,
"wait_timeout": "1200"
}
},
"msg": "An error occurred waiting for the image to become available. (Waiter ImageAvailable failed: Max attempts exceeded)"
}

# Fixed code
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(
            source_region=dict(required=True),
            source_image_id=dict(required=True),
            name=dict(default="default"),
            description=dict(default=""),
            encrypted=dict(type="bool", default=False, required=False),
            kms_key_id=dict(type="str", required=False),
            wait=dict(type="bool", default=False),
            wait_timeout=dict(type="int", default=600),
            tags=dict(type="dict"),
        )
    )

    module = AnsibleModule(argument_spec=argument_spec)

    region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
    ec2 = boto3_conn(
        module,
        conn_type="client",
        resource="ec2",
        region=region,
        endpoint=ec2_url,
        **aws_connect_params,
    )

    copy_image(module, ec2)
# Buggy code
def __init__(self):
    self._module = None
    self._commands = list()
    self._current_config = None
    self._required_config = None


# Traceback (nAttributeError)
fatal: [swi60]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 201, in <module>\n    main()\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 197, in main\n    OnyxVlanModule.main()\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 229, in main\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 207, in run\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 161, in load_current_config\n    self._create_vlan_data(vlan_id, vlan_data)\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 143, in _create_vlan_data\n    'name': self.get_config_attr(vlan_data, 'Name')\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 183, in get_config_attr\nAttributeError: 'list' object has no attribute 'get'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1

# Fixed code
def __init__(self):
    self._module = None
    self._commands = list()
    self._current_config = None
    self._required_config = None
    self._os_version = None
# Buggy code
def _create_vlan_data(self, vlan_id, vlan_data):
    return {"vlan_id": vlan_id, "name": self.get_config_attr(vlan_data, "Name")}


# Traceback (nAttributeError)
fatal: [swi60]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 201, in <module>\n    main()\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 197, in main\n    OnyxVlanModule.main()\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 229, in main\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 207, in run\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 161, in load_current_config\n    self._create_vlan_data(vlan_id, vlan_data)\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 143, in _create_vlan_data\n    'name': self.get_config_attr(vlan_data, 'Name')\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 183, in get_config_attr\nAttributeError: 'list' object has no attribute 'get'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1

# Fixed code
def _create_vlan_data(self, vlan_id, vlan_data):
    if self._os_version >= self.ONYX_API_VERSION:
        vlan_data = vlan_data[0]
    return {"vlan_id": vlan_id, "name": self.get_config_attr(vlan_data, "Name")}
# Buggy code
def load_current_config(self):
    # called in base class in run function
    self._current_config = dict()
    vlan_config = self._get_vlan_config()
    if not vlan_config:
        return
    for vlan_id, vlan_data in iteritems(vlan_config):
        try:
            vlan_id = int(vlan_id)
        except ValueError:
            continue
        self._current_config[vlan_id] = self._create_vlan_data(vlan_id, vlan_data)


# Traceback (nAttributeError)
fatal: [swi60]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 201, in <module>\n    main()\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 197, in main\n    OnyxVlanModule.main()\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 229, in main\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 207, in run\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 161, in load_current_config\n    self._create_vlan_data(vlan_id, vlan_data)\n  File \"/tmp/ansible_pkMA4U/ansible_module_onyx_vlan.py\", line 143, in _create_vlan_data\n    'name': self.get_config_attr(vlan_data, 'Name')\n  File \"/tmp/ansible_pkMA4U/ansible_modlib.zip/ansible/module_utils/network/onyx/onyx.py\", line 183, in get_config_attr\nAttributeError: 'list' object has no attribute 'get'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1

# Fixed code
def load_current_config(self):
    # called in base class in run function
    self._os_version = self._get_os_version()
    self._current_config = dict()
    vlan_config = self._get_vlan_config()
    if not vlan_config:
        return
    for vlan_id, vlan_data in iteritems(vlan_config):
        try:
            vlan_id = int(vlan_id)
        except ValueError:
            continue
        self._current_config[vlan_id] = self._create_vlan_data(vlan_id, vlan_data)
# Buggy code
def download(self, artifact, filename=None):
    filename = artifact.get_filename(filename)
    if not artifact.version or artifact.version == "latest":
        artifact = Artifact(
            artifact.group_id,
            artifact.artifact_id,
            self.find_latest_version_available(artifact),
            artifact.classifier,
            artifact.extension,
        )

    url = self.find_uri_for_artifact(artifact)
    result = True
    if not self.verify_md5(filename, url + ".md5"):
        response = self._request(
            url, "Failed to download artifact " + str(artifact), lambda r: r
        )
        if response:
            f = open(filename, "wb")
            self._write_chunks(response, f, report_hook=self.chunk_report)
            f.close()
        else:
            result = False
    return result


# Traceback (ValueError)
failed: [myhost] (item={u'version': 3.2, u'group': u'asm', u'name': u'asm'}) => {"changed": false, "failed": true, "item": {"group": "asm", "name": "asm", "version": 3.2}, "module_stderr": "Shared connection to myhost closed.
", "module_stdout": "Traceback (most recent call last):
File \"/tmp/ansible_bQHxvE/ansible_module_maven_artifact.py\", line 499, in <module>
main()
File \"/tmp/ansible_bQHxvE/ansible_module_maven_artifact.py\", line 476, in main
if os.path.lexists(b_dest) and downloader.verify_md5(dest, downloader.find_uri_for_artifact(artifact) + '.md5'):
File \"/tmp/ansible_bQHxvE/ansible_module_maven_artifact.py\", line 390, in verify_md5\
remote = self._request(remote_md5, \"Failed to download MD5\", lambda r: r.read())
File \"/tmp/ansible_bQHxvE/ansible_module_maven_artifact.py\", line 333, in _request
raise ValueError(failmsg + \" because of \" + info['msg'] + \"for URL \" + url_to_use)
ValueError: Failed to download MD5 because of HTTP Error 404: Not Foundfor URL http://artifactory.url/maven/asm/asm/3.2/asm-3.2.jar.md5
", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def download(self, artifact, verify_download, filename=None):
    filename = artifact.get_filename(filename)
    if not artifact.version or artifact.version == "latest":
        artifact = Artifact(
            artifact.group_id,
            artifact.artifact_id,
            self.find_latest_version_available(artifact),
            artifact.classifier,
            artifact.extension,
        )
    url = self.find_uri_for_artifact(artifact)
    error = None
    response = self._request(
        url, "Failed to download artifact " + str(artifact), lambda r: r
    )
    if response:
        f = open(filename, "wb")
        self._write_chunks(response, f, report_hook=self.chunk_report)
        f.close()
        with open(filename, "wb") as f:
            self._write_chunks(response, f, report_hook=self.chunk_report)

        if verify_download and not self.verify_md5(filename, url + ".md5"):
            # if verify_change was set, the previous file would be deleted
            os.remove(filename)
            error = "Checksum verification failed"
        else:
            error = None
    else:
        error = "Error downloading artifact " + str(artifact)
    return error
# Buggy code
def get_user_data(self):
    user_data = self.module.params.get("user_data")
    if user_data is not None:
        user_data = base64.b64encode(str(user_data))
    return user_data


# Traceback (TypeError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: TypeError: a bytes-like object is required, not 'str'
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_j03a0m9f/ansible_module_cs_instance.py\", line 1088, in <module>\n    main()\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_j03a0m9f/ansible_module_cs_instance.py\", line 1068, in main\n    acs_instance.present_instance()\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_j03a0m9f/ansible_module_cs_instance.py\", line 668, in present_instance\n    instance = self.update_instance(instance=instance, start_vm=start_vm)\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_j03a0m9f/ansible_module_cs_instance.py\", line 765, in update_instance\n    args_instance_update['userdata'] = self.get_user_data()\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_j03a0m9f/ansible_module_cs_instance.py\", line 682, in get_user_data\n    user_data = base64.b64encode(str(user_data))\n  File \"/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/base64.py\", line 58, in b64encode\n    encoded = binascii.b2a_base64(s, newline=False)\nTypeError: a bytes-like object is required, not 'str'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def get_user_data(self):
    user_data = self.module.params.get("user_data")
    if user_data is not None:
        user_data = to_text(base64.b64encode(to_bytes(user_data)))
    return user_data
# Buggy code
def _get_instance_user_data(self, instance):
    # Query the user data if we need to
    if "userdata" in instance:
        return instance["userdata"]

    user_data = ""
    if self.get_user_data() is not None:
        res = self.query_api(
            "getVirtualMachineUserData", virtualmachineid=instance["id"]
        )
        user_data = res["virtualmachineuserdata"].get("userdata", "")
    return user_data


# Traceback (KeyError)
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: KeyError: 'id'
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_b9HigX/ansible_module_cs_instance.py\", line 1088, in <module>\n    main()\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_b9HigX/ansible_module_cs_instance.py\", line 1078, in main\n    result = acs_instance.get_result(instance)\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_b9HigX/ansible_module_cs_instance.py\", line 973, in get_result\n    self.result['user_data'] = self._get_instance_user_data(instance)\n  File \"/var/folders/75/8jzhscr56j13rv6tj6805ch40000gn/T/ansible_b9HigX/ansible_module_cs_instance.py\", line 544, in _get_instance_user_data\n    res = self.cs.getVirtualMachineUserData(virtualmachineid=instance['id'])\nKeyError: 'id'\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

# Fixed code
def _get_instance_user_data(self, instance):
    # Query the user data if we need to
    if "userdata" in instance:
        return instance["userdata"]

    user_data = ""
    if self.get_user_data() is not None and instance.get("id"):
        res = self.query_api(
            "getVirtualMachineUserData", virtualmachineid=instance["id"]
        )
        user_data = res["virtualmachineuserdata"].get("userdata", "")
    return user_data
# Buggy code
def download(self, artifact, filename=None):
    filename = artifact.get_filename(filename)
    if not artifact.version or artifact.version == "latest":
        artifact = Artifact(
            artifact.group_id,
            artifact.artifact_id,
            self.find_latest_version_available(artifact),
            artifact.classifier,
            artifact.extension,
        )

    url = self.find_uri_for_artifact(artifact)
    result = True
    if not self.verify_md5(filename, url + ".md5"):
        response = self._request(
            url, "Failed to download artifact " + str(artifact), lambda r: r
        )
        if response:
            f = open(filename, "w")
            # f.write(response.read())
            self._write_chunks(response, f, report_hook=self.chunk_report)
            f.close()
        else:
            result = False
    return result


# Traceback (nAttributeError)
failed: [default] (item={u'group_id': u'<group_id>', u'artifact_id': u'<artifact>', u'version': u'<version>'}) => {"changed": false, "item": {"artifact_id": "<artifact>", "group_id": "<group_id>", "version": "<version>"}, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 499, in <module>\n    main()\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 481, in main\n    if downloader.download(artifact, b_dest):\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 350, in download\n    self._write_chunks(response, f, report_hook=self.chunk_report)\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 368, in _write_chunks\n    total_size = response.info().getheader('Content-Length').strip()\nAttributeError: 'HTTPMessage' object has no attribute 'getheader'\nShared connection to 127.0.0.1 closed.\r\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def download(self, artifact, filename=None):
    filename = artifact.get_filename(filename)
    if not artifact.version or artifact.version == "latest":
        artifact = Artifact(
            artifact.group_id,
            artifact.artifact_id,
            self.find_latest_version_available(artifact),
            artifact.classifier,
            artifact.extension,
        )

    url = self.find_uri_for_artifact(artifact)
    result = True
    if not self.verify_md5(filename, url + ".md5"):
        response = self._request(
            url, "Failed to download artifact " + str(artifact), lambda r: r
        )
        if response:
            f = open(filename, "wb")
            self._write_chunks(response, f, report_hook=self.chunk_report)
            f.close()
        else:
            result = False
    return result
# Buggy code
def _write_chunks(self, response, file, chunk_size=8192, report_hook=None):
    total_size = response.info().getheader("Content-Length").strip()
    total_size = int(total_size)
    bytes_so_far = 0

    while 1:
        chunk = response.read(chunk_size)
        bytes_so_far += len(chunk)

        if not chunk:
            break

        file.write(chunk)
        if report_hook:
            report_hook(bytes_so_far, chunk_size, total_size)

    return bytes_so_far


# Traceback (nAttributeError)
failed: [default] (item={u'group_id': u'<group_id>', u'artifact_id': u'<artifact>', u'version': u'<version>'}) => {"changed": false, "item": {"artifact_id": "<artifact>", "group_id": "<group_id>", "version": "<version>"}, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 499, in <module>\n    main()\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 481, in main\n    if downloader.download(artifact, b_dest):\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 350, in download\n    self._write_chunks(response, f, report_hook=self.chunk_report)\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 368, in _write_chunks\n    total_size = response.info().getheader('Content-Length').strip()\nAttributeError: 'HTTPMessage' object has no attribute 'getheader'\nShared connection to 127.0.0.1 closed.\r\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def _write_chunks(self, response, filehandle, chunk_size=8192, report_hook=None):
    total_size = response.info().get("Content-Length").strip()
    total_size = int(total_size)
    bytes_so_far = 0

    while True:
        chunk = response.read(chunk_size)
        bytes_so_far += len(chunk)

        if not chunk:
            break

        filehandle.write(chunk)
        if report_hook:
            report_hook(bytes_so_far, chunk_size, total_size)

    return bytes_so_far
# Buggy code
def download(self, artifact, filename=None):
    filename = artifact.get_filename(filename)
    if not artifact.version or artifact.version == "latest":
        artifact = Artifact(
            artifact.group_id,
            artifact.artifact_id,
            self.find_latest_version_available(artifact),
            artifact.classifier,
            artifact.extension,
        )

    url = self.find_uri_for_artifact(artifact)
    if not self.verify_md5(filename, url + ".md5"):
        response = self._request(
            url, "Failed to download artifact " + str(artifact), lambda r: r
        )
        if response:
            f = open(filename, "w")
            # f.write(response.read())
            self._write_chunks(response, f, report_hook=self.chunk_report)
            f.close()
            return True
        else:
            return False
    else:
        return True


# Traceback (nAttributeError)
failed: [default] (item={u'group_id': u'<group_id>', u'artifact_id': u'<artifact>', u'version': u'<version>'}) => {"changed": false, "item": {"artifact_id": "<artifact>", "group_id": "<group_id>", "version": "<version>"}, "module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 499, in <module>\n    main()\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 481, in main\n    if downloader.download(artifact, b_dest):\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 350, in download\n    self._write_chunks(response, f, report_hook=self.chunk_report)\n  File \"/tmp/ansible_58_aoltx/ansible_module_maven_artifact.py\", line 368, in _write_chunks\n    total_size = response.info().getheader('Content-Length').strip()\nAttributeError: 'HTTPMessage' object has no attribute 'getheader'\nShared connection to 127.0.0.1 closed.\r\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}

# Fixed code
def download(self, artifact, filename=None):
    filename = artifact.get_filename(filename)
    if not artifact.version or artifact.version == "latest":
        artifact = Artifact(
            artifact.group_id,
            artifact.artifact_id,
            self.find_latest_version_available(artifact),
            artifact.classifier,
            artifact.extension,
        )

    url = self.find_uri_for_artifact(artifact)
    if not self.verify_md5(filename, url + ".md5"):
        response = self._request(
            url, "Failed to download artifact " + str(artifact), lambda r: r
        )
        if response:
            f = open(filename, "wb")
            self._write_chunks(response, f, report_hook=self.chunk_report)
            f.close()
            return True
        else:
            return False
    else:
        return True
# Buggy code
def get_diff(w, have):
    c = deepcopy(w)
    del c["interfaces"]
    del c["name"]
    del c["associated_interfaces"]
    for o in have:
        del o["interfaces"]
        del o["name"]
        if o["vlan_id"] == w["vlan_id"]:
            diff_dict = dict(set(c.items()) - set(o.items()))
            return diff_dict


# Traceback (KeyError)
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_pzr6W4/ansible_module_nxos_vlan.py", line 567, in <module>
main()
File "/tmp/ansible_pzr6W4/ansible_module_nxos_vlan.py", line 552, in main
commands = map_obj_to_commands((want, have), module, os_platform)
File "/tmp/ansible_pzr6W4/ansible_module_nxos_vlan.py", line 273, in map_obj_to_commands
diff = get_diff(w, have)
File "/tmp/ansible_pzr6W4/ansible_module_nxos_vlan.py", line 181, in get_diff
del o['interfaces']
KeyError: 'interfaces'

fatal: [nxos9k-01]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_pzr6W4/ansible_module_nxos_vlan.py\", line 567, in <module>\n    main()\n  File \"/tmp/ansible_pzr6W4/ansible_module_nxos_vlan.py\", line 552, in main\n    commands = map_obj_to_commands((want, have), module, os_platform)\n  File \"/tmp/ansible_pzr6W4/ansible_module_nxos_vlan.py\", line 273, in map_obj_to_commands\n    diff = get_diff(w, have)\n  File \"/tmp/ansible_pzr6W4/ansible_module_nxos_vlan.py\", line 181, in get_diff\n    del o['interfaces']\nKeyError: 'interfaces'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}

# Fixed code
def get_diff(w, obj):
    c = deepcopy(w)
    entries = ("interfaces", "associated_interfaces", "name", "delay", "vlan_range")
    for key in entries:
        if key in c:
            del c[key]

    o = deepcopy(obj)
    del o["interfaces"]
    del o["name"]
    if o["vlan_id"] == w["vlan_id"]:
        diff_dict = dict(set(c.items()) - set(o.items()))
        return diff_dict
# Buggy code
def execute_show_command(command, module):
    provider = module.params["provider"]
    if provider["transport"] == "cli":
        if "show port-channel summary" in command:
            command += " | json"
        cmds = [command]
        body = run_commands(module, cmds)
    elif provider["transport"] == "nxapi":
        cmds = [command]
        body = run_commands(module, cmds)

    return body


# Traceback (TypeError)
Traceback (most recent call last):
File "/var/folders/jv/29pmt_2j39ngz8ftz40j1mn00000gn/T/ansible_bc8MeK/ansible_module_nxos_linkagg.py", line 411, in <module>
main()
File "/var/folders/jv/29pmt_2j39ngz8ftz40j1mn00000gn/T/ansible_bc8MeK/ansible_module_nxos_linkagg.py", line 398, in main
have = map_config_to_obj(module)
File "/var/folders/jv/29pmt_2j39ngz8ftz40j1mn00000gn/T/ansible_bc8MeK/ansible_module_nxos_linkagg.py", line 337, in map_config_to_obj
output = execute_show_command('show port-channel summary', module)[0]
File "/var/folders/jv/29pmt_2j39ngz8ftz40j1mn00000gn/T/ansible_bc8MeK/ansible_module_nxos_linkagg.py", line 143, in execute_show_command
if provider['transport'] == 'cli':
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def execute_show_command(command, module):
    device_info = get_capabilities(module)
    network_api = device_info.get("network_api", "nxapi")

    if network_api == "cliconf":
        if "show port-channel summary" in command:
            command += " | json"
        cmds = [command]
        body = run_commands(module, cmds)
    elif network_api == "nxapi":
        cmds = [command]
        body = run_commands(module, cmds)

    return body
# Buggy code
def get_verification_attributes(connection, module, identity):
    response = call_and_handle_errors(
        module, connection.get_identity_verification_attributes, Identities=[identity]
    )
    identity_verification = response["VerificationAttributes"]
    if identity not in identity_verification:
        return None
    return identity_verification[identity]


# Traceback (TypeError)
Traceback (most recent call last):
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 448, in <module>
main()
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 443, in main
create_or_update_identity(connection, module, region, account_id)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 372, in create_or_update_identity
notifications_changed, notification_attributes = update_identity_notifications(connection, module)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 347, in update_identity_notifications
changed |= update_notification_topic(connection, module, identity, identity_notifications, notification_type)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 275, in update_notification_topic
if topic_key in identity_notifications:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def get_verification_attributes(connection, module, identity, retries=0, retryDelay=10):
    # Unpredictably get_identity_verification_attributes doesn't include the identity even when we've
    # just registered it. Suspect this is an eventual consistency issue on AWS side.
    # Don't want this complexity exposed users of the module as they'd have to retry to ensure
    # a consistent return from the module.
    # To avoid this we have an internal retry that we use only after registering the identity.
    for attempt in range(0, retries + 1):
        response = call_and_handle_errors(
            module,
            connection.get_identity_verification_attributes,
            Identities=[identity],
        )
        identity_verification = response["VerificationAttributes"]
        if identity in identity_verification:
            break
        time.sleep(retryDelay)
    if identity not in identity_verification:
        return None
    return identity_verification[identity]
# Buggy code
def update_notification_topic(
    connection, module, identity, identity_notifications, notification_type
):
    arg_dict = module.params.get(notification_type.lower() + "_notifications")
    topic_key = notification_type + "Topic"
    if topic_key in identity_notifications:
        current = identity_notifications[topic_key]
    else:
        current = None

    if arg_dict is not None and "topic" in arg_dict:
        required = arg_dict["topic"]
    else:
        required = None

    if current != required:
        call_and_handle_errors(
            module,
            connection.set_identity_notification_topic,
            Identity=identity,
            NotificationType=notification_type,
            SnsTopic=required,
        )
        return True
    return False


# Traceback (TypeError)
Traceback (most recent call last):
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 448, in <module>
main()
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 443, in main
create_or_update_identity(connection, module, region, account_id)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 372, in create_or_update_identity
notifications_changed, notification_attributes = update_identity_notifications(connection, module)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 347, in update_identity_notifications
changed |= update_notification_topic(connection, module, identity, identity_notifications, notification_type)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 275, in update_notification_topic
if topic_key in identity_notifications:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def update_notification_topic(
    connection, module, identity, identity_notifications, notification_type
):
    arg_dict = module.params.get(notification_type.lower() + "_notifications")
    topic_key = notification_type + "Topic"
    if identity_notifications is None:
        # If there is no configuration for notifications cannot be being sent to topics
        # hence assume None as the current state.
        current = None
    elif topic_key in identity_notifications:
        current = identity_notifications[topic_key]
    else:
        # If there is information on the notifications setup but no information on the
        # particular notification topic it's pretty safe to assume there's no topic for
        # this notification. AWS API docs suggest this information will always be
        # included but best to be defensive
        current = None

    if arg_dict is not None and "topic" in arg_dict:
        required = arg_dict["topic"]
    else:
        required = None

    if current != required:
        call_and_handle_errors(
            module,
            connection.set_identity_notification_topic,
            Identity=identity,
            NotificationType=notification_type,
            SnsTopic=required,
        )
        return True
    return False
# Buggy code
def update_notification_topic_headers(
    connection, module, identity, identity_notifications, notification_type
):
    arg_dict = module.params.get(notification_type.lower() + "_notifications")
    header_key = "HeadersIn" + notification_type + "NotificationsEnabled"
    if header_key in identity_notifications:
        current = identity_notifications[header_key]
    else:
        current = False

    if arg_dict is not None and "include_headers" in arg_dict:
        required = arg_dict["include_headers"]
    else:
        required = False

    if current != required:
        call_and_handle_errors(
            module,
            connection.set_identity_headers_in_notifications_enabled,
            Identity=identity,
            NotificationType=notification_type,
            Enabled=required,
        )
        return True
    return False


# Traceback (TypeError)
Traceback (most recent call last):
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 448, in <module>
main()
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 443, in main
create_or_update_identity(connection, module, region, account_id)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 372, in create_or_update_identity
notifications_changed, notification_attributes = update_identity_notifications(connection, module)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 347, in update_identity_notifications
changed |= update_notification_topic(connection, module, identity, identity_notifications, notification_type)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 275, in update_notification_topic
if topic_key in identity_notifications:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def update_notification_topic_headers(
    connection, module, identity, identity_notifications, notification_type
):
    arg_dict = module.params.get(notification_type.lower() + "_notifications")
    header_key = "HeadersIn" + notification_type + "NotificationsEnabled"
    if identity_notifications is None:
        # If there is no configuration for topic notifications, headers cannot be being
        # forwarded, hence assume false.
        current = False
    elif header_key in identity_notifications:
        current = identity_notifications[header_key]
    else:
        # AWS API doc indicates that the headers in fields are optional. Unfortunately
        # it's not clear on what this means. But it's a pretty safe assumption that it means
        # headers are not included since most API consumers would interpret absence as false.
        current = False

    if arg_dict is not None and "include_headers" in arg_dict:
        required = arg_dict["include_headers"]
    else:
        required = False

    if current != required:
        call_and_handle_errors(
            module,
            connection.set_identity_headers_in_notifications_enabled,
            Identity=identity,
            NotificationType=notification_type,
            Enabled=required,
        )
        return True
    return False
# Buggy code
def update_feedback_forwarding(connection, module, identity, identity_notifications):
    if "ForwardingEnabled" in identity_notifications:
        current = identity_notifications["ForwardingEnabled"]
    else:
        current = False

    required = module.params.get("feedback_forwarding")

    if current != required:
        call_and_handle_errors(
            module,
            connection.set_identity_feedback_forwarding_enabled,
            Identity=identity,
            ForwardingEnabled=required,
        )
        return True
    return False


# Traceback (TypeError)
Traceback (most recent call last):
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 448, in <module>
main()
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 443, in main
create_or_update_identity(connection, module, region, account_id)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 372, in create_or_update_identity
notifications_changed, notification_attributes = update_identity_notifications(connection, module)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 347, in update_identity_notifications
changed |= update_notification_topic(connection, module, identity, identity_notifications, notification_type)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 275, in update_notification_topic
if topic_key in identity_notifications:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def update_feedback_forwarding(connection, module, identity, identity_notifications):
    if identity_notifications is None:
        # AWS requires feedback forwarding to be enabled unless bounces and complaints
        # are being handled by SNS topics. So in the absence of identity_notifications
        # information existing feedback forwarding must be on.
        current = True
    elif "ForwardingEnabled" in identity_notifications:
        current = identity_notifications["ForwardingEnabled"]
    else:
        # If there is information on the notifications setup but no information on the
        # forwarding state it's pretty safe to assume forwarding is off. AWS API docs
        # suggest this information will always be included but best to be defensive
        current = False

    required = module.params.get("feedback_forwarding")

    if current != required:
        call_and_handle_errors(
            module,
            connection.set_identity_feedback_forwarding_enabled,
            Identity=identity,
            ForwardingEnabled=required,
        )
        return True
    return False
# Buggy code
def update_identity_notifications(connection, module):
    identity = module.params.get("identity")
    changed = False
    identity_notifications = get_identity_notifications(connection, module, identity)

    for notification_type in ("Bounce", "Complaint", "Delivery"):
        changed |= update_notification_topic(
            connection, module, identity, identity_notifications, notification_type
        )
        changed |= update_notification_topic_headers(
            connection, module, identity, identity_notifications, notification_type
        )

    changed |= update_feedback_forwarding(
        connection, module, identity, identity_notifications
    )

    if changed:
        identity_notifications = get_identity_notifications(
            connection, module, identity
        )
    return changed, identity_notifications


# Traceback (TypeError)
Traceback (most recent call last):
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 448, in <module>
main()
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 443, in main
create_or_update_identity(connection, module, region, account_id)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 372, in create_or_update_identity
notifications_changed, notification_attributes = update_identity_notifications(connection, module)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 347, in update_identity_notifications
changed |= update_notification_topic(connection, module, identity, identity_notifications, notification_type)
File "/tmp/ansible_FTBGdl/ansible_module_aws_ses_identity.py", line 275, in update_notification_topic
if topic_key in identity_notifications:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def update_identity_notifications(connection, module):
    identity = module.params.get("identity")
    changed = False
    identity_notifications = get_identity_notifications(connection, module, identity)

    for notification_type in ("Bounce", "Complaint", "Delivery"):
        changed |= update_notification_topic(
            connection, module, identity, identity_notifications, notification_type
        )
        changed |= update_notification_topic_headers(
            connection, module, identity, identity_notifications, notification_type
        )

    changed |= update_feedback_forwarding(
        connection, module, identity, identity_notifications
    )

    if changed or identity_notifications is None:
        identity_notifications = get_identity_notifications(
            connection, module, identity, retries=4
        )
    return changed, identity_notifications
# Buggy code
def map_config_to_obj(module):
    objs = []
    output = run_commands(module, ["show vlan"])
    lines = output[0].strip().splitlines()[2:]

    for l in lines:
        splitted_line = re.split(r"\s{2,}", l.strip())
        obj = {}
        obj["vlan_id"] = splitted_line[0]
        obj["name"] = splitted_line[1]
        obj["state"] = splitted_line[2]

        if obj["state"] == "suspended":
            obj["state"] = "suspend"

        obj["interfaces"] = []
        if len(splitted_line) > 3:
            for i in splitted_line[3].split(","):
                obj["interfaces"].append(i.strip().replace("Et", "ethernet"))

        objs.append(obj)

    return objs


# Traceback (IndexError)
The full traceback is:
Traceback (most recent call last):
File "/var/folders/d8/pkl369kn44z2vxsrnzxkwfydn2t_cc/T/ansible_E6bJX6/ansible_module_eos_vlan.py", line 321, in <module>
main()
File "/var/folders/d8/pkl369kn44z2vxsrnzxkwfydn2t_cc/T/ansible_E6bJX6/ansible_module_eos_vlan.py", line 300, in main
have = map_config_to_obj(module)
File "/var/folders/d8/pkl369kn44z2vxsrnzxkwfydn2t_cc/T/ansible_E6bJX6/ansible_module_eos_vlan.py", line 205, in map_config_to_obj
obj['name'] = splitted_line[1]
IndexError: list index out of range

fatal: [a05-25-1-sw-oob]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/var/folders/d8/pkl369kn44z2vxsrnzxkwfydn2t_cc/T/ansible_E6bJX6/ansible_module_eos_vlan.py\", line 321, in <module>\n    main()\n  File \"/var/folders/d8/pkl369kn44z2vxsrnzxkwfydn2t_cc/T/ansible_E6bJX6/ansible_module_eos_vlan.py\", line 300, in main\n    have = map_config_to_obj(module)\n  File \"/var/folders/d8/pkl369kn44z2vxsrnzxkwfydn2t_cc/T/ansible_E6bJX6/ansible_module_eos_vlan.py\", line 205, in map_config_to_obj\n    obj['name'] = splitted_line[1]\nIndexError: list index out of range\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def map_config_to_obj(module):
    objs = []
    vlans = run_commands(module, ["show vlan conf | json"])

    for vlan in vlans[0]["vlans"]:
        obj = {}
        obj["vlan_id"] = vlan
        obj["name"] = vlans[0]["vlans"][vlan]["name"]
        obj["state"] = vlans[0]["vlans"][vlan]["status"]
        obj["interfaces"] = []

        interfaces = vlans[0]["vlans"][vlan]

        for interface in interfaces["interfaces"]:
            obj["interfaces"].append(interface)

        if obj["state"] == "suspended":
            obj["state"] = "suspend"

        objs.append(obj)

    return objs