Script 'mail_helper' called by obssrc Hello community, here is the log from the commit of package python-pytest-socket for openSUSE:Factory checked in at 2024-09-20 17:11:56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/python-pytest-socket (Old) and /work/SRC/openSUSE:Factory/.python-pytest-socket.new.29891 (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "python-pytest-socket" Fri Sep 20 17:11:56 2024 rev:5 rq:1202077 version:0.7.0 Changes: -------- --- /work/SRC/openSUSE:Factory/python-pytest-socket/python-pytest-socket.changes 2023-05-10 16:18:56.799124543 +0200 +++ /work/SRC/openSUSE:Factory/.python-pytest-socket.new.29891/python-pytest-socket.changes 2024-09-20 17:13:02.506305881 +0200 @@ -1,0 +2,19 @@ +Fri Sep 20 05:50:02 UTC 2024 - Steve Kowalik <steven.kowa...@suse.com> + +- Update to 0.7.0: + * Enhancements: + + Force enable socket CLI flag #186 + + Use getaddrinfo() instead of gethostbyname() #209 + + Allow both Hosts via IP and Name #275 + * Changes: + + Removed support for Python 3.7 and older. + + Dependency updates + + Development updates + + Testing updates + + Emit license and readme for source distribution #233 +- Update description and summary. +- Switch to pyproject macros. +- Run a small part of the test suite to check basic functionality. +- No more greedy globs in %files. + +------------------------------------------------------------------- Old: ---- pytest_socket-0.6.0.tar.gz New: ---- pytest_socket-0.7.0.tar.gz ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ python-pytest-socket.spec ++++++ --- /var/tmp/diff_new_pack.EiaAHL/_old 2024-09-20 17:13:02.934323709 +0200 +++ /var/tmp/diff_new_pack.EiaAHL/_new 2024-09-20 17:13:02.938323876 +0200 @@ -1,7 +1,7 @@ # # spec file for package python-pytest-socket # -# Copyright (c) 2023 SUSE LLC +# Copyright (c) 2024 SUSE LLC # # All modifications and additions to the file contributed by third parties # remain the property of their copyright owners, unless otherwise agreed @@ -18,13 +18,16 @@ %{?sle15_python_module_pythons} Name: python-pytest-socket -Version: 0.6.0 +Version: 0.7.0 Release: 0 -Summary: Pytest Plugin to disable socket +Summary: Pytest Plugin to disable socket calls License: MIT URL: https://github.com/miketheman/pytest-socket Source: https://files.pythonhosted.org/packages/source/p/pytest-socket/pytest_socket-%{version}.tar.gz -BuildRequires: %{python_module setuptools} +BuildRequires: %{python_module base >= 3.8} +BuildRequires: %{python_module pip} +BuildRequires: %{python_module poetry-core} +BuildRequires: %{python_module wheel} BuildRequires: fdupes BuildRequires: python-rpm-macros Requires: python-pytest >= 3.6.3 @@ -35,24 +38,29 @@ %python_subpackages %description -A Pytest Plugin to disable socket calls during tests. +A plugin to use with Pytest to disable or restrict socket calls during +tests to ensure network calls are prevented. %prep %setup -q -n pytest_socket-%{version} +touch tests/__init__.py %build -%python_build +%pyproject_wheel %install -%python_install +%pyproject_install %python_expand %fdupes %{buildroot}%{$python_sitelib} -# Tests require a network connection -#%%check -#%%pytest +%check +export PYTHONPATH=$PWD/tests +# Most tests require a network connection, let's check basic function +%pytest -k 'test_disable_via or test_global_disable_via' %files %{python_files} %doc README.md %license LICENSE -%{python_sitelib}/* +%{python_sitelib}/pytest_socket.py +%pycache_only %{python_sitelib}/__pycache__/pytest_socket*.pyc +%{python_sitelib}/pytest_socket-%{version}.dist-info ++++++ pytest_socket-0.6.0.tar.gz -> pytest_socket-0.7.0.tar.gz ++++++ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/.coveragerc new/pytest_socket-0.7.0/.coveragerc --- old/pytest_socket-0.6.0/.coveragerc 2021-03-30 18:05:42.045221800 +0200 +++ new/pytest_socket-0.7.0/.coveragerc 1970-01-01 01:00:00.000000000 +0100 @@ -1,2 +0,0 @@ -[report] -include = *pytest_socket* diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/PKG-INFO new/pytest_socket-0.7.0/PKG-INFO --- old/pytest_socket-0.6.0/PKG-INFO 1970-01-01 01:00:00.000000000 +0100 +++ new/pytest_socket-0.7.0/PKG-INFO 1970-01-01 01:00:00.000000000 +0100 @@ -1,12 +1,12 @@ Metadata-Version: 2.1 Name: pytest-socket -Version: 0.6.0 +Version: 0.7.0 Summary: Pytest Plugin to disable socket calls during tests Home-page: https://pypi.org/project/pytest-socket/ License: MIT Author: Mike Fiedler Author-email: mikethe...@gmail.com -Requires-Python: >=3.7,<4.0 +Requires-Python: >=3.8,<4.0 Classifier: Development Status :: 4 - Beta Classifier: Framework :: Pytest Classifier: Intended Audience :: Developers @@ -14,20 +14,17 @@ Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Topic :: Software Development :: Testing -Requires-Dist: pytest (>=3.6.3) +Requires-Dist: pytest (>=6.2.5) Project-URL: Bug Tracker, https://github.com/miketheman/pytest-socket/issues Project-URL: Change Log, https://github.com/miketheman/pytest-socket/blob/main/CHANGELOG.md +Project-URL: Funding, https://github.com/sponsors/miketheman Project-URL: Repository, https://github.com/miketheman/pytest-socket Description-Content-Type: text/markdown @@ -52,7 +49,7 @@ ## Requirements -- [Pytest](https://github.com/pytest-dev/pytest) 3.6.3 or greater +- [Pytest](https://github.com/pytest-dev/pytest) 6.2.5 or greater ## Installation @@ -60,7 +57,7 @@ from [PyPI](https://pypi.python.org/pypi): ```console -$ pip install pytest-socket +pip install pytest-socket ``` or add to your `pyproject.toml` for [poetry](https://python-poetry.org/): @@ -99,6 +96,9 @@ disable_socket() ``` +If you exceptionally want to enable socket for one particular execution +pass `--force-enable-socket`. It takes precedence over `--disable-socket`. + To enable Unix sockets during the test run (e.g. for async), add this option: ```ini diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/README.md new/pytest_socket-0.7.0/README.md --- old/pytest_socket-0.6.0/README.md 2022-07-04 14:41:04.653300000 +0200 +++ new/pytest_socket-0.7.0/README.md 2024-01-28 20:42:55.353310800 +0100 @@ -19,7 +19,7 @@ ## Requirements -- [Pytest](https://github.com/pytest-dev/pytest) 3.6.3 or greater +- [Pytest](https://github.com/pytest-dev/pytest) 6.2.5 or greater ## Installation @@ -27,7 +27,7 @@ from [PyPI](https://pypi.python.org/pypi): ```console -$ pip install pytest-socket +pip install pytest-socket ``` or add to your `pyproject.toml` for [poetry](https://python-poetry.org/): @@ -66,6 +66,9 @@ disable_socket() ``` +If you exceptionally want to enable socket for one particular execution +pass `--force-enable-socket`. It takes precedence over `--disable-socket`. + To enable Unix sockets during the test run (e.g. for async), add this option: ```ini diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/pyproject.toml new/pytest_socket-0.7.0/pyproject.toml --- old/pytest_socket-0.6.0/pyproject.toml 2023-02-03 20:00:29.828366800 +0100 +++ new/pytest_socket-0.7.0/pyproject.toml 2024-01-28 21:07:04.793340000 +0100 @@ -1,6 +1,6 @@ [tool.poetry] name = "pytest-socket" -version = "0.6.0" +version = "0.7.0" description = "Pytest Plugin to disable socket calls during tests" authors = ["Mike Fiedler <mikethe...@gmail.com>"] license = "MIT" @@ -8,11 +8,9 @@ homepage = "https://pypi.org/project/pytest-socket/" repository = "https://github.com/miketheman/pytest-socket" include = [ - { path = "LICENSE" }, - { path = "README.md" }, + { path = "LICENSE", format = "sdist" }, + { path = "README.md", format = "sdist" }, { path = "tests", format = "sdist" }, - { path = "pytest.ini", format = "sdist" }, - { path = ".coveragerc", format = "sdist" }, { path = ".flake8", format = "sdist" }, ] classifiers = [ @@ -21,30 +19,29 @@ "Intended Audience :: Developers", "Topic :: Software Development :: Testing", "Programming Language :: Python", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "Programming Language :: Python :: Implementation :: CPython", "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", ] [tool.poetry.dependencies] -python = "^3.7" -pytest = ">=3.6.3" +python = "^3.8" +pytest = ">=6.2.5" [tool.poetry.dev-dependencies] -coverage = "^7.0" -pytest = "^7.0" -pytest-httpbin = "^1.0" -pytest-randomly = "^3.5.0" -asynctest = "^0.13.0" +coverage = "^7.3" +pytest-httpbin = "^2.0.0" +pytest-randomly = "^3.15.0" requests = "^2.26.0" -starlette = "^0.23.0" -httpx = "^0.23.0" -# See https://github.com/postmanlabs/httpbin/pull/674 -httpbin = { git = "https://github.com/maximino-dev/httpbin.git", rev = "651c03a73" } +starlette = "^0.36.1" +httpx = "^0.26.0" +# Waiting for new release. See https://github.com/psf/httpbin/issues/35 +httpbin = { git = "https://github.com/psf/httpbin.git", rev = "1f6e0498" } [tool.poetry.plugins.pytest11] socket = 'pytest_socket' @@ -52,6 +49,10 @@ [tool.poetry.urls] "Bug Tracker" = "https://github.com/miketheman/pytest-socket/issues" "Change Log" = "https://github.com/miketheman/pytest-socket/blob/main/CHANGELOG.md" +"Funding" = "https://github.com/sponsors/miketheman" + +[tool.coverage.report] +include = ["*pytest_socket*", "tests*"] [tool.isort] known_first_party = ['pytest_socket', 'conftest', 'test_socket'] diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/pytest_socket.py new/pytest_socket-0.7.0/pytest_socket.py --- old/pytest_socket-0.6.0/pytest_socket.py 2023-02-03 19:37:23.603405500 +0100 +++ new/pytest_socket-0.7.0/pytest_socket.py 2024-01-27 17:38:36.128723600 +0100 @@ -1,5 +1,8 @@ import ipaddress +import itertools import socket +import typing +from collections import defaultdict import pytest @@ -31,6 +34,12 @@ help="Disable socket.socket by default to block network calls.", ) group.addoption( + "--force-enable-socket", + action="store_true", + dest="force_enable_socket", + help="Force enable socket.socket network calls (override --disable-socket).", + ) + group.addoption( "--allow-hosts", dest="allow_hosts", metavar="ALLOWED_HOSTS_CSV", @@ -100,6 +109,7 @@ ) # Store the global configs in the `pytest.Config` object. + config.__socket_force_enabled = config.getoption("--force-enable-socket") config.__socket_disabled = config.getoption("--disable-socket") config.__socket_allow_unix_socket = config.getoption("--allow-unix-socket") config.__socket_allow_hosts = config.getoption("--allow-hosts") @@ -119,9 +129,12 @@ if not hasattr(item, "fixturenames"): return - # If test has the `enable_socket` marker, we accept this as most explicit. - if "socket_enabled" in item.fixturenames or item.get_closest_marker( - "enable_socket" + # If test has the `enable_socket` marker, fixture or + # it's forced from the CLI, we accept this as most explicit. + if ( + "socket_enabled" in item.fixturenames + or item.get_closest_marker("enable_socket") + or item.config.__socket_force_enabled ): enable_socket() return @@ -182,24 +195,26 @@ return False -def resolve_hostname(hostname): +def resolve_hostnames(hostname: str) -> typing.Set[str]: try: - return socket.gethostbyname(hostname) + return { + addr_struct[0] for *_, addr_struct in socket.getaddrinfo(hostname, None) + } except socket.gaierror: - return None + return set() -def normalize_allowed_hosts(allowed_hosts): - """Convert all items in `allowed_hosts` to an IP address.""" - ip_hosts = [] +def normalize_allowed_hosts( + allowed_hosts: typing.List[str], +) -> typing.Dict[str, typing.Set[str]]: + """Map all items in `allowed_hosts` to IP addresses.""" + ip_hosts = defaultdict(set) for host in allowed_hosts: host = host.strip() if is_ipaddress(host): - ip_hosts.append(host) + ip_hosts[host].add(host) else: - resolved = resolve_hostname(host) - if resolved: - ip_hosts.append(resolved) + ip_hosts[host].update(resolve_hostnames(host)) return ip_hosts @@ -212,16 +227,29 @@ if not isinstance(allowed, list): return - allowed_hosts = normalize_allowed_hosts(allowed) + allowed_ip_hosts_by_host = normalize_allowed_hosts(allowed) + allowed_ip_hosts_and_hostnames = set( + itertools.chain(*allowed_ip_hosts_by_host.values()) + ) | set(allowed_ip_hosts_by_host.keys()) + allowed_list = sorted( + [ + ( + host + if len(normalized) == 1 and next(iter(normalized)) == host + else f"{host} ({','.join(sorted(normalized))})" + ) + for host, normalized in allowed_ip_hosts_by_host.items() + ] + ) def guarded_connect(inst, *args): host = host_from_connect_args(args) - if host in allowed_hosts or ( + if host in allowed_ip_hosts_and_hostnames or ( _is_unix_socket(inst.family) and allow_unix_socket ): return _true_connect(inst, *args) - raise SocketConnectBlockedError(allowed, host) + raise SocketConnectBlockedError(allowed_list, host) socket.socket.connect = guarded_connect diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/setup.py new/pytest_socket-0.7.0/setup.py --- old/pytest_socket-0.6.0/setup.py 1970-01-01 01:00:00.000000000 +0100 +++ new/pytest_socket-0.7.0/setup.py 1970-01-01 01:00:00.000000000 +0100 @@ -1,29 +0,0 @@ -# -*- coding: utf-8 -*- -from setuptools import setup - -modules = \ -['pytest_socket'] -install_requires = \ -['pytest>=3.6.3'] - -entry_points = \ -{'pytest11': ['socket = pytest_socket']} - -setup_kwargs = { - 'name': 'pytest-socket', - 'version': '0.6.0', - 'description': 'Pytest Plugin to disable socket calls during tests', - 'long_description': '# pytest-socket\n\n[](https://pypi.python.org/pypi/pytest-socket)\n[](https://pypi.python.org/pypi/pytest-socket)\n[](https://github.com/miketheman/pytest-socket/actions?query=workflow%3A%22Python+Tests%22)\n[](https://results.pre-commit.ci/latest/github/miketheman/pytest-socket/main)\n[](https://codeclimate.com/github/miketheman/pytest-socket/maintainability)\n[](https://app.fossa.io/projects/git%2Bgithub.com%2Fmiketheman%2Fp ytest-socket?ref=badge_shield)\n[](https://github.com/psf/black)\n\nA plugin to use with Pytest to disable or restrict `socket` calls during\ntests to ensure network calls are prevented.\n\n---\n\n## Features\n\n- Disables all network calls flowing through Python\\\'s `socket` interface.\n\n## Requirements\n\n- [Pytest](https://github.com/pytest-dev/pytest) 3.6.3 or greater\n\n## Installation\n\nYou can install `pytest-socket` via [pip](https://pypi.python.org/pypi/pip/)\nfrom [PyPI](https://pypi.python.org/pypi):\n\n```console\n$ pip install pytest-socket\n```\n\nor add to your `pyproject.toml` for [poetry](https://python-poetry.org/):\n\n```ini\n[tool.poetry.dev-dependencies]\npytest-socket = "*"\n```\n\n## Usage\n\nRun `pytest --disable-socket`, tests should fail on any access to `socket` or\nlibraries using socket with a `SocketBlockedError`.\n\nTo add this flag as the default behavior, add this sect ion to your\n[`pytest.ini`](https://docs.pytest.org/en/6.2.x/customize.html#pytest-ini):\n\n```ini\n[pytest]\naddopts = --disable-socket\n```\n\nor add this to your [`setup.cfg`](https://docs.pytest.org/en/6.2.x/customize.html#setup-cfg):\n\n```ini\n[tool:pytest]\naddopts = --disable-socket\n```\n\nor update your [`conftest.py`](https://docs.pytest.org/en/6.2.x/writing_plugins.html#conftest-py-plugins) to include:\n\n```python\nfrom pytest_socket import disable_socket\n\ndef pytest_runtest_setup():\n disable_socket()\n```\n\nTo enable Unix sockets during the test run (e.g. for async), add this option:\n\n```ini\n[pytest]\naddopts = --disable-socket --allow-unix-socket\n```\n\nTo enable specific tests use of `socket`, pass in the fixture to the test or\nuse a marker:\n\n```python\ndef test_explicitly_enable_socket(socket_enabled):\n assert socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\n...@pytest.mark.enable_socket\ndef test_explicitly_enable_socket_with_mark():\n asser t socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n```\n\nTo allow only specific hosts per-test:\n\n```python\n...@pytest.mark.allow_hosts([\'127.0.0.1\'])\ndef test_explicitly_enable_socket_with_mark():\n assert socket.socket.connect((\'127.0.0.1\', 80))\n```\n\nor for whole test run\n\n```ini\n[pytest]\naddopts = --allow-hosts=127.0.0.1,127.0.1.1\n```\n\n### Frequently Asked Questions\n\nQ: Why is network access disabled in some of my tests but not others?\n\nA: pytest\'s default fixture scope is "function", which `socket_enabled` uses.\nIf you create another fixture that creates a socket usage that has a "higher"\ninstantiation order, such as at the module/class/session, then the higher order\nfixture will be resolved first, and won\'t be disabled during the tests.\nRead more in [this excellent example](https://github.com/miketheman/pytest-socket/issues/45#issue-679835420)\nand more about [pytest fixture order here](https://docs.pytest.org/en/stable/fixture.html#fixture-instant iation-order).\n\nThis behavior may change in the future, as we learn more about pytest\nfixture order, and what users expect to happen.\n\n## Contributing\n\nContributions are very welcome. Tests can be run with\n[pytest](https://github.com/pytest-dev/pytest), please ensure the\ncoverage at least stays the same before you submit a pull request.\n\n## License\n\nDistributed under the terms of the\n[MIT](http://opensource.org/licenses/MIT) license, "pytest-socket" is\nfree and open source software\n\n[](https://app.fossa.io/projects/git%2Bgithub.com%2Fmiketheman%2Fpytest-socket?ref=badge_large)\n\n## Issues\n\nIf you encounter any problems, please [file an issue](https://github.com/miketheman/pytest-socket/issues)\nalong with a detailed description.\n\n## References\n\nThis [Pytest](https://github.com/pytest-dev/pytest) plugin was generated with\n[Cookiecutter](https://githu b.com/audreyr/cookiecutter) along with\n[\\@hackebrot](https://github.com/hackebrot)\\\'s\n[Cookiecutter-pytest-plugin](https://github.com/pytest-dev/cookiecutter-pytest-plugin)\ntemplate.\n\nThis plugin came about due to the efforts by\n[\\@hangtwenty](https://github.com/hangtwenty) solving a [StackOverflow\nquestion](https://stackoverflow.com/a/30064664), then converted into a\npytest plugin by [\\@miketheman](https://github.com/miketheman).\n', - 'author': 'Mike Fiedler', - 'author_email': 'mikethe...@gmail.com', - 'maintainer': 'None', - 'maintainer_email': 'None', - 'url': 'https://pypi.org/project/pytest-socket/', - 'py_modules': modules, - 'install_requires': install_requires, - 'entry_points': entry_points, - 'python_requires': '>=3.7,<4.0', -} - - -setup(**setup_kwargs) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/tests/common.py new/pytest_socket-0.7.0/tests/common.py --- old/pytest_socket-0.6.0/tests/common.py 1970-01-01 01:00:00.000000000 +0100 +++ new/pytest_socket-0.7.0/tests/common.py 2023-06-18 20:29:34.423575000 +0200 @@ -0,0 +1,16 @@ +""" +Common test functions. +""" + + +def assert_socket_blocked(result, passed=0, skipped=0, failed=1): + """ + Uses built in methods to test for common failure scenarios. + Usually we only test for a single failure, + but sometimes we want to test for multiple conditions, + so we can pass in the expected counts. + """ + result.assert_outcomes(passed=passed, skipped=skipped, failed=failed) + result.stdout.fnmatch_lines( + "*Socket*Blocked*Error: A test tried to use socket.socket.*" + ) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/tests/test_async.py new/pytest_socket-0.7.0/tests/test_async.py --- old/pytest_socket-0.6.0/tests/test_async.py 2022-07-04 14:41:04.654518800 +0200 +++ new/pytest_socket-0.7.0/tests/test_async.py 2023-06-18 20:29:34.424035000 +0200 @@ -1,28 +1,5 @@ from conftest import unix_sockets_only -from test_socket import assert_socket_blocked - - -@unix_sockets_only -def test_asynctest(testdir): - testdir.makepyfile( - """ - import socket - import asynctest - - - class AnExampleWithTestCaseAndCoroutines(asynctest.TestCase): - async def a_coroutine(self): - return "I worked" - - async def test_that_a_coroutine_runs(self): - self.assertIn("worked", await self.a_coroutine()) - - async def test_inet_is_blocked(self): - socket.socket(socket.AF_INET, socket.SOCK_STREAM) - """ - ) - result = testdir.runpytest("--disable-socket", "--allow-unix-socket") - result.assert_outcomes(passed=1, skipped=0, failed=1) +from tests.common import assert_socket_blocked @unix_sockets_only diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/tests/test_precedence.py new/pytest_socket-0.7.0/tests/test_precedence.py --- old/pytest_socket-0.6.0/tests/test_precedence.py 2022-07-04 14:41:04.655182400 +0200 +++ new/pytest_socket-0.7.0/tests/test_precedence.py 2023-06-18 20:29:34.424466600 +0200 @@ -1,16 +1,7 @@ """Test module to express precedence tests between the different configuration combinations""" - -def assert_socket_blocked(result, passed=0, skipped=0, failed=1): - """Uses built in methods to test for common failure scenarios. - Usually we only test for a single failure, - but sometimes we want to test for multiple conditions, - so we can pass in the expected counts.""" - result.assert_outcomes(passed=passed, skipped=skipped, failed=failed) - result.stdout.fnmatch_lines( - "*Socket*Blocked*Error: A test tried to use socket.socket.*" - ) +from tests.common import assert_socket_blocked def test_disable_via_fixture(testdir): @@ -54,6 +45,34 @@ assert_socket_blocked(result) +def test_force_enable_socket_via_cli_flag(testdir): + testdir.makepyfile( + """ + import socket + import pytest + + @pytest.mark.disable_socket + def test_socket(): + socket.socket(socket.AF_INET, socket.SOCK_STREAM) + """ + ) + result = testdir.runpytest("--force-enable-socket") + result.assert_outcomes(passed=1) + + +def test_force_enable_cli_flag_precedence(testdir): + testdir.makepyfile( + """ + import socket + + def test_socket(): + socket.socket(socket.AF_INET, socket.SOCK_STREAM) + """ + ) + result = testdir.runpytest("--disable-socket", "--force-enable-socket") + result.assert_outcomes(passed=1) + + def test_global_disable_via_config(testdir): testdir.makepyfile( """ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/tests/test_restrict_hosts.py new/pytest_socket-0.7.0/tests/test_restrict_hosts.py --- old/pytest_socket-0.6.0/tests/test_restrict_hosts.py 2023-02-03 00:10:51.744330400 +0100 +++ new/pytest_socket-0.7.0/tests/test_restrict_hosts.py 2024-01-27 17:38:36.129155900 +0100 @@ -31,6 +31,16 @@ assert urlopen('http://{0}:{1}/').getcode() == 200 """ +urlopen_hostname_code_template = """ + import pytest + from urllib.request import urlopen + + {3} + def {2}(): + # Skip {{1}} as we expect {{0}} to be the full hostname with or without port + assert urlopen('http://{0}').getcode() == 200 +""" + def assert_host_blocked(result, host): result.stdout.fnmatch_lines( @@ -45,6 +55,7 @@ test_name = inspect.stack()[1][3] mark = "" + host = kwargs.get("host", httpbin.host) cli_arg = kwargs.get("cli_arg", None) code_template = kwargs.get("code_template", connect_code_template) mark_arg = kwargs.get("mark_arg", None) @@ -55,7 +66,7 @@ elif isinstance(mark_arg, list): hosts = '","'.join(mark_arg) mark = f'@pytest.mark.allow_hosts(["{hosts}"])' - code = code_template.format(httpbin.host, httpbin.port, test_name, mark) + code = code_template.format(host, httpbin.port, test_name, mark) testdir.makepyfile(code) if cli_arg: @@ -67,7 +78,9 @@ result.assert_outcomes(1, 0, 0) else: result.assert_outcomes(0, 0, 1) - assert_host_blocked(result, httpbin.host) + assert_host_blocked(result, host) + + return result return assert_socket_connect @@ -106,10 +119,31 @@ assert_connect(True, cli_arg=localhost) -def test_single_cli_arg_connect_enabled_hostname_resolved(assert_connect): +def test_single_cli_arg_connect_enabled_localhost_resolved(assert_connect): assert_connect(True, cli_arg="localhost") +def test_single_cli_arg_127_0_0_1_hostname_localhost_connect_disabled(assert_connect): + assert_connect(False, cli_arg=localhost, host="localhost") + + +def test_single_cli_arg_localhost_hostname_localhost_connect_enabled(assert_connect): + assert_connect(True, cli_arg="localhost", host="localhost") + + +def test_single_cli_arg_connect_disabled_hostname_resolved(assert_connect): + result = assert_connect( + False, + cli_arg="localhost", + host="1.2.3.4", + code_template=urlopen_hostname_code_template, + ) + result.stdout.fnmatch_lines( + '*A test tried to use socket.socket.connect() with host "1.2.3.4" ' + '(allowed: "localhost (127.0.0.1,::1)")*' + ) + + def test_single_cli_arg_connect_enabled_hostname_unresolvable(assert_connect): assert_connect(False, cli_arg="unresolvable") diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/pytest_socket-0.6.0/tests/test_socket.py new/pytest_socket-0.7.0/tests/test_socket.py --- old/pytest_socket-0.6.0/tests/test_socket.py 2022-07-04 14:41:04.655759000 +0200 +++ new/pytest_socket-0.7.0/tests/test_socket.py 2023-06-21 12:57:28.292064700 +0200 @@ -1,6 +1,7 @@ import pytest from conftest import unix_sockets_only +from tests.common import assert_socket_blocked PYFILE_SOCKET_USED_IN_TEST_ARGS = """ import socket @@ -26,13 +27,6 @@ """ -def assert_socket_blocked(result): - result.assert_outcomes(passed=0, skipped=0, failed=1) - result.stdout.fnmatch_lines( - "*SocketBlockedError: A test tried to use socket.socket.*" - ) - - @pytest.mark.parametrize( "pyfile", [ @@ -155,7 +149,7 @@ from urllib2 import urlopen def test_disable_socket_urllib(): - assert urlopen('http://httpbin.org/get').getcode() == 200 + assert urlopen('https://httpstat.us/200').getcode() == 200 """ ) result = testdir.runpytest() @@ -176,7 +170,7 @@ @pytest.mark.enable_socket def test_disable_socket_urllib(): - assert urlopen('http://httpbin.org/get').getcode() == 200 + assert urlopen('https://httpstat.us/200').getcode() == 200 """ ) result = testdir.runpytest("--disable-socket") @@ -196,7 +190,7 @@ @pytest.mark.disable_socket def test_disable_socket_urllib(): - assert urlopen('http://httpbin.org/get').getcode() == 200 + assert urlopen('https://httpstat.us/200').getcode() == 200 """ ) result = testdir.runpytest()