gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _parse_openssl_req(csr_filename):
    """
    Parses openssl command line output, this is a workaround for M2Crypto's
    inability to get them from CSR objects.
    """
    if not salt.utils.path.which("openssl"):
        raise salt.exceptions.SaltInvocationError("openssl binary not found in path")
    cmd = "openssl req -text -noout -in {0}".format(csr_filename)

    output = __salt__["cmd.run_stdout"](cmd)

    output = re.sub(r": rsaEncryption", ":", output)
    output = re.sub(r"[0-9a-f]{2}:", "", output)

    return salt.utils.data.decode(salt.utils.yaml.safe_load(output))


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1014, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/state.py", line 1933, in call
**cdata['kwargs'])
File "/usr/lib/python3/dist-packages/salt/loader.py", line 1951, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python3/dist-packages/salt/states/x509.py", line 675, in crl_managed
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid, digest=digest, include_expired=include_expired)
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1019, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

# Fixed code
def _parse_openssl_req(csr_filename):
    """
    Parses openssl command line output, this is a workaround for M2Crypto's
    inability to get them from CSR objects.
    """
    if not salt.utils.path.which("openssl"):
        raise salt.exceptions.SaltInvocationError("openssl binary not found in path")
    cmd = "openssl req -text -noout -in {}".format(csr_filename)

    output = __salt__["cmd.run_stdout"](cmd)

    output = re.sub(r": rsaEncryption", ":", output)
    output = re.sub(r"[0-9a-f]{2}:", "", output)

    return salt.utils.data.decode(salt.utils.yaml.safe_load(output))
# Buggy code
def _dec2hex(decval):
    """
    Converts decimal values to nicely formatted hex strings
    """
    return _pretty_hex("{0:X}".format(decval))


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1014, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/state.py", line 1933, in call
**cdata['kwargs'])
File "/usr/lib/python3/dist-packages/salt/loader.py", line 1951, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python3/dist-packages/salt/states/x509.py", line 675, in crl_managed
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid, digest=digest, include_expired=include_expired)
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1019, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

# Fixed code
def _dec2hex(decval):
    """
    Converts decimal values to nicely formatted hex strings
    """
    return _pretty_hex("{:X}".format(decval))
# Buggy code
def read_crl(crl):
    """
    Returns a dict containing details of a certificate revocation list.
    Input can be a PEM string or file path.

    :depends:   - OpenSSL command line tool

    crl:
        A path or PEM encoded string containing the CRL to read.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.read_crl /etc/pki/mycrl.crl
    """
    text = _text_or_file(crl)
    text = get_pem_entry(text, pem_type="X509 CRL")

    crltempfile = tempfile.NamedTemporaryFile(delete=True)
    crltempfile.write(salt.utils.stringutils.to_bytes(text, encoding="ascii"))
    crltempfile.flush()
    crlparsed = _parse_openssl_crl(crltempfile.name)
    crltempfile.close()

    return crlparsed


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1014, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/state.py", line 1933, in call
**cdata['kwargs'])
File "/usr/lib/python3/dist-packages/salt/loader.py", line 1951, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python3/dist-packages/salt/states/x509.py", line 675, in crl_managed
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid, digest=digest, include_expired=include_expired)
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1019, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

# Fixed code
def read_crl(crl):
    """
    Returns a dict containing details of a certificate revocation list.
    Input can be a PEM string or file path.

    :depends:   - OpenSSL command line tool

    crl:
        A path or PEM encoded string containing the CRL to read.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.read_crl /etc/pki/mycrl.crl
    """
    text = _text_or_file(crl)
    text = get_pem_entry(text, pem_type="X509 CRL")

    crltempfile = tempfile.NamedTemporaryFile(delete=True)
    crltempfile.write(salt.utils.stringutils.to_bytes(text, encoding="ascii"))
    crltempfile.flush()
    crlparsed = _parse_openssl_crl(crltempfile.name)
    crltempfile.close()

    return crlparsed
# Buggy code
def get_signing_policy(signing_policy_name):
    """
    Returns the details of a names signing policy, including the text of
    the public key that will be used to sign it. Does not return the
    private key.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.get_signing_policy www
    """
    signing_policy = _get_signing_policy(signing_policy_name)
    if not signing_policy:
        return "Signing policy {0} does not exist.".format(signing_policy_name)
    if isinstance(signing_policy, list):
        dict_ = {}
        for item in signing_policy:
            dict_.update(item)
        signing_policy = dict_

    try:
        del signing_policy["signing_private_key"]
    except KeyError:
        pass

    try:
        signing_policy["signing_cert"] = get_pem_entry(
            signing_policy["signing_cert"], "CERTIFICATE"
        )
    except KeyError:
        pass

    return signing_policy


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1014, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/state.py", line 1933, in call
**cdata['kwargs'])
File "/usr/lib/python3/dist-packages/salt/loader.py", line 1951, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python3/dist-packages/salt/states/x509.py", line 675, in crl_managed
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid, digest=digest, include_expired=include_expired)
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1019, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

# Fixed code
def get_signing_policy(signing_policy_name):
    """
    Returns the details of a names signing policy, including the text of
    the public key that will be used to sign it. Does not return the
    private key.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.get_signing_policy www
    """
    signing_policy = _get_signing_policy(signing_policy_name)
    if not signing_policy:
        return "Signing policy {} does not exist.".format(signing_policy_name)
    if isinstance(signing_policy, list):
        dict_ = {}
        for item in signing_policy:
            dict_.update(item)
        signing_policy = dict_

    try:
        del signing_policy["signing_private_key"]
    except KeyError:
        pass

    try:
        signing_policy["signing_cert"] = get_pem_entry(
            signing_policy["signing_cert"], "CERTIFICATE"
        )
    except KeyError:
        pass

    return signing_policy
# Buggy code
def read_crl(crl):
    """
    Returns a dict containing details of a certificate revocation list.
    Input can be a PEM string or file path.

    :depends:   - OpenSSL command line tool

    crl:
        A path or PEM encoded string containing the CRL to read.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.read_crl /etc/pki/mycrl.crl
    """
    text = _text_or_file(crl)
    text = get_pem_entry(text, pem_type="X509 CRL")

    crltempfile = tempfile.NamedTemporaryFile(delete=True)
    crltempfile.write(salt.utils.stringutils.to_str(text))
    crltempfile.flush()
    crlparsed = _parse_openssl_crl(crltempfile.name)
    crltempfile.close()

    return crlparsed


# Traceback (TypeError)
An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1014, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/state.py", line 1933, in call
**cdata['kwargs'])
File "/usr/lib/python3/dist-packages/salt/loader.py", line 1951, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python3/dist-packages/salt/states/x509.py", line 675, in crl_managed
signing_cert=signing_cert, revoked=revoked, days_valid=days_valid, digest=digest, include_expired=include_expired)
File "/usr/lib/python3/dist-packages/salt/modules/x509.py", line 1019, in create_crl
crltext = crl.export(**export_kwargs)
File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 2230, in export
raise TypeError("digest must be provided")
TypeError: digest must be provided

# Fixed code
def read_crl(crl):
    """
    Returns a dict containing details of a certificate revocation list.
    Input can be a PEM string or file path.

    :depends:   - OpenSSL command line tool

    crl:
        A path or PEM encoded string containing the CRL to read.

    CLI Example:

    .. code-block:: bash

        salt '*' x509.read_crl /etc/pki/mycrl.crl
    """
    text = _text_or_file(crl)
    text = get_pem_entry(text, pem_type="X509 CRL")

    crltempfile = tempfile.NamedTemporaryFile(delete=True)
    crltempfile.write(salt.utils.stringutils.to_bytes(text, encoding="ascii"))
    crltempfile.flush()
    crlparsed = _parse_openssl_crl(crltempfile.name)
    crltempfile.close()

    return crlparsed
# Buggy code
def clean_args(args):
    """
    Cleans up the args that weren't passed in
    """
    for arg in args:
        if not args[arg]:
            del args[arg]
    return args


# Traceback (RuntimeError)
$ sudo salt host1.example.com genesis.mksls kickstart /tmp/anaconda-ks.cfg
host1.example.com:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/salt/minion.py", line 1870, in _thread_return
opts, data, func, args, kwargs
File "/usr/lib/python3.6/site-packages/salt/executors/direct_call.py", line 12, in execute
return func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/salt/modules/genesis.py", line 739, in mksls
return salt.utils.kickstart.mksls(src, dst)
File "/usr/lib/python3.6/site-packages/salt/utils/kickstart.py", line 927, in mksls
ks_opts["auth"] = parse_auth(line)
File "/usr/lib/python3.6/site-packages/salt/utils/kickstart.py", line 116, in parse_auth
args = clean_args(vars(parser.parse_args(rules)))
File "/usr/lib/python3.6/site-packages/salt/utils/kickstart.py", line 21, in clean_args
for arg in args:
RuntimeError: dictionary changed size during iteration

# Fixed code
def clean_args(args):
    """
    Cleans up the args that weren't passed in
    """
    for arg in list(args):
        if not args[arg]:
            del args[arg]
    return args
# Buggy code
def is_proxytype(opts, proxytype):
    """
    Is this a proxy minion of type proxytype
    """
    return (
        salt.utils.platform.is_proxy()
        and opts.get("proxy", None).get("proxytype", None) == proxytype
    )


# Traceback (NameError)
[ERROR   ] Failed to import grains esxi, this is due most likely to a syntax error:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/salt/loader.py", line 1685, in _load_module
mod = spec.loader.load_module()
File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper
File "<frozen importlib._bootstrap_external>", line 823, in load_module
File "<frozen importlib._bootstrap_external>", line 682, in load_module
File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
File "<frozen importlib._bootstrap>", line 684, in _load
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/usr/local/lib/python3.6/site-packages/salt/grains/esxi.py", line 18, in <module>
if salt.utils.platform.is_proxy() and __opts__["proxy"]["proxytype"] == "esxi":
NameError: name '__opts__' is not defined

# Fixed code
def is_proxytype(opts, proxytype):
    """
    Is this a proxy minion of type proxytype
    """
    return (
        salt.utils.platform.is_proxy()
        and opts.get("proxy", {}).get("proxytype", None) == proxytype
    )
# Buggy code
def makePickle(self, record):
    return self.format(record)


# Traceback (TypeError)
--- Logging error ---
Traceback (most recent call last):
File "/usr/lib/python3.6/logging/handlers.py", line 634, in emit
self.send(s)
File "/usr/lib/python3.6/logging/handlers.py", line 692, in send
self.sock.sendto(s, self.address)
TypeError: a bytes-like object is required, not 'str'

# Fixed code
def makePickle(self, record):
    return salt.utils.stringutils.to_bytes(self.format(record))
# Buggy code
def emit(self, record):
    formatted_object = self.format(record)
    self.publisher.send(formatted_object)


# Traceback (TypeError)
--- Logging error ---
Traceback (most recent call last):
File "/usr/lib/python3.6/logging/handlers.py", line 634, in emit
self.send(s)
File "/usr/lib/python3.6/logging/handlers.py", line 692, in send
self.sock.sendto(s, self.address)
TypeError: a bytes-like object is required, not 'str'

# Fixed code
def emit(self, record):
    formatted_object = salt.utils.stringutils.to_bytes(self.format(record))
    self.publisher.send(formatted_object)
# Buggy code
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.platform.is_windows():
        return "win_dns_client"
    return (False, "Module win_dns_client: module only works on Windows systems")


# Traceback (AttributeError)
2020-03-06 15:32:08,164 [salt.state       :322 ][ERROR   ][4036] An exception occurred in this state: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\state.py", line 1981, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\loader.py", line 1977, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\states\win_dns_client.py", line 48, in dns_exists
configured_list = __salt__['win_dns_client.get_dns_servers'](interface)
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\modules\win_dns_client.py", line 44, in get_dns_servers
with salt.utils.winapi.Com():
AttributeError: module 'salt.utils' has no attribute 'winapi'

# Fixed code
def __virtual__():
    """
    Only works on Windows systems
    """
    if not salt.utils.platform.is_windows():
        return False, "Module win_dns_client: module only works on Windows systems"
    if not HAS_LIBS:
        return False, "Module win_dns_client: missing required libraries"
    return "win_dns_client"
# Buggy code
def get_dns_servers(interface="Local Area Connection"):
    """
    Return a list of the configured DNS servers of the specified interface

    CLI Example:

    .. code-block:: bash

        salt '*' win_dns_client.get_dns_servers 'Local Area Connection'
    """
    # remove any escape characters
    interface = interface.split("\\")
    interface = "".join(interface)

    with salt.utils.winapi.Com():
        c = wmi.WMI()
        for iface in c.Win32_NetworkAdapter(NetEnabled=True):
            if interface == iface.NetConnectionID:
                iface_config = c.Win32_NetworkAdapterConfiguration(
                    Index=iface.Index
                ).pop()
                try:
                    return list(iface_config.DNSServerSearchOrder)
                except TypeError:
                    return []
    log.debug('Interface "%s" not found', interface)
    return False


# Traceback (AttributeError)
2020-03-06 15:32:08,164 [salt.state       :322 ][ERROR   ][4036] An exception occurred in this state: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\state.py", line 1981, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\loader.py", line 1977, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\states\win_dns_client.py", line 48, in dns_exists
configured_list = __salt__['win_dns_client.get_dns_servers'](interface)
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\modules\win_dns_client.py", line 44, in get_dns_servers
with salt.utils.winapi.Com():
AttributeError: module 'salt.utils' has no attribute 'winapi'

# Fixed code
def get_dns_servers(interface="Local Area Connection"):
    """
    Return a list of the configured DNS servers of the specified interface

    Args:
        interface (str): The name of the network interface. This is the name as
        it appears in the Control Panel under Network Connections

    Returns:
        list: A list of dns servers

    CLI Example:

    .. code-block:: bash

        salt '*' win_dns_client.get_dns_servers 'Local Area Connection'
    """
    # remove any escape characters
    interface = interface.split("\\")
    interface = "".join(interface)

    with salt.utils.winapi.Com():
        c = wmi.WMI()
        for iface in c.Win32_NetworkAdapter(NetEnabled=True):
            if interface == iface.NetConnectionID:
                iface_config = c.Win32_NetworkAdapterConfiguration(
                    Index=iface.Index
                ).pop()
                try:
                    return list(iface_config.DNSServerSearchOrder)
                except TypeError:
                    return []
    log.debug('Interface "%s" not found', interface)
    return False
# Buggy code
def get_dns_config(interface="Local Area Connection"):
    """
    Get the type of DNS configuration (dhcp / static)

    CLI Example:

    .. code-block:: bash

        salt '*' win_dns_client.get_dns_config 'Local Area Connection'
    """
    # remove any escape characters
    interface = interface.split("\\")
    interface = "".join(interface)

    with salt.utils.winapi.Com():
        c = wmi.WMI()
        for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
            if interface == iface.Description:
                return iface.DHCPEnabled


# Traceback (AttributeError)
2020-03-06 15:32:08,164 [salt.state       :322 ][ERROR   ][4036] An exception occurred in this state: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\state.py", line 1981, in call
**cdata['kwargs'])
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\loader.py", line 1977, in wrapper
return f(*args, **kwargs)
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\states\win_dns_client.py", line 48, in dns_exists
configured_list = __salt__['win_dns_client.get_dns_servers'](interface)
File "c:\salt\bin\lib\site-packages\salt-3000-py3.5.egg\salt\modules\win_dns_client.py", line 44, in get_dns_servers
with salt.utils.winapi.Com():
AttributeError: module 'salt.utils' has no attribute 'winapi'

# Fixed code
def get_dns_config(interface="Local Area Connection"):
    """
    Get the type of DNS configuration (dhcp / static).

    Args:
        interface (str): The name of the network interface. This is the
        Description in the Network Connection Details for the device

    Returns:
        bool: ``True`` if DNS is configured, otherwise ``False``

    CLI Example:

    .. code-block:: bash

        salt '*' win_dns_client.get_dns_config 'Local Area Connection'
    """
    # remove any escape characters
    interface = interface.split("\\")
    interface = "".join(interface)

    with salt.utils.winapi.Com():
        c = wmi.WMI()
        for iface in c.Win32_NetworkAdapterConfiguration(IPEnabled=1):
            if interface == iface.Description:
                return iface.DHCPEnabled
# Buggy code
def unsubscribe(self, tag, match_type=None):
    """
    Un-subscribe to events matching the passed tag.
    """
    if tag is None:
        return
    match_func = self._get_match_func(match_type)

    self.pending_tags.remove([tag, match_func])

    old_events = self.pending_events
    self.pending_events = []
    for evt in old_events:
        if any(
            pmatch_func(evt["tag"], ptag) for ptag, pmatch_func in self.pending_tags
        ):
            self.pending_events.append(evt)


# Traceback (ValueError)
leap151:/srv/salt # python3 apitest.py
Executing job with jid 20190810142659884529
-------------------------------------------

{
"leap151.asteras.cool": {
"ret": {
"test_|-test1_|-test1_|-succeed_with_changes": {
"name": "test1",
"changes": {
"testing": {
"old": "Unchanged",
"new": "Something pretended to change"
}
},
"result": true,
"comment": "Success!",
"__sls__": "test",
"__run_num__": 0,
"start_time": "14:27:00.036770",
"duration": 0.442,
"__id__": "test1"
}
},
"out": "highstate"
}
}
salt/job/20190810142659884529
Traceback (most recent call last):
File "apitest.py", line 12, in
for server in returned :
File "/usr/lib/python3.6/site-packages/salt/client/__init__.py", line 987, in get_cli_returns
self._clean_up_subscriptions(jid)
File "/usr/lib/python3.6/site-packages/salt/client/__init__.py", line 1866, in _clean_up_subscriptions
self.event.unsubscribe('salt/job/{0}'.format(job_id))
File "/usr/lib/python3.6/site-packages/salt/utils/event.py", line 355, in unsubscribe
self.pending_tags.remove([tag, match_func])
ValueError: list.remove(x): x not in list

# Fixed code
def unsubscribe(self, tag, match_type=None):
    """
    Un-subscribe to events matching the passed tag.
    """
    if tag is None:
        return
    match_func = self._get_match_func(match_type)

    try:
        self.pending_tags.remove([tag, match_func])
    except ValueError:
        pass

    old_events = self.pending_events
    self.pending_events = []
    for evt in old_events:
        if any(
            pmatch_func(evt["tag"], ptag) for ptag, pmatch_func in self.pending_tags
        ):
            self.pending_events.append(evt)
# Buggy code
def paged_object_to_list(paged_object):
    """
    Extract all pages within a paged object as a list of dictionaries
    """
    paged_return = []
    while True:
        try:
            page = next(paged_object)
            paged_return.append(page.as_dict())
        except CloudError:
            raise
        except StopIteration:
            break

    return paged_return


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/salt/cloud/__init__.py", line 67, in _call
ret = func(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/salt/cloud/__init__.py", line 2294, in create_multiprocessing
local_master=parallel_data['local_master']
File "/usr/lib/python3.6/site-packages/salt/cloud/__init__.py", line 1253, in create
output = self.clouds[func](vm_)
File "/usr/lib/python3.6/site-packages/salt/cloud/clouds/azurearm.py", line 1404, in create
vm_request = request_instance(vm_=vm_)
File "/usr/lib/python3.6/site-packages/salt/cloud/clouds/azurearm.py", line 1167, in request_instance
volume['lun'],
TypeError: __init__() takes 1 positional argument but 2 were given

# Fixed code
def paged_object_to_list(paged_object):
    """
    Extract all pages within a paged object as a list of dictionaries
    """
    paged_return = []
    while True:
        try:
            page = next(paged_object)
            paged_return.append(page.as_dict())
        except StopIteration:
            break

    return paged_return
# Buggy code
def get_enabled(root=None):
    """
    Return a list of all enabled services

    root
        Enable/disable/mask unit files in the specified root directory

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_enabled
    """
    ret = set()
    # Get enabled systemd units. Can't use --state=enabled here because it's
    # not present until systemd 216.
    out = __salt__["cmd.run"](
        _systemctl_cmd("--full --no-legend --no-pager list-unit-files", root=root),
        python_shell=False,
        ignore_retcode=True,
    )
    for line in salt.utils.itertools.split(out, "\n"):
        try:
            fullname, unit_state = line.strip().split(None, 1)
        except ValueError:
            continue
        else:
            if unit_state != "enabled":
                continue
        try:
            unit_name, unit_type = fullname.rsplit(".", 1)
        except ValueError:
            continue
        if unit_type in VALID_UNIT_TYPES:
            ret.add(unit_name if unit_type == "service" else fullname)

    # Add in any sysvinit services that are enabled
    ret.update(set([x for x in _get_sysv_services(root) if _sysv_enabled(x, root)]))
    return sorted(ret)


# Traceback (AssertionError)
Traceback (most recent call last):
File "/tmp/kitchen/testing/tests/integration/modules/test_linux_service.py", line 130, in test_service_disable
self.assertIn(self.service_name, self.run_function("service.get_disabled"))
AssertionError: 'sshd' not found in []

# Fixed code
def get_enabled(root=None):
    """
    Return a list of all enabled services

    root
        Enable/disable/mask unit files in the specified root directory

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_enabled
    """
    ret = set()
    # Get enabled systemd units. Can't use --state=enabled here because it's
    # not present until systemd 216.
    out = __salt__["cmd.run"](
        _systemctl_cmd("--full --no-legend --no-pager list-unit-files", root=root),
        python_shell=False,
        ignore_retcode=True,
    )
    for line in salt.utils.itertools.split(out, "\n"):
        try:
            fullname, unit_state = line.strip().split(None, 1)
        except ValueError:
            continue
        else:
            # Arch Linux adds a third column, which we want to ignore
            if unit_state.split()[0] != "enabled":
                continue
        try:
            unit_name, unit_type = fullname.rsplit(".", 1)
        except ValueError:
            continue
        if unit_type in VALID_UNIT_TYPES:
            ret.add(unit_name if unit_type == "service" else fullname)

    # Add in any sysvinit services that are enabled
    ret.update(set([x for x in _get_sysv_services(root) if _sysv_enabled(x, root)]))
    return sorted(ret)
# Buggy code
def get_disabled(root=None):
    """
    Return a list of all disabled services

    root
        Enable/disable/mask unit files in the specified root directory

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_disabled
    """
    ret = set()
    # Get disabled systemd units. Can't use --state=disabled here because it's
    # not present until systemd 216.
    out = __salt__["cmd.run"](
        _systemctl_cmd("--full --no-legend --no-pager list-unit-files", root=root),
        python_shell=False,
        ignore_retcode=True,
    )
    for line in salt.utils.itertools.split(out, "\n"):
        try:
            fullname, unit_state = line.strip().split(None, 1)
        except ValueError:
            continue
        else:
            if unit_state != "disabled":
                continue
        try:
            unit_name, unit_type = fullname.rsplit(".", 1)
        except ValueError:
            continue
        if unit_type in VALID_UNIT_TYPES:
            ret.add(unit_name if unit_type == "service" else fullname)

    # Add in any sysvinit services that are disabled
    ret.update(set([x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)]))
    return sorted(ret)


# Traceback (AssertionError)
Traceback (most recent call last):
File "/tmp/kitchen/testing/tests/integration/modules/test_linux_service.py", line 130, in test_service_disable
self.assertIn(self.service_name, self.run_function("service.get_disabled"))
AssertionError: 'sshd' not found in []

# Fixed code
def get_disabled(root=None):
    """
    Return a list of all disabled services

    root
        Enable/disable/mask unit files in the specified root directory

    CLI Example:

    .. code-block:: bash

        salt '*' service.get_disabled
    """
    ret = set()
    # Get disabled systemd units. Can't use --state=disabled here because it's
    # not present until systemd 216.
    out = __salt__["cmd.run"](
        _systemctl_cmd("--full --no-legend --no-pager list-unit-files", root=root),
        python_shell=False,
        ignore_retcode=True,
    )
    for line in salt.utils.itertools.split(out, "\n"):
        try:
            fullname, unit_state = line.strip().split(None, 1)
        except ValueError:
            continue
        else:
            # Arch Linux adds a third column, which we want to ignore
            if unit_state.split()[0] != "disabled":
                continue
        try:
            unit_name, unit_type = fullname.rsplit(".", 1)
        except ValueError:
            continue
        if unit_type in VALID_UNIT_TYPES:
            ret.add(unit_name if unit_type == "service" else fullname)

    # Add in any sysvinit services that are disabled
    ret.update(set([x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)]))
    return sorted(ret)
# Buggy code
def orchestrate(
    mods, saltenv="base", test=None, exclude=None, pillar=None, pillarenv=None
):
    """
    .. versionadded:: 2016.11.0

    Execute the orchestrate runner from a masterless minion.

    .. seealso:: More Orchestrate documentation

        * :ref:`Full Orchestrate Tutorial <orchestrate-runner>`
        * :py:mod:`Docs for the ``salt`` state module <salt.states.saltmod>`

    CLI Examples:

    .. code-block:: bash

        salt-call --local state.orchestrate webserver
        salt-call --local state.orchestrate webserver saltenv=dev test=True
        salt-call --local state.orchestrate webserver saltenv=dev pillarenv=aws
    """
    return _orchestrate(
        mods=mods,
        saltenv=saltenv,
        test=test,
        exclude=exclude,
        pillar=pillar,
        pillarenv=pillarenv,
    )


# Traceback (KeyError)
----------
ID: zsh_fail_1
Function: cmd.run
Name: echo hey
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/modules/cmdmod.py", line 442, in _run
pwd.getpwnam(runas)
KeyError: "getpwnam(): name not found: 'cristi'"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/state.py", line 1981, in call
**cdata['kwargs'])
File "/usr/lib/python3/dist-packages/salt/loader.py", line 1977, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python3/dist-packages/salt/states/cmd.py", line 892, in run
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
File "/usr/lib/python3/dist-packages/salt/states/cmd.py", line 366, in mod_run_check
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
File "/usr/lib/python3/dist-packages/salt/modules/cmdmod.py", line 2277, in retcode
**kwargs)
File "/usr/lib/python3/dist-packages/salt/modules/cmdmod.py", line 445, in _run
'User \'{0}\' is not available'.format(runas)
salt.exceptions.CommandExecutionError: User 'cristi' is not available
Started: 11:52:32.097022
Duration: 9.035 ms
Changes:
----------
ID: zsh_test_1
Function: cmd.run
Name: echo "t1"
Result: True
Comment: Command "echo "t1"" run
Started: 11:52:32.106490
Duration: 37.838 ms
Changes:
----------
pid:
30057
retcode:
0
stderr:
stdout:
t1

# Fixed code
def orchestrate(
    mods, saltenv="base", test=None, exclude=None, pillar=None, pillarenv=None
):
    """
    .. versionadded:: 2016.11.0

    Execute the orchestrate runner from a masterless minion.

    .. seealso:: More Orchestrate documentation

        * :ref:`Full Orchestrate Tutorial <orchestrate-runner>`
        * Docs for the salt state module :py:mod:`salt.states.saltmod`

    CLI Examples:

    .. code-block:: bash

        salt-call --local state.orchestrate webserver
        salt-call --local state.orchestrate webserver saltenv=dev test=True
        salt-call --local state.orchestrate webserver saltenv=dev pillarenv=aws
    """
    return _orchestrate(
        mods=mods,
        saltenv=saltenv,
        test=test,
        exclude=exclude,
        pillar=pillar,
        pillarenv=pillarenv,
    )
# Buggy code
def wait_call(
    name,
    func,
    args=(),
    kws=None,
    onlyif=None,
    unless=None,
    creates=None,
    stateful=False,
    use_vt=False,
    output_loglevel="debug",
    hide_output=False,
    **kwargs,
):
    # Ignoring our arguments is intentional.
    return {"name": name, "changes": {}, "result": True, "comment": ""}


# Traceback (KeyError)
----------
ID: zsh_fail_1
Function: cmd.run
Name: echo hey
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/modules/cmdmod.py", line 442, in _run
pwd.getpwnam(runas)
KeyError: "getpwnam(): name not found: 'cristi'"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/state.py", line 1981, in call
**cdata['kwargs'])
File "/usr/lib/python3/dist-packages/salt/loader.py", line 1977, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python3/dist-packages/salt/states/cmd.py", line 892, in run
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
File "/usr/lib/python3/dist-packages/salt/states/cmd.py", line 366, in mod_run_check
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
File "/usr/lib/python3/dist-packages/salt/modules/cmdmod.py", line 2277, in retcode
**kwargs)
File "/usr/lib/python3/dist-packages/salt/modules/cmdmod.py", line 445, in _run
'User \'{0}\' is not available'.format(runas)
salt.exceptions.CommandExecutionError: User 'cristi' is not available
Started: 11:52:32.097022
Duration: 9.035 ms
Changes:
----------
ID: zsh_test_1
Function: cmd.run
Name: echo "t1"
Result: True
Comment: Command "echo "t1"" run
Started: 11:52:32.106490
Duration: 37.838 ms
Changes:
----------
pid:
30057
retcode:
0
stderr:
stdout:
t1

# Fixed code
def wait_call(
    name,
    func,
    args=(),
    kws=None,
    stateful=False,
    use_vt=False,
    output_loglevel="debug",
    hide_output=False,
    **kwargs,
):
    # Ignoring our arguments is intentional.
    return {"name": name, "changes": {}, "result": True, "comment": ""}
# Buggy code
def write_secret(path, **kwargs):
    """
    Set secret at the path in vault. The vault policy used must allow this.

    CLI Example:

    .. code-block:: bash

            salt '*' vault.write_secret "secret/my/secret" user="foo" password="bar"
    """
    log.debug("Writing vault secrets for %s at %s", __grains__["id"], path)
    data = dict([(x, y) for x, y in kwargs.items() if not x.startswith("__")])
    try:
        url = "v1/{0}".format(path)
        response = __utils__["vault.make_request"]("POST", url, json=data)
        if response.status_code == 200:
            return response.json()["data"]
        elif response.status_code != 204:
            response.raise_for_status()
        return True
    except Exception as err:  # pylint: disable=broad-except
        log.error("Failed to write secret! %s: %s", type(err).__name__, err)
        return False


# Traceback (CommandExecutionError)
$ sudo salt-run sdb.get 'sdb://sdb_vault/secret/data/salt/pillar_data/wew'
[ERROR   ] Failed to read secret! KeyError: u'wew'
Exception occurred in runner sdb.get: Traceback (most recent call last):
File "/opt/saltstack/lib/python2.7/site-packages/salt/client/mixins.py", line 387, in _low
data['return'] = self.functions[fun](*args, **kwargs)
File "/opt/saltstack/lib/python2.7/site-packages/salt/runners/sdb.py", line 27, in get
return salt.utils.sdb.sdb_get(uri, __opts__, __utils__)
File "/opt/saltstack/lib/python2.7/site-packages/salt/utils/sdb.py", line 46, in sdb_get
return loaded_db[fun](query, profile=profile)
File "/opt/saltstack/lib/python2.7/site-packages/salt/sdb/vault.py", line 122, in get
raise salt.exceptions.CommandExecutionError(e)
CommandExecutionError: u'wew'
[INFO    ] Runner completed: 20181023165316837868

# Fixed code
def write_secret(path, **kwargs):
    """
    Set secret at the path in vault. The vault policy used must allow this.

    CLI Example:

    .. code-block:: bash

            salt '*' vault.write_secret "secret/my/secret" user="foo" password="bar"
    """
    log.debug("Writing vault secrets for %s at %s", __grains__["id"], path)
    data = dict([(x, y) for x, y in kwargs.items() if not x.startswith("__")])
    version2 = __utils__["vault.is_v2"](path)
    if version2["v2"]:
        path = version2["data"]
        data = {"data": data}
    try:
        url = "v1/{0}".format(path)
        response = __utils__["vault.make_request"]("POST", url, json=data)
        if response.status_code == 200:
            return response.json()["data"]
        elif response.status_code != 204:
            response.raise_for_status()
        return True
    except Exception as err:  # pylint: disable=broad-except
        log.error("Failed to write secret! %s: %s", type(err).__name__, err)
        return False
# Buggy code
def write_raw(path, raw):
    """
    Set raw data at the path in vault. The vault policy used must allow this.

    CLI Example:

    .. code-block:: bash

            salt '*' vault.write_raw "secret/my/secret" '{"user":"foo","password": "bar"}'
    """
    log.debug("Writing vault secrets for %s at %s", __grains__["id"], path)
    try:
        url = "v1/{0}".format(path)
        response = __utils__["vault.make_request"]("POST", url, json=raw)
        if response.status_code == 200:
            return response.json()["data"]
        elif response.status_code != 204:
            response.raise_for_status()
        return True
    except Exception as err:  # pylint: disable=broad-except
        log.error("Failed to write secret! %s: %s", type(err).__name__, err)
        return False


# Traceback (CommandExecutionError)
$ sudo salt-run sdb.get 'sdb://sdb_vault/secret/data/salt/pillar_data/wew'
[ERROR   ] Failed to read secret! KeyError: u'wew'
Exception occurred in runner sdb.get: Traceback (most recent call last):
File "/opt/saltstack/lib/python2.7/site-packages/salt/client/mixins.py", line 387, in _low
data['return'] = self.functions[fun](*args, **kwargs)
File "/opt/saltstack/lib/python2.7/site-packages/salt/runners/sdb.py", line 27, in get
return salt.utils.sdb.sdb_get(uri, __opts__, __utils__)
File "/opt/saltstack/lib/python2.7/site-packages/salt/utils/sdb.py", line 46, in sdb_get
return loaded_db[fun](query, profile=profile)
File "/opt/saltstack/lib/python2.7/site-packages/salt/sdb/vault.py", line 122, in get
raise salt.exceptions.CommandExecutionError(e)
CommandExecutionError: u'wew'
[INFO    ] Runner completed: 20181023165316837868

# Fixed code
def write_raw(path, raw):
    """
    Set raw data at the path in vault. The vault policy used must allow this.

    CLI Example:

    .. code-block:: bash

            salt '*' vault.write_raw "secret/my/secret" '{"user":"foo","password": "bar"}'
    """
    log.debug("Writing vault secrets for %s at %s", __grains__["id"], path)
    version2 = __utils__["vault.is_v2"](path)
    if version2["v2"]:
        path = version2["data"]
        raw = {"data": raw}
    try:
        url = "v1/{0}".format(path)
        response = __utils__["vault.make_request"]("POST", url, json=raw)
        if response.status_code == 200:
            return response.json()["data"]
        elif response.status_code != 204:
            response.raise_for_status()
        return True
    except Exception as err:  # pylint: disable=broad-except
        log.error("Failed to write secret! %s: %s", type(err).__name__, err)
        return False
# Buggy code
def delete_secret(path):
    """
    Delete secret at the path in vault. The vault policy used must allow this.

    CLI Example:

    .. code-block:: bash

        salt '*' vault.delete_secret "secret/my/secret"
    """
    log.debug("Deleting vault secrets for %s in %s", __grains__["id"], path)
    try:
        url = "v1/{0}".format(path)
        response = __utils__["vault.make_request"]("DELETE", url)
        if response.status_code != 204:
            response.raise_for_status()
        return True
    except Exception as err:  # pylint: disable=broad-except
        log.error("Failed to delete secret! %s: %s", type(err).__name__, err)
        return False


# Traceback (CommandExecutionError)
$ sudo salt-run sdb.get 'sdb://sdb_vault/secret/data/salt/pillar_data/wew'
[ERROR   ] Failed to read secret! KeyError: u'wew'
Exception occurred in runner sdb.get: Traceback (most recent call last):
File "/opt/saltstack/lib/python2.7/site-packages/salt/client/mixins.py", line 387, in _low
data['return'] = self.functions[fun](*args, **kwargs)
File "/opt/saltstack/lib/python2.7/site-packages/salt/runners/sdb.py", line 27, in get
return salt.utils.sdb.sdb_get(uri, __opts__, __utils__)
File "/opt/saltstack/lib/python2.7/site-packages/salt/utils/sdb.py", line 46, in sdb_get
return loaded_db[fun](query, profile=profile)
File "/opt/saltstack/lib/python2.7/site-packages/salt/sdb/vault.py", line 122, in get
raise salt.exceptions.CommandExecutionError(e)
CommandExecutionError: u'wew'
[INFO    ] Runner completed: 20181023165316837868

# Fixed code
def delete_secret(path):
    """
    Delete secret at the path in vault. The vault policy used must allow this.

    CLI Example:

    .. code-block:: bash

        salt '*' vault.delete_secret "secret/my/secret"
    """
    log.debug("Deleting vault secrets for %s in %s", __grains__["id"], path)
    version2 = __utils__["vault.is_v2"](path)
    if version2["v2"]:
        path = version2["data"]
    try:
        url = "v1/{0}".format(path)
        response = __utils__["vault.make_request"]("DELETE", url)
        if response.status_code != 204:
            response.raise_for_status()
        return True
    except Exception as err:  # pylint: disable=broad-except
        log.error("Failed to delete secret! %s: %s", type(err).__name__, err)
        return False
# Buggy code
def list_secrets(path):
    """
    List secret keys at the path in vault. The vault policy used must allow this.
    The path should end with a trailing slash.

    CLI Example:

    .. code-block:: bash

            salt '*' vault.list_secrets "secret/my/"
    """
    log.debug("Listing vault secret keys for %s in %s", __grains__["id"], path)
    try:
        url = "v1/{0}".format(path)
        response = __utils__["vault.make_request"]("LIST", url)
        if response.status_code != 200:
            response.raise_for_status()
        return response.json()["data"]
    except Exception as err:  # pylint: disable=broad-except
        log.error("Failed to list secrets! %s: %s", type(err).__name__, err)
        return None


# Traceback (CommandExecutionError)
$ sudo salt-run sdb.get 'sdb://sdb_vault/secret/data/salt/pillar_data/wew'
[ERROR   ] Failed to read secret! KeyError: u'wew'
Exception occurred in runner sdb.get: Traceback (most recent call last):
File "/opt/saltstack/lib/python2.7/site-packages/salt/client/mixins.py", line 387, in _low
data['return'] = self.functions[fun](*args, **kwargs)
File "/opt/saltstack/lib/python2.7/site-packages/salt/runners/sdb.py", line 27, in get
return salt.utils.sdb.sdb_get(uri, __opts__, __utils__)
File "/opt/saltstack/lib/python2.7/site-packages/salt/utils/sdb.py", line 46, in sdb_get
return loaded_db[fun](query, profile=profile)
File "/opt/saltstack/lib/python2.7/site-packages/salt/sdb/vault.py", line 122, in get
raise salt.exceptions.CommandExecutionError(e)
CommandExecutionError: u'wew'
[INFO    ] Runner completed: 20181023165316837868

# Fixed code
def list_secrets(path):
    """
    List secret keys at the path in vault. The vault policy used must allow this.
    The path should end with a trailing slash.

    CLI Example:

    .. code-block:: bash

            salt '*' vault.list_secrets "secret/my/"
    """
    log.debug("Listing vault secret keys for %s in %s", __grains__["id"], path)
    version2 = __utils__["vault.is_v2"](path)
    if version2["v2"]:
        path = version2["metadata"]
    try:
        url = "v1/{0}".format(path)
        response = __utils__["vault.make_request"]("LIST", url)
        if response.status_code != 200:
            response.raise_for_status()
        return response.json()["data"]
    except Exception as err:  # pylint: disable=broad-except
        log.error("Failed to list secrets! %s: %s", type(err).__name__, err)
        return None