cpython/Lib/test/test_importlib/import_
Barry Warsaw 13d4489142
gh-86298: Ensure that __loader__ and __spec__.loader agree in warnings.warn_explicit() (GH-97803)
In `_warnings.c`, in the C equivalent of `warnings.warn_explicit()`, if the module globals are given (and not None), the warning will attempt to get the source line for the issued warning.  To do this, it needs the module's loader.

Previously, it would only look up `__loader__` in the module globals.  In https://github.com/python/cpython/issues/86298 we want to defer to the `__spec__.loader` if available.

The first step on this journey is to check that `loader == __spec__.loader` and issue another warning if it is not.  This commit does that.

Since this is a PoC, only manual testing for now.

```python
# /tmp/foo.py
import warnings

import bar

warnings.warn_explicit(
    'warning!',
    RuntimeWarning,
    'bar.py', 2,
    module='bar knee',
    module_globals=bar.__dict__,
    )
```

```python
# /tmp/bar.py
import sys
import os
import pathlib

# __loader__ = pathlib.Path()
```

Then running this: `./python.exe -Wdefault /tmp/foo.py`

Produces:

```
bar.py:2: RuntimeWarning: warning!
  import os
```

Uncomment the `__loader__ = ` line in `bar.py` and try it again:

```
sys:1: ImportWarning: Module bar; __loader__ != __spec__.loader (<_frozen_importlib_external.SourceFileLoader object at 0x109f7dfa0> != PosixPath('.'))
bar.py:2: RuntimeWarning: warning!
  import os
```

Automerge-Triggered-By: GH:warsaw
2022-10-06 19:32:53 -07:00
..
__init__.py
__main__.py
test___loader__.py
test___package__.py gh-65961: Raise `DeprecationWarning` when `__package__` differs from `__spec__.parent` (#97879) 2022-10-05 15:00:45 -07:00
test_api.py
test_caching.py
test_fromlist.py
test_helpers.py gh-86298: Ensure that __loader__ and __spec__.loader agree in warnings.warn_explicit() (GH-97803) 2022-10-06 19:32:53 -07:00
test_meta_path.py
test_packages.py
test_path.py gh-93461: Invalidate sys.path_importer_cache entries with relative paths (GH-93653) 2022-06-10 23:56:26 +02:00
test_relative_imports.py