Repository: pycountry/pycountry (language: python)

Issue:
`test_has_version_attribute` fails without installed package
Since https://github.com/flyingcircusio/pycountry/pull/52 was merged it is possible to run tests without installing pycountry.

Anyway, such attempt fails on test `test_has_version_attribute` as:
```
===================================================================================== FAILURES ======================================================================================
____________________________________________________________________________ test_has_version_attribute _____________________________________________________________________________

    def test_has_version_attribute():
>       assert pycountry.__version__ != "n/a"
E       AssertionError: assert 'n/a' != 'n/a'
E        +  where 'n/a' = pycountry.__version__

src/pycountry/tests/test_general.py:246: AssertionError
============================================================================== short test summary info ==============================================================================
FAILED src/pycountry/tests/test_general.py::test_has_version_attribute - AssertionError: assert 'n/a' != 'n/a'
=========================================================================== 1 failed, 20 passed in 1.24s ============================================================================
```



Discussion / hints:
How did you end up running the tests without the package installed?
Via `port test ...` from MacPorts.
@ctheune do you think this needs to be done or is this an edge case for a specific type of environment 

That's completely weird. I think this is more of an issue with whatever macports is doing. Apparently they're not using the package installation and build mechanisms that are absolutely standard. I wonder how they get packages working that use entry points etc ... 

From my perspective I'd ask the MacPorts maintainers to fix this properly.
@ctheune how can I run tests without installing pycountry?
I'm not sure I get the question... In what environment do you want to run the test *without installing pycountry*? 
@ctheune I've checked https://github.com/pycountry/pycountry/blob/main/.github/workflows/test.yml and I see that you assume that current version of project is installed, before running tests.

So, my question: how can I run test *withouth* installing pycountry?
My head is running in circles. In Python it doesn't make sense to run tests on a package that isn't installed (in the interpreter's sys.path) ... 
> My head is running in circles. In Python it doesn't make sense to run tests on a package that isn't installed (in the interpreter's sys.path) ...

Which can be emulated via `PYTHONPATH`, isn't it?
I have no idea what your goal is here ... 
@catap could you write your goal in a user story format.

"I as an end user would like to be able to run pytest on pycountry via ________ in order to _______"

Examples of other libraries that you've seen this supported for may also be of use.
I’m a maintainer of a lot of ports in MacPorts: https://ports.macports.org/search/?selected_facets=maintainers_exact:catap and majority of python ports which I’m supporting allows tests on that way.
You can run with `pytest --pyargs pycountry` to look on the path instead of the current directory. And you need to set `PYTHONPATH` correctly as well. This isn't really a `pycountry` question.
> You can run with `pytest --pyargs pycountry` to look on the path instead of the current directory. And you need to set `PYTHONPATH` correctly as well. This isn't really a `pycountry` question.

It is. The issue that unit tests are failing when not installed.
@catap, how can I locally reproduce the failure you're seeing?  Can you give me steps starting from however you retrieve the `pycountry` code?

Note: these steps need to be unrelated to MacPorts; I'm on Linux :)
@catap I haven't gone as far as to actually install MacPorts as I don't want to impact my environment settings and paths, however, I was able to run `pytest --pyargs pycountry` successfully from a venv where `pycountry` is not installed. This was tested on version `23.12.11`. 

``` bash
(mac_ports) (base) nate.schimmoller@NateSchimmollerMBP pycountry % pytest --pyargs pycountry
============================= test session starts ==============================
platform darwin -- Python 3.10.9, pytest-7.1.2, pluggy-1.3.0
rootdir: /Users/nate.schimmoller/Documents/GitHub/pycountry, configfile: pytest.ini
plugins: anyio-3.5.0, cov-4.1.0
collected 49 items                                                             

src/pycountry/tests/test_general.py .................................... [ 73%]
.............                                                            [100%]

=============================== warnings summary ===============================
src/pycountry/tests/test_general.py::test_missing_common_official_use_same
  /Users/nate.schimmoller/Documents/GitHub/pycountry/src/pycountry/db.py:51: UserWarning: Country's official_name not found. Country name provided instead.
    warnings.warn(warning_message, UserWarning)

src/pycountry/tests/test_general.py::test_missing_common_official_use_same
  /Users/nate.schimmoller/Documents/GitHub/pycountry/src/pycountry/db.py:51: UserWarning: Country's common_name not found. Country name provided instead.
    warnings.warn(warning_message, UserWarning)

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
- generated xml file: /Users/nate.schimmoller/Documents/GitHub/pycountry/report.xml -

---------- coverage: platform darwin, python 3.10.9-final-0 ----------
Coverage HTML written to dir htmlcov

Required test coverage of 95.0% reached. Total coverage: 95.77%
======================== 49 passed, 2 warnings in 2.15s ========================
(mac_ports) (base) nate.schimmoller@NateSchimmollerMBP pycountry % pip list
Package    Version
---------- -------
pip        22.3.1
setuptools 65.5.0
```
Sorry, I've missed email with asking to reproduce. How I can reproduce it without MacPorts or anything else:

```
√ macports-ports % mkdir /tmp/xxx
√ macports-ports % cd /tmp/xxx
√ xxx % git clone https://github.com/pycountry/pycountry.git
Cloning into 'pycountry'...
remote: Enumerating objects: 14533, done.
remote: Counting objects: 100% (2307/2307), done.
remote: Compressing objects: 100% (1041/1041), done.
remote: Total 14533 (delta 827), reused 1918 (delta 703), pack-reused 12226
Receiving objects: 100% (14533/14533), 40.90 MiB | 26.04 MiB/s, done.
Resolving deltas: 100% (8112/8112), done.
? xxx % cd pycountry
√ pycountry % python3.12 -mvenv .venv
√ pycountry % sh
sh-3.2$ . ./.venv/bin/activate
(.venv) sh-3.2$ pip3 install pytest
Collecting pytest
  Obtaining dependency information for pytest from https://files.pythonhosted.org/packages/f3/8c/f16efd81ca8e293b2cc78f111190a79ee539d0d5d36ccd49975cb3beac60/pytest-7.4.3-py3-none-any.whl.metadata
  Downloading pytest-7.4.3-py3-none-any.whl.metadata (7.9 kB)
Collecting iniconfig (from pytest)
  Using cached iniconfig-2.0.0-py3-none-any.whl (5.9 kB)
Collecting packaging (from pytest)
  Obtaining dependency information for packaging from https://files.pythonhosted.org/packages/ec/1a/610693ac4ee14fcdf2d9bf3c493370e4f2ef7ae2e19217d7a237ff42367d/packaging-23.2-py3-none-any.whl.metadata
  Downloading packaging-23.2-py3-none-any.whl.metadata (3.2 kB)
Collecting pluggy<2.0,>=0.12 (from pytest)
  Obtaining dependency information for pluggy<2.0,>=0.12 from https://files.pythonhosted.org/packages/05/b8/42ed91898d4784546c5f06c60506400548db3f7a4b3fb441cba4e5c17952/pluggy-1.3.0-py3-none-any.whl.metadata
  Downloading pluggy-1.3.0-py3-none-any.whl.metadata (4.3 kB)
Using cached pytest-7.4.3-py3-none-any.whl (325 kB)
Using cached pluggy-1.3.0-py3-none-any.whl (18 kB)
Using cached packaging-23.2-py3-none-any.whl (53 kB)
Installing collected packages: pluggy, packaging, iniconfig, pytest
Successfully installed iniconfig-2.0.0 packaging-23.2 pluggy-1.3.0 pytest-7.4.3

[notice] A new release of pip is available: 23.2.1 -> 23.3.2
[notice] To update, run: pip install --upgrade pip
(.venv) sh-3.2$ pytest -o addopts=''
============================================================================================ test session starts ============================================================================================
platform darwin -- Python 3.12.1, pytest-7.4.3, pluggy-1.3.0
rootdir: /private/tmp/xxx/pycountry
configfile: pytest.ini
collected 0 items / 1 error

================================================================================================== ERRORS ===================================================================================================
___________________________________________________________________________ ERROR collecting src/pycountry/tests/test_general.py ____________________________________________________________________________
ImportError while importing test module '/private/tmp/xxx/pycountry/src/pycountry/tests/test_general.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/local/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py:90: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
src/pycountry/tests/test_general.py:9: in <module>
    import pycountry
E   ModuleNotFoundError: No module named 'pycountry'
========================================================================================== short test summary info ==========================================================================================
ERROR src/pycountry/tests/test_general.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================================= 1 error in 0.63s ==============================================================================================
(.venv) sh-3.2$

```

without `-o addopts=''` it fails as:
```
(.venv) sh-3.2$ pytest
ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --cov=src --cov-report=html
  inifile: /private/tmp/xxx/pycountry/pytest.ini
  rootdir: /private/tmp/xxx/pycountry

(.venv) sh-3.2$
```
and if I install `pytest-cov` it fails like this:
```
(.venv) sh-3.2$ pip3 install pytest-cov
Collecting pytest-cov
  Obtaining dependency information for pytest-cov from https://files.pythonhosted.org/packages/a7/4b/8b78d126e275efa2379b1c2e09dc52cf70df16fc3b90613ef82531499d73/pytest_cov-4.1.0-py3-none-any.whl.metadata
  Downloading pytest_cov-4.1.0-py3-none-any.whl.metadata (26 kB)
Requirement already satisfied: pytest>=4.6 in ./.venv/lib/python3.12/site-packages (from pytest-cov) (7.4.3)
Collecting coverage[toml]>=5.2.1 (from pytest-cov)
  Obtaining dependency information for coverage[toml]>=5.2.1 from https://files.pythonhosted.org/packages/d2/8b/113b8c7e7f7c258a0a7054f66d2afa1d974d22a8b220e43ddd45bfa1cabb/coverage-7.3.3-cp312-cp312-macosx_10_9_x86_64.whl.metadata
  Downloading coverage-7.3.3-cp312-cp312-macosx_10_9_x86_64.whl.metadata (8.1 kB)
Requirement already satisfied: iniconfig in ./.venv/lib/python3.12/site-packages (from pytest>=4.6->pytest-cov) (2.0.0)
Requirement already satisfied: packaging in ./.venv/lib/python3.12/site-packages (from pytest>=4.6->pytest-cov) (23.2)
Requirement already satisfied: pluggy<2.0,>=0.12 in ./.venv/lib/python3.12/site-packages (from pytest>=4.6->pytest-cov) (1.3.0)
Downloading pytest_cov-4.1.0-py3-none-any.whl (21 kB)
Downloading coverage-7.3.3-cp312-cp312-macosx_10_9_x86_64.whl (201 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 201.6/201.6 kB 3.0 MB/s eta 0:00:00
Installing collected packages: coverage, pytest-cov
Successfully installed coverage-7.3.3 pytest-cov-4.1.0

[notice] A new release of pip is available: 23.2.1 -> 23.3.2
[notice] To update, run: pip install --upgrade pip
(.venv) sh-3.2$ pytest
============================================================================================ test session starts ============================================================================================
platform darwin -- Python 3.12.1, pytest-7.4.3, pluggy-1.3.0
rootdir: /private/tmp/xxx/pycountry
configfile: pytest.ini
plugins: cov-4.1.0
collected 0 items / 1 error                                                                                                                                                                                 

================================================================================================== ERRORS ===================================================================================================
___________________________________________________________________________ ERROR collecting src/pycountry/tests/test_general.py ____________________________________________________________________________
ImportError while importing test module '/private/tmp/xxx/pycountry/src/pycountry/tests/test_general.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/local/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py:90: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
src/pycountry/tests/test_general.py:9: in <module>
    import pycountry
E   ModuleNotFoundError: No module named 'pycountry'
------------------------------------------------------------------------- generated xml file: /private/tmp/xxx/pycountry/report.xml -------------------------------------------------------------------------

---------- coverage: platform darwin, python 3.12.1-final-0 ----------
Coverage HTML written to dir htmlcov

FAIL Required test coverage of 95.0% not reached. Total coverage: 0.91%
========================================================================================== short test summary info ==========================================================================================
ERROR src/pycountry/tests/test_general.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================================================= 1 error in 1.00s ==============================================================================================
(.venv) sh-3.2$ 
```
and if I install it, it works:
```
(.venv) sh-3.2$ pip install .
Processing /private/tmp/xxx/pycountry
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Building wheels for collected packages: pycountry
  Building wheel for pycountry (pyproject.toml) ... done
  Created wheel for pycountry: filename=pycountry-23.12.11.dev0-py3-none-any.whl size=6215369 sha256=606f3f676684a606d2df46ebd314bb5fdccfc116383bbeb0f107ef954c532725
  Stored in directory: /private/var/folders/rq/wqy42lq543z9rwrlj7vf1h4r0000gn/T/pip-ephem-wheel-cache-3t_ut9mt/wheels/78/b5/4f/cf9f82e6dbdb87ec2ac0560283e6e50e23446ce505d4890864
Successfully built pycountry
Installing collected packages: pycountry
Successfully installed pycountry-23.12.11.dev0

[notice] A new release of pip is available: 23.2.1 -> 23.3.2
[notice] To update, run: pip install --upgrade pip
(.venv) sh-3.2$ pytest
============================================================================================ test session starts ============================================================================================
platform darwin -- Python 3.12.1, pytest-7.4.3, pluggy-1.3.0
rootdir: /private/tmp/xxx/pycountry
configfile: pytest.ini
plugins: cov-4.1.0
collected 49 items                                                                                                                                                                                          

src/pycountry/tests/test_general.py .................................................                                                                                                                 [100%]

============================================================================================= warnings summary ==============================================================================================
src/pycountry/tests/test_general.py::test_missing_common_official_use_same
  /private/tmp/xxx/pycountry/.venv/lib/python3.12/site-packages/pycountry/db.py:51: UserWarning: Country's official_name not found. Country name provided instead.
    warnings.warn(warning_message, UserWarning)

src/pycountry/tests/test_general.py::test_missing_common_official_use_same
  /private/tmp/xxx/pycountry/.venv/lib/python3.12/site-packages/pycountry/db.py:51: UserWarning: Country's common_name not found. Country name provided instead.
    warnings.warn(warning_message, UserWarning)

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
------------------------------------------------------------------------- generated xml file: /private/tmp/xxx/pycountry/report.xml -------------------------------------------------------------------------

---------- coverage: platform darwin, python 3.12.1-final-0 ----------
Coverage HTML written to dir htmlcov

FAIL Required test coverage of 95.0% not reached. Total coverage: 40.49%
====================================================================================== 49 passed, 2 warnings in 1.60s =======================================================================================
(.venv) sh-3.2$ 
```
@zware is it enough or shall I add something else?
@catap thanks so much for this I was able to replicate and come up with a potential fix:

1. Add a `conftest.py` file to root and modify `pytest.ini`, solves the `pytest: error: unrecognized arguments: --cov=src`

##### conftest.py
``` python 
import sys
from pathlib import Path

# Assuming conftest.py is at the root of the project
root_dir = Path(__file__).parent
src_dir = root_dir / 'src'

sys.path.insert(0, str(src_dir))
```

##### pytest.ini
``` python
[pytest]
addopts = --tb=native --cov-report=html src --junitxml=report.xml
junit_family = xunit1
```

2. @catap you do need to also `pip install pytest-cov` to resolve `pytest: error: unrecognized arguments: --cov-report=html`

4. Modify `src/pycountry/tests/test_general.test_has_version_attributes`

``` python
def test_has_version_attribute():
    try:
        from importlib_resources import files
    except ImportError:
        from importlib.resources import files

    from importlib.metadata import distribution, PackageNotFoundError

    try:
        distribution('pycountry')
        package_installed = True
    except PackageNotFoundError:
        package_installed = False

    if package_installed:
        assert pycountry.__version__ != "n/a"
        assert len(pycountry.__version__) >= 5
        assert "." in pycountry.__version__
    else:
        pytest.skip("Skipping version check as pycountry is not installed in a standard way")
```
@nschimmoller (3) is something that I had in mind when I've opened this issue ;)
BTW I haven't see any reason to have `test_has_version_attribute` at all. Maybe I miss something. Why was it added at the first place?
I do think that we want end users with a standard installation to be able to run `pytest.__version__` so they are aware what version they are on and by adding it in to the testing it ensures that this properly gets set before release.

I'd hate to end up with a release down the line where inadvertently a user runs `pytest.__version__` and gets an attribute error or it returns `n/a`
@zware for your review :) 

Fix patch:
diff --git a/pyproject.toml b/pyproject.toml
index faf40c11..80c0e82a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -44,6 +44,11 @@ importlib-resources = {version = "^5.12.0", python = "<3.9"}
 pytest = "^7.1.3"
 pytest-cov = "^4.0.0"
 
+[tool.pytest.ini_options]
+pythonpath = "src"
+addopts = "--cov --cov-report=html --cov-report=term-missing"
+required_plugins = "pytest-cov>=4.0.0"
+
 [build-system]
 requires = ["poetry-core>=1.0.0"]
 build-backend = "poetry.core.masonry.api"
diff --git a/tox.ini b/tox.ini
index cc73d7a4..a886e184 100644
--- a/tox.ini
+++ b/tox.ini
@@ -10,7 +10,7 @@ envlist = py3{8,9,10,11,12},clean,report
 [testenv]
 deps = pytest
    pytest-cov
-commands = pytest --cov --cov-append --cov-report=term-missing
+commands = pytest --cov-append
 depends =
 	py3{8,9,10,11,12}: clean
 	report: py3{8,9,10,11,12}


Test patch:
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 88f17a0c..bec27ca6 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -52,4 +52,4 @@ jobs:
         if: steps.cache-deps.outputs.cache-hit != 'true'
 
       - run: poetry install
-      - run: poetry run pytest -vv --cov --cov-report=term-missing
+      - run: poetry run pytest -vv
diff --git a/pytest.ini b/pytest.ini
deleted file mode 100644
index 164800de..00000000
--- a/pytest.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[pytest]
-addopts = --tb=native --cov=src --cov-report=html src --junitxml=report.xml
-junit_family = xunit1
diff --git a/src/pycountry/tests/test_general.py b/src/pycountry/tests/test_general.py
index 6fbbe0ae..6c8a3d47 100644
--- a/src/pycountry/tests/test_general.py
+++ b/src/pycountry/tests/test_general.py
@@ -10,19 +10,19 @@
 import pycountry.db
 
 
-@pytest.fixture(autouse=True, scope="session")
-def logging():
-    import logging
-
-    logging.basicConfig(level=logging.DEBUG)
+@pytest.fixture
+def countries():
+    pycountry.countries._clear()
+    yield pycountry.countries
+    pycountry.countries._clear()
 
 
-def test_country_list():
+def test_country_list(countries):
     assert len(pycountry.countries) == 249
     assert isinstance(list(pycountry.countries)[0], pycountry.db.Data)
 
 
-def test_country_fuzzy_search():
+def test_country_fuzzy_search(countries):
     results = pycountry.countries.search_fuzzy("England")
     assert len(results) == 1
     assert results[0] == pycountry.countries.get(alpha_2="GB")
@@ -63,13 +63,13 @@ def test_country_fuzzy_search():
     assert results[0] == pycountry.countries.get(alpha_2="US")
 
 
-def test_historic_country_fuzzy_search():
+def test_historic_country_fuzzy_search(countries):
     results = pycountry.historic_countries.search_fuzzy("burma")
     assert len(results) == 1
     assert results[0] == pycountry.historic_countries.get(alpha_4="BUMM")
 
 
-def test_germany_has_all_attributes():
+def test_germany_has_all_attributes(countries):
     germany = pycountry.countries.get(alpha_2="DE")
     assert germany.alpha_2 == "DE"
     assert germany.alpha_3 == "DEU"
@@ -78,15 +78,17 @@ def test_germany_has_all_attributes():
     assert germany.official_name == "Federal Republic of Germany"
 
 
-def test_missing_common_official_use_same():
+def test_missing_common_official_use_same(countries):
     aruba = pycountry.countries.get(alpha_2="AW")
     assert aruba.alpha_2 == "AW"
     assert aruba.name == "Aruba"
-    assert aruba.official_name == "Aruba"
-    assert aruba.common_name == "Aruba"
+    with pytest.warns(UserWarning, match="official_name not found"):
+        assert aruba.official_name == "Aruba"
+    with pytest.warns(UserWarning, match="common_name not found"):
+        assert aruba.common_name == "Aruba"
 
 
-def test_missing_common_official_use_different():
+def test_missing_common_official_use_different(countries):
     vietnam = pycountry.countries.get(alpha_2="VN")
     assert vietnam.alpha_2 == "VN"
     assert vietnam.name == "Viet Nam"
@@ -94,13 +96,13 @@ def test_missing_common_official_use_different():
     assert vietnam.common_name == "Vietnam"
 
 
-def test_country_missing_attribute():
+def test_country_missing_attribute(countries):
     germany = pycountry.countries.get(alpha_2="DE")
     with pytest.raises(AttributeError):
         _ = germany.foo
 
 
-def test_subdivisions_directly_accessible():
+def test_subdivisions_directly_accessible(countries):
     assert len(pycountry.subdivisions) == 5127
     assert isinstance(list(pycountry.subdivisions)[0], pycountry.db.Data)
 
@@ -179,8 +181,7 @@ def test_locales():
     german = gettext.translation(
         "iso3166-1", pycountry.LOCALES_DIR, languages=["de"]
     )
-    german.install()
-    assert _("Germany") == "Deutschland"
+    assert german.gettext("Germany") == "Deutschland"
 
 
 def test_removed_countries():
@@ -192,7 +193,7 @@ def test_removed_countries():
     assert ussr.withdrawal_date == "1992-08-30"
 
 
-def test_repr():
+def test_repr(countries):
     assert re.match(
         "Country\\(alpha_2=u?'DE', "
         "alpha_3=u?'DEU', "
@@ -204,7 +205,7 @@ def test_repr():
     )
 
 
-def test_dict():
+def test_dict(countries):
     country = pycountry.countries.get(alpha_2="DE")
     exp = {
         "alpha_2": "DE",
@@ -217,13 +218,13 @@ def test_dict():
     assert dict(country) == exp
 
 
-def test_dir():
+def test_dir(countries):
     germany = pycountry.countries.get(alpha_2="DE")
     for n in "alpha_2", "alpha_3", "name", "numeric", "official_name":
         assert n in dir(germany)
 
 
-def test_get():
+def test_get(countries):
     c = pycountry.countries
     with pytest.raises(TypeError):
         c.get(alpha_2="DE", alpha_3="DEU")
@@ -233,7 +234,7 @@ def test_get():
     assert c.get(alpha_2="Foo", default=tracer) is tracer
 
 
-def test_lookup():
+def test_lookup(countries):
     c = pycountry.countries
     g = c.get(alpha_2="DE")
     assert g == c.get(alpha_2="de")
@@ -281,6 +282,10 @@ def test_subdivision_empty_list():
 
 
 def test_has_version_attribute():
+    try:
+        _importlib_metadata.distribution("pycountry")
+    except _importlib_metadata.PackageNotFoundError:
+        pytest.skip("pycountry not installed correctly, you're on your own")
     assert pycountry.__version__ != "n/a"
     assert len(pycountry.__version__) >= 5
     assert "." in pycountry.__version__
@@ -290,7 +295,7 @@ def test_is_instance_of_language():
     assert isinstance(pycountry.languages, pycountry.Languages)
 
 
-def test_is_instance_of_country():
+def test_is_instance_of_country(countries):
     united_states = pycountry.countries.get(alpha_2="US")
     class_name = united_states.__class__.__name__
     assert class_name == "Country"
@@ -308,8 +313,7 @@ def test_is_instance_of_currency():
     assert isinstance(pycountry.currencies, pycountry.Currencies)
 
 
-def test_add_entry():
-    pycountry.countries._clear()
+def test_add_entry(countries):
     assert pycountry.countries.get(alpha_2="XK") is None
 
     pycountry.countries.add_entry(
@@ -320,8 +324,7 @@ def test_add_entry():
     assert isinstance(country, pycountry.countries.data_class)
 
 
-def test_remove_entry():
-    pycountry.countries._clear()
+def test_remove_entry(countries):
     assert pycountry.countries.get(alpha_2="DE") is not None
 
     pycountry.countries.remove_entry(alpha_2="DE")
@@ -329,7 +332,12 @@ def test_remove_entry():
     assert pycountry.countries.get(alpha_2="DE") is None
 
 
-def test_no_results_lookup_error():
+def test_remove_non_existent_entry():
+    with pytest.raises(KeyError, match="not found"):
+        pycountry.countries.remove_entry(name="Not A Real Country")
+
+
+def test_no_results_lookup_error(countries):
     try:
         import importlib_resources  # type: ignore
     except ModuleNotFoundError:
@@ -374,16 +382,16 @@ def test_subdivision_partial_match():
     assert results[0].name == "Massachusetts"
 
 
-def non_country_attribute_error(self):
-    with self.assertRaises(AttributeError):
-        english = pycountry.languages.get(name="English")
-        result = english.official_name
+def test_non_country_attribute_error():
+    english = pycountry.languages.get(name="English")
+    with pytest.raises(AttributeError):
+        english.official_name
 
 
-def country_attribute_error(self):
-    with self.assertRaises(AttributeError):
-        canada = pycountry.countries.get(alpha_2="CA")
-        result = canada.maple_syrup
+def test_country_attribute_error(countries):
+    canada = pycountry.countries.get(alpha_2="CA")
+    with pytest.raises(AttributeError):
+        canada.maple_syrup
 
 
 def test_with_accents():
@@ -449,28 +457,6 @@ def test_all_subdivisions_have_name_attribute():
     assert all_have_name_attr
 
 
-def test_remove_countries():
-    # Test case 1: Removing an existing entry
-    kw1 = {"name": "United States"}
-    try:
-        pycountry.countries.remove_entry(**kw1)
-    except KeyError as e:
-        assert False, f"Unexpected KeyError for 'United States': {e}"
-
-    # Test case 2: Removing a non-existing entry
-    kw2 = {"name": "Non Existent Country"}
-    try:
-        pycountry.countries.remove_entry(**kw2)
-    except KeyError as e:
-        assert "not found and cannot be removed" in str(
-            e
-        )  # Check the error message
-    else:
-        assert (
-            False
-        ), "Expected KeyError for 'Non Existent Country', but no exception was raised"
-
-
 def test_subdivisions_with_missing_parents():
     result = [
         (i.code, i.parent_code)