Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set http caching for tests #207

Open
wants to merge 38 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
a7c44e3
Set http caching for tests
tgrandje Aug 8, 2024
36cc789
Remove version check from unittests
tgrandje Aug 9, 2024
a3de263
Update conftest.py
tgrandje Aug 27, 2024
8ebea8b
Restore insee secrets on local machine after tests
tgrandje Aug 27, 2024
1bb34c7
First try to store artifacts on SSP Cloud
tgrandje Aug 27, 2024
8cc05f0
Update conftest.py
tgrandje Aug 28, 2024
0955cb0
Add hash check of cache before/after session
tgrandje Aug 28, 2024
c234300
Fix typo
tgrandje Aug 28, 2024
fc94a0a
Handle missing cache
tgrandje Aug 29, 2024
ec945f8
Update .gitignore
tgrandje Aug 29, 2024
f1791a7
Add compression of archived cache
tgrandje Aug 30, 2024
b5302b6
Preserve proxies during tests
tgrandje Aug 30, 2024
1b7fa7c
Merge branch 'enhancement/tests_requests_patching' of https://github.…
tgrandje Aug 30, 2024
bcb8f1c
Store proxy to crendentials for perservation during tests
tgrandje Aug 30, 2024
4a39255
Add log entries to pytest session load/teardown + flag bugfix
tgrandje Aug 30, 2024
47eb542
Fix tests exception types
tgrandje Aug 30, 2024
2005993
Better credentials persistence and systemic tempfiles removal before …
tgrandje Aug 30, 2024
c40c504
Merge branch 'master' into enhancement/tests_requests_patching
tgrandje Aug 30, 2024
680cc1f
Bugfix new credentials with proxy from os.environ
tgrandje Aug 30, 2024
55277ad
Remove previous credentials persistence patch
tgrandje Aug 30, 2024
d158177
Bugfix on exception type
tgrandje Aug 30, 2024
f6b92a6
Run test sequentialy to ensure proper caching
tgrandje Aug 30, 2024
5552528
Fix missing application type
tgrandje Sep 2, 2024
92e81ea
Revert "Fix missing application type"
tgrandje Sep 3, 2024
013ccb2
Fix headers matching
tgrandje Sep 3, 2024
7f42bec
Add timers for benchmark
tgrandje Sep 3, 2024
4d22025
Test filesystem backend
tgrandje Sep 3, 2024
ade2acc
Fix cleanup/restoration for filesystem backend
tgrandje Sep 4, 2024
ced1cbf
Fix UnboundLocalError
tgrandje Sep 4, 2024
644d037
Store first benchmark results in project
tgrandje Sep 4, 2024
851edc6
Reset backend to SQLite and Linux exceptions fixed
tgrandje Sep 4, 2024
b7745ae
Remove temp poetry files & benchmark
tgrandje Sep 4, 2024
76190d5
Moved _get_credentials fix to different PR
tgrandje Sep 4, 2024
be1e272
Moved _request_insee exception fixes to different PR
tgrandje Sep 4, 2024
a84e595
Manage corrupted 7z archive
tgrandje Sep 12, 2024
f4fa8f8
Revert exception type in tests (moved to another PR)
tgrandje Sep 12, 2024
8eee51b
Fix conftest with missing/incomplete/invalid SSPCloud credentials
tgrandje Sep 18, 2024
f4913ee
Fix typo
tgrandje Sep 18, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/pkgTests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ jobs:
build:
runs-on: ubuntu-latest
strategy:
max-parallel: 1
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11"]
python-version: ["3.8", "3.12"]

steps:
- uses: actions/checkout@v2
Expand Down Expand Up @@ -46,10 +47,15 @@ jobs:
# run all py files
# for f in *.py; do python "$f"; done
cd ../..
- name: Add requests-cache - s3fs - py7zr
run: pip install requests-cache s3fs py7zr # Used to monkeypatch requests and store artifacts
- name: Test with pytest
env:
insee_key: ${{ secrets.INSEE_KEY }}
insee_secret: ${{ secrets.INSEE_SECRET }}
s3_token: ${{ secrets.S3_TOKEN }}
s3_secret: ${{ secrets.S3_SECRET }}
s3_key: ${{ secrets.S3_KEY }}
run: |
pytest -v --cov
- name: "Upload coverage to Codecov"
Expand Down
8 changes: 7 additions & 1 deletion .github/workflows/pkgTests_pull_requests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ jobs:
build:
runs-on: ubuntu-latest
strategy:
max-parallel: 1
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11"]
python-version: ["3.8", "3.12"]

steps:
- uses: actions/checkout@v4
Expand Down Expand Up @@ -48,10 +49,15 @@ jobs:
# run all py files
# for f in *.py; do python "$f"; done
cd ../..
- name: Add requests-cache - s3fs - py7zr
run: pip install requests-cache s3fs py7zr # Used to monkeypatch requests and store artifacts
- name: Test with pytest
env:
insee_key: ${{ secrets.INSEE_KEY }}
insee_secret: ${{ secrets.INSEE_SECRET }}
s3_token: ${{ secrets.S3_TOKEN }}
s3_secret: ${{ secrets.S3_SECRET }}
s3_key: ${{ secrets.S3_KEY }}
run: |
pytest -v --cov
- name: "Upload coverage to Codecov"
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ docs/examples/.jupyter_cache/*
.spyproject/
poetry.lock
docs/examples/*.csv
docs/examples/*.svg
docs/examples/*.svg
.env
163 changes: 82 additions & 81 deletions pynsee/utils/_get_credentials.py
Original file line number Diff line number Diff line change
@@ -1,81 +1,82 @@
# -*- coding: utf-8 -*-
# Copyright : INSEE, 2021

import json
import logging
import os

from functools import lru_cache
from typing import Dict

from platformdirs import user_config_dir


logger = logging.getLogger(__name__)


def _get_credentials() -> Dict[str, str]:
'''
Try to load credentials.

If the environment variables `insee_key` and `insee_secret` are set, use
these.
Otherwise try to load them from the config file.

Returns a dict containing at least an "insee_key" and an "insee_secret"
entry.
'''
key_dict: Dict[str, str] = {}

try:
key_dict["insee_key"] = os.environ["insee_key"]
key_dict["insee_secret"] = os.environ["insee_secret"]

envir_var_used = True
except KeyError:
envir_var_used = False

config_file = os.path.join(
user_config_dir("pynsee", ensure_exists=True), "config.json")

try:
with open(config_file, "r") as f:
key_dict = json.load(f)

http_proxy = key_dict["http_proxy"]
https_proxy = key_dict["https_proxy"]

if (http_proxy is None) or (not isinstance(http_proxy, str)):
http_proxy = ""
if (https_proxy is None) or (not isinstance(https_proxy, str)):
https_proxy = ""

os.environ["http_proxy"] = http_proxy
os.environ["https_proxy"] = https_proxy
except Exception:
_missing_credentials()

if envir_var_used:
_warn_env_credentials()

return key_dict


@lru_cache(maxsize=None)
def _missing_credentials() -> None:
logger.critical(
"INSEE API credentials have not been found: please try to reuse "
"pynsee.utils.init_conn to save them locally.\n"
"Otherwise, you can still use environment variables as follow:\n\n"
"import os\n"
"os.environ['insee_key'] = 'my_insee_key'\n"
"os.environ['insee_secret'] = 'my_insee_secret'"
)


@lru_cache(maxsize=None)
def _warn_env_credentials() -> None:
logger.warning(
"Existing environment variables used, instead of locally "
"saved credentials"
)
# -*- coding: utf-8 -*-
# Copyright : INSEE, 2021

import json
import logging
import os

from functools import lru_cache
from typing import Dict

from platformdirs import user_config_dir


logger = logging.getLogger(__name__)


def _get_credentials() -> Dict[str, str]:
"""
Try to load credentials.

If the environment variables `insee_key` and `insee_secret` are set, use
these.
Otherwise try to load them from the config file.

Returns a dict containing at least an "insee_key" and an "insee_secret"
entry.
"""
key_dict: Dict[str, str] = {}

try:
key_dict["insee_key"] = os.environ["insee_key"]
key_dict["insee_secret"] = os.environ["insee_secret"]

envir_var_used = True
except KeyError:
envir_var_used = False

config_file = os.path.join(
user_config_dir("pynsee", ensure_exists=True), "config.json"
)

try:
with open(config_file, "r") as f:
key_dict = json.load(f)

http_proxy = key_dict["http_proxy"]
https_proxy = key_dict["https_proxy"]

if (http_proxy is None) or (not isinstance(http_proxy, str)):
http_proxy = ""
if (https_proxy is None) or (not isinstance(https_proxy, str)):
https_proxy = ""

os.environ["http_proxy"] = http_proxy
os.environ["https_proxy"] = https_proxy
except Exception:
_missing_credentials()

if envir_var_used:
_warn_env_credentials()

return key_dict


@lru_cache(maxsize=None)
def _missing_credentials() -> None:
logger.critical(
"INSEE API credentials have not been found: please try to reuse "
"pynsee.utils.init_conn to save them locally.\n"
"Otherwise, you can still use environment variables as follow:\n\n"
"import os\n"
"os.environ['insee_key'] = 'my_insee_key'\n"
"os.environ['insee_secret'] = 'my_insee_secret'"
)


@lru_cache(maxsize=None)
def _warn_env_credentials() -> None:
logger.warning(
"Existing environment variables used, instead of locally "
"saved credentials"
)
12 changes: 8 additions & 4 deletions pynsee/utils/_request_insee.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@

from pynsee.utils._get_token import _get_token
from pynsee.utils._get_credentials import _get_credentials
from pynsee.utils.requests_params import _get_requests_session, _get_requests_headers, _get_requests_proxies
from pynsee.utils.requests_params import (
_get_requests_session,
_get_requests_headers,
_get_requests_proxies,
)

import logging

Expand Down Expand Up @@ -53,7 +57,7 @@ def _request_insee(
print(api_url)
except:
pass

# force sdmx use with a system variable
try:
pynsee_use_sdmx = os.environ["pynsee_use_sdmx"]
Expand All @@ -80,11 +84,11 @@ def _request_insee(

if token is not None:
user_agent = _get_requests_headers()

headers = {
"Accept": file_format,
"Authorization": "Bearer " + token,
'User-Agent': user_agent['User-Agent']
"User-Agent": user_agent["User-Agent"],
}

session = _get_requests_session()
Expand Down
Loading
Loading