instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
stringclasses 1
value | environment_setup_commit
stringlengths 40
40
| FAIL_TO_PASS
listlengths 1
4.94k
| PASS_TO_PASS
listlengths 0
7.82k
| meta
dict | created_at
stringlengths 25
25
| license
stringclasses 8
values | __index_level_0__
int64 0
6.41k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mie-lab__trackintel-561
|
diff --git a/README.md b/README.md
index 0afb7c7..e729d60 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ The image below explicitly shows the definition of **locations** as clustered **
You can enter the *trackintel* framework if your data corresponds to any of the above mentioned movement data representation. Here are some of the functionalities that we provide:
* **Import**: Import from the following data formats is supported: `geopandas dataframes` (recommended), `csv files` in a specified format, `postGIS` databases. We also provide specific dataset readers for popular public datasets (e.g, geolife).
-* **Aggregation**: We provide functionalities to aggregate into the next level of our data model. E.g., positionfixes->staypoints; positionfixes->triplegs; staypoints->locations; staypoints+triplegs->trips; trips->tours
+* **Aggregation**: We provide functionalities to aggregate into the next level of our data model. E.g., positionfixes→staypoints; positionfixes→triplegs; staypoints→locations; staypoints+triplegs→trips; trips→tours
* **Enrichment**: Activity semantics for staypoints; Mode of transport semantics for triplegs; High level semantics for locations
## How it works
@@ -58,9 +58,9 @@ import geopandas as gpd
import trackintel as ti
# read pfs from csv file
-pfs = ti.io.file.read_positionfixes_csv(".\examples\data\pfs.csv", sep=";", index_col="id")
+pfs = ti.io.read_positionfixes_csv(".\examples\data\pfs.csv", sep=";", index_col="id")
# or with predefined dataset readers (here geolife)
-pfs, _ = ti.io.dataset_reader.read_geolife(".\tests\data\geolife_long")
+pfs, _ = ti.io.read_geolife(".\tests\data\geolife_long")
```
**[2.]** Data model generation.
diff --git a/trackintel/model/staypoints.py b/trackintel/model/staypoints.py
index f5c97b1..1fc7286 100644
--- a/trackintel/model/staypoints.py
+++ b/trackintel/model/staypoints.py
@@ -154,3 +154,13 @@ class Staypoints(TrackintelBase, TrackintelGeoDataFrame):
See :func:`trackintel.analysis.temporal_tracking_quality` for full documentation.
"""
return ti.analysis.tracking_quality.temporal_tracking_quality(self, granularity=granularity)
+
+ def generate_trips(self, triplegs, gap_threshold=15, add_geometry=True):
+ """
+ Generate trips based on staypoints and triplegs.
+
+ See :func:`trackintel.preprocessing.generate_triplegs` for full documentation.
+ """
+ return ti.preprocessing.triplegs.generate_trips(
+ self, triplegs, gap_threshold=gap_threshold, add_geometry=add_geometry
+ )
|
mie-lab/trackintel
|
3ce2ea4c2aa16006e5c1f358ef6663234dedaa01
|
diff --git a/tests/preprocessing/test_triplegs.py b/tests/preprocessing/test_triplegs.py
index af99006..31448aa 100644
--- a/tests/preprocessing/test_triplegs.py
+++ b/tests/preprocessing/test_triplegs.py
@@ -122,7 +122,7 @@ class TestGenerate_trips:
assert correct_dest_point == dest_point_trips
- def test_accessor(self, example_triplegs):
+ def test_accessor_triplegs(self, example_triplegs):
"""Test if the accessor leads to the same results as the explicit function."""
sp, tpls = example_triplegs
@@ -137,6 +137,21 @@ class TestGenerate_trips:
assert_geodataframe_equal(sp_expl, sp_acc)
assert_geodataframe_equal(tpls_acc, tpls_expl)
+ def test_accessor_staypoints(self, example_triplegs):
+ """Test if the accessor leads to the same results as the explicit function."""
+ sp, tpls = example_triplegs
+
+ # generate trips using the explicit function import
+ sp_expl, tpls_expl, trips_expl = ti.preprocessing.triplegs.generate_trips(sp, tpls, gap_threshold=15)
+
+ # generate trips using the accessor
+ sp_acc, tpls_acc, trips_acc = sp.as_staypoints.generate_trips(tpls, gap_threshold=15)
+
+ # test if generated trips are equal
+ assert_geodataframe_equal(trips_expl, trips_acc)
+ assert_geodataframe_equal(sp_expl, sp_acc)
+ assert_geodataframe_equal(tpls_acc, tpls_expl)
+
def test_generate_trips_missing_link(self, example_triplegs):
"""Test nan is assigned for missing link between sp and trips, and tpls and trips."""
sp, tpls = example_triplegs
|
ENH: Enable `generate_trips` for `Staypoints`
`generate_trips` function need staypoints and triplegs as argument. I would find it coherent to add a `generate_trips` method to `Staypoints` as well and not only to `Triplegs`
|
0.0
|
3ce2ea4c2aa16006e5c1f358ef6663234dedaa01
|
[
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_accessor_staypoints"
] |
[
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_duplicate_columns",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_generate_trips",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_trip_wo_geom",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_trip_coordinates",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_accessor_triplegs",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_generate_trips_missing_link",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_generate_trips_dtype_consistent",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_compare_to_old_trip_function",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_generate_trips_index_start",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_generate_trips_gap_detection",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_generate_trips_id_management",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_only_staypoints_in_trip",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_sp_tpls_index",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_loop_linestring_case",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_keeping_all_columns_sp_tpls",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_missing_is_activity_column",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_crs",
"tests/preprocessing/test_triplegs.py::TestGenerate_trips::test_trips_type"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-29 23:50:55+00:00
|
mit
| 3,935 |
|
mie-lab__trackintel-581
|
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index c816663..ed07d36 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -13,7 +13,7 @@ ci:
repos:
- repo: https://github.com/psf/black
- rev: 23.10.1
+ rev: 23.11.0
hooks:
- id: black
args: [
diff --git a/trackintel/io/dataset_reader.py b/trackintel/io/dataset_reader.py
index 25c4cc3..c2c6b2a 100644
--- a/trackintel/io/dataset_reader.py
+++ b/trackintel/io/dataset_reader.py
@@ -700,10 +700,13 @@ def read_gpx(path):
Positionfixes
"""
pattern = os.path.join(path, "*.gpx")
+ # sorted to make result deterministic
+ files = sorted(glob.glob(pattern))
+ if not files:
+ raise FileNotFoundError(f'Found no gpx files in path "{path}"')
pfs_list = []
track_fid_offset = 0
- # sorted to make result deterministic
- for file in sorted(glob.glob(pattern)):
+ for file in files:
pfs = _read_single_gpx_file(file)
# give each track an unique ID
pfs["track_fid"] += track_fid_offset
|
mie-lab/trackintel
|
b43c225d071d38170a14e5f6cd1d9be565eb59c4
|
diff --git a/tests/io/test_dataset_reader.py b/tests/io/test_dataset_reader.py
index d963554..577d7c8 100644
--- a/tests/io/test_dataset_reader.py
+++ b/tests/io/test_dataset_reader.py
@@ -268,3 +268,8 @@ class TestGpx_reader:
}
pfs_test = Positionfixes(data, geometry="geometry", crs=4326)
assert_geodataframe_equal(pfs, pfs_test)
+
+ def test_missing_files(self):
+ """Test if useful message is output if directory has no gpx files"""
+ with pytest.raises(FileNotFoundError, match="Found no gpx files"):
+ read_gpx(os.path.join("tests", "data"))
|
Raise error in gpx reader if path does not exist
We had a problem that the gpx reader function still executed even though the path did not exist, and then an error was only thrown in the last line `pd.concat(pfs_list, ignore_index=True)` with the error `no objects to concatenate`. There should be an error `Path does not exist` or so
|
0.0
|
b43c225d071d38170a14e5f6cd1d9be565eb59c4
|
[
"tests/io/test_dataset_reader.py::TestGpx_reader::test_missing_files"
] |
[
"tests/io/test_dataset_reader.py::TestReadGeolife::test_loop_read",
"tests/io/test_dataset_reader.py::TestReadGeolife::test_print_progress_flag",
"tests/io/test_dataset_reader.py::TestReadGeolife::test_label_reading",
"tests/io/test_dataset_reader.py::TestReadGeolife::test_wrong_folder_name",
"tests/io/test_dataset_reader.py::TestReadGeolife::test_no_user_folders",
"tests/io/test_dataset_reader.py::Test_GetLabels::test_example_data",
"tests/io/test_dataset_reader.py::Test_GetDf::test_example_data",
"tests/io/test_dataset_reader.py::TestGeolife_add_modes_to_triplegs::test_duplicate_matching",
"tests/io/test_dataset_reader.py::TestGeolife_add_modes_to_triplegs::test_geolife_mode_matching",
"tests/io/test_dataset_reader.py::TestGeolife_add_modes_to_triplegs::test_no_overlap",
"tests/io/test_dataset_reader.py::TestGeolife_add_modes_to_triplegs::test_mode_matching",
"tests/io/test_dataset_reader.py::TestGeolife_add_modes_to_triplegs::test_mode_matching_multi_user",
"tests/io/test_dataset_reader.py::TestGeolife_add_modes_to_triplegs::test_impossible_matching"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-13 18:59:27+00:00
|
mit
| 3,936 |
|
mie-lab__trackintel-588
|
diff --git a/trackintel/preprocessing/trips.py b/trackintel/preprocessing/trips.py
index 7df3e87..b197964 100644
--- a/trackintel/preprocessing/trips.py
+++ b/trackintel/preprocessing/trips.py
@@ -8,6 +8,7 @@ from tqdm import tqdm
import trackintel as ti
from trackintel import Tours, Trips
+from trackintel.preprocessing.util import applyParallel
def get_trips_grouped(trips, tours):
@@ -59,6 +60,7 @@ def generate_tours(
max_time="1d",
max_nr_gaps=0,
print_progress=False,
+ n_jobs=1,
):
"""
Generate trackintel-tours from trips
@@ -85,6 +87,12 @@ def generate_tours(
print_progress : bool, default False
If print_progress is True, the progress bar is displayed
+ n_jobs: int, default 1
+ The maximum number of concurrently running jobs. If -1 all CPUs are used. If 1 is given, no parallel
+ computing code is used at all, which is useful for debugging. See
+ https://joblib.readthedocs.io/en/latest/parallel.html#parallel-reference-documentation
+ for a detailed description
+
Returns
-------
trips_with_tours: Trips
@@ -150,19 +158,14 @@ def generate_tours(
"geom_col": geom_col,
"crs_is_projected": crs_is_projected,
}
- if print_progress:
- tqdm.pandas(desc="User tour generation")
- tours = (
- trips_input.groupby(["user_id"], group_keys=False, as_index=False)
- .progress_apply(_generate_tours_user, **kwargs)
- .reset_index(drop=True)
- )
- else:
- tours = (
- trips_input.groupby(["user_id"], group_keys=False, as_index=False)
- .apply(_generate_tours_user, **kwargs)
- .reset_index(drop=True)
- )
+
+ tours = applyParallel(
+ trips_input.groupby("user_id", group_keys=False, as_index=False),
+ _generate_tours_user,
+ print_progress=print_progress,
+ n_jobs=n_jobs,
+ **kwargs
+ )
# No tours found
if len(tours) == 0:
|
mie-lab/trackintel
|
879bd126f1b6e9e624309b483c44c90d33e62ab0
|
diff --git a/tests/preprocessing/test_trips.py b/tests/preprocessing/test_trips.py
index 8cd1a07..0043423 100644
--- a/tests/preprocessing/test_trips.py
+++ b/tests/preprocessing/test_trips.py
@@ -146,8 +146,8 @@ class TestGenerate_tours:
def test_generate_tours(self, example_trip_data):
"""Test general functionality of generate tours function"""
- trips, sp_locs = example_trip_data
- trips_out, tours = ti.preprocessing.trips.generate_tours(trips)
+ trips, _ = example_trip_data
+ trips_out, _ = ti.preprocessing.trips.generate_tours(trips)
# check that nothing else than the new column has changed in trips df
assert all(trips_out.iloc[:, :6] == trips)
# check that the two tours were found
@@ -161,9 +161,22 @@ class TestGenerate_tours:
user_1_df = trips_out[trips_out["user_id"] == 1]
assert all(pd.isna(user_1_df["tour_id"]))
+ def test_parallel_computing(self, example_trip_data):
+ """The result obtained with parallel computing should be identical."""
+ trips, _ = example_trip_data
+
+ # without parallel computing code
+ trips_ori, tours_ori = ti.preprocessing.trips.generate_tours(trips, n_jobs=1)
+ # using two cores
+ trips_para, tours_para = ti.preprocessing.trips.generate_tours(trips, n_jobs=2)
+
+ # the result of parallel computing should be identical
+ assert_geodataframe_equal(trips_ori, trips_para)
+ pd.testing.assert_frame_equal(tours_ori, tours_para)
+
def test_tours_with_gap(self, example_trip_data):
"""Test functionality of max_nr_gaps parameter in tour generation"""
- trips, sp_locs = example_trip_data
+ trips, _ = example_trip_data
trips_out, tours = ti.preprocessing.trips.generate_tours(trips, max_nr_gaps=1)
# new tour was found for user 1
assert len(tours) == 3
@@ -172,8 +185,8 @@ class TestGenerate_tours:
def test_tour_times(self, example_trip_data):
"""Check whether the start and end times of generated tours are correct"""
- trips, sp_locs = example_trip_data
- trips_out, tours = ti.preprocessing.trips.generate_tours(trips, max_nr_gaps=1, max_time="1d")
+ trips, _ = example_trip_data
+ _, tours = ti.preprocessing.trips.generate_tours(trips, max_nr_gaps=1, max_time="1d")
# check that all times are below the max time
for i, row in tours.iterrows():
time_diff = row["finished_at"] - row["started_at"]
@@ -189,16 +202,16 @@ class TestGenerate_tours:
def test_tour_geom(self, example_trip_data):
"""Test whether tour generation is invariant to the name of the geometry column"""
- trips, sp_locs = example_trip_data
+ trips, _ = example_trip_data
trips.rename(columns={"geom": "other_geom_name"}, inplace=True)
trips = trips.set_geometry("other_geom_name")
- trips_out, tours = ti.preprocessing.trips.generate_tours(trips)
+ trips_out, _ = ti.preprocessing.trips.generate_tours(trips)
# check that nothing else than the new column has changed in trips df
assert all(trips_out.iloc[:, :6] == trips)
def test_tour_max_time(self, example_trip_data):
"""Test functionality of max time argument in tour generation"""
- trips, sp_locs = example_trip_data
+ trips, _ = example_trip_data
with pytest.warns(UserWarning, match="No tours can be generated, return empty tours"):
_, tours = ti.preprocessing.trips.generate_tours(trips, max_time="2h") # only 2 hours allowed
assert len(tours) == 0
@@ -208,7 +221,7 @@ class TestGenerate_tours:
def test_tours_locations(self, example_trip_data):
"""Test whether tour generation with locations as input yields correct results as well"""
trips, sp_locs = example_trip_data
- trips_out, tours = ti.preprocessing.trips.generate_tours(trips, staypoints=sp_locs, max_nr_gaps=1)
+ _, tours = ti.preprocessing.trips.generate_tours(trips, staypoints=sp_locs, max_nr_gaps=1)
assert all(tours["location_id"] == pd.Series([1, 2, 2]))
# group trips by tour and check that the locations of start and end of each tour are correct
@@ -263,12 +276,12 @@ class TestGenerate_tours:
def test_print_progress_flag(self, example_trip_data, capsys):
"""Test if the print_progress bar controls the printing behavior."""
- trips, sp_locs = example_trip_data
- trips_out, tours = ti.preprocessing.trips.generate_tours(trips, print_progress=True)
+ trips, _ = example_trip_data
+ ti.preprocessing.trips.generate_tours(trips, print_progress=True)
captured_print = capsys.readouterr()
assert captured_print.err != ""
- trips_out, tours = ti.preprocessing.trips.generate_tours(trips, print_progress=False)
+ ti.preprocessing.trips.generate_tours(trips, print_progress=False)
captured_noprint = capsys.readouterr()
assert captured_noprint.err == ""
|
Support multiprocessing for generate_tours
It would be great if `generate_tours` would support parallelization. This can be easily implemented by using [apply_parallel](https://github.com/mie-lab/trackintel/blob/master/trackintel/preprocessing/util.py#L42)
instead of [apply](https://github.com/mie-lab/trackintel/blob/master/trackintel/preprocessing/trips.py#L152) as it is for example done in `generate_locations` [here](https://github.com/mie-lab/trackintel/blob/master/trackintel/preprocessing/staypoints.py#L96)
|
0.0
|
879bd126f1b6e9e624309b483c44c90d33e62ab0
|
[
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_parallel_computing"
] |
[
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_generate_tours",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tours_with_gap",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tour_times",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tour_geom",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tour_max_time",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tours_locations",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tours_crs",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_generate_tours_geolife",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_accessor",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_print_progress_flag",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_index_stability",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_nested_tour",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tours_warn_existing_column",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tours_time_gap_error",
"tests/preprocessing/test_trips.py::TestGenerate_tours::test_tours_type",
"tests/preprocessing/test_trips.py::TestTourHelpers::test_get_trips_grouped"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-12-25 20:34:45+00:00
|
mit
| 3,937 |
|
miguelgrinberg__python-engineio-108
|
diff --git a/engineio/async_drivers/asgi.py b/engineio/async_drivers/asgi.py
index 64ac4d4..9f8d9ce 100644
--- a/engineio/async_drivers/asgi.py
+++ b/engineio/async_drivers/asgi.py
@@ -40,54 +40,50 @@ class ASGIApp:
self.engineio_path = engineio_path.strip('/')
self.static_files = static_files or {}
- def __call__(self, scope):
+ async def __call__(self, scope, receive, send):
if scope['type'] in ['http', 'websocket'] and \
scope['path'].startswith('/{0}/'.format(self.engineio_path)):
- return self.engineio_asgi_app(scope)
+ await self.engineio_asgi_app(scope, receive, send)
elif scope['type'] == 'http' and scope['path'] in self.static_files:
- return self.serve_static_file(scope)
+ await self.serve_static_file(scope, receive, send)
elif self.other_asgi_app is not None:
- return self.other_asgi_app(scope)
+ await self.other_asgi_app(scope, receive, send)
elif scope['type'] == 'lifespan':
- return self.lifespan
+ await self.lifespan(scope, receive, send)
else:
- return self.not_found
+ await self.not_found(scope, receive, send)
- def engineio_asgi_app(self, scope):
- async def _app(receive, send):
- await self.engineio_server.handle_request(scope, receive, send)
- return _app
+ async def engineio_asgi_app(self, scope, receive, send):
+ await self.engineio_server.handle_request(scope, receive, send)
- def serve_static_file(self, scope):
- async def _send_static_file(receive, send): # pragma: no cover
- event = await receive()
- if event['type'] == 'http.request':
- if scope['path'] in self.static_files:
- content_type = self.static_files[scope['path']][
- 'content_type'].encode('utf-8')
- filename = self.static_files[scope['path']]['filename']
- status_code = 200
- with open(filename, 'rb') as f:
- payload = f.read()
- else:
- content_type = b'text/plain'
- status_code = 404
- payload = b'not found'
- await send({'type': 'http.response.start',
- 'status': status_code,
- 'headers': [(b'Content-Type', content_type)]})
- await send({'type': 'http.response.body',
- 'body': payload})
- return _send_static_file
-
- async def lifespan(self, receive, send):
+ async def serve_static_file(self, scope, receive, send):
+ event = await receive()
+ if event['type'] == 'http.request':
+ if scope['path'] in self.static_files:
+ content_type = self.static_files[scope['path']][
+ 'content_type'].encode('utf-8')
+ filename = self.static_files[scope['path']]['filename']
+ status_code = 200
+ with open(filename, 'rb') as f:
+ payload = f.read()
+ else:
+ content_type = b'text/plain'
+ status_code = 404
+ payload = b'not found'
+ await send({'type': 'http.response.start',
+ 'status': status_code,
+ 'headers': [(b'Content-Type', content_type)]})
+ await send({'type': 'http.response.body',
+ 'body': payload})
+
+ async def lifespan(self, scope, receive, send):
event = await receive()
if event['type'] == 'lifespan.startup':
await send({'type': 'lifespan.startup.complete'})
elif event['type'] == 'lifespan.shutdown':
await send({'type': 'lifespan.shutdown.complete'})
- async def not_found(self, receive, send):
+ async def not_found(self, scope, receive, send):
"""Return a 404 Not Found error to the client."""
await send({'type': 'http.response.start',
'status': 404,
|
miguelgrinberg/python-engineio
|
88400ba57cb5173e36d8305fbdb10b483895be08
|
diff --git a/tests/asyncio/test_async_asgi.py b/tests/asyncio/test_async_asgi.py
index 035bf65..a5e7b9e 100644
--- a/tests/asyncio/test_async_asgi.py
+++ b/tests/asyncio/test_async_asgi.py
@@ -45,17 +45,16 @@ class AsgiTests(unittest.TestCase):
mock_server.handle_request = AsyncMock()
app = async_asgi.ASGIApp(mock_server)
scope = {'type': 'http', 'path': '/engine.io/'}
- handler = app(scope)
- _run(handler('receive', 'send'))
+ _run(app(scope, 'receive', 'send'))
mock_server.handle_request.mock.assert_called_once_with(
scope, 'receive', 'send')
def test_other_app_routing(self):
- other_app = mock.MagicMock()
+ other_app = AsyncMock()
app = async_asgi.ASGIApp('eio', other_app)
scope = {'type': 'http', 'path': '/foo'}
- app(scope)
- other_app.assert_called_once_with(scope)
+ _run(app(scope, 'receive', 'send'))
+ other_app.mock.assert_called_once_with(scope, 'receive', 'send')
def test_static_file_routing(self):
root_dir = os.path.dirname(__file__)
@@ -63,45 +62,45 @@ class AsgiTests(unittest.TestCase):
'/foo': {'content_type': 'text/html',
'filename': root_dir + '/index.html'}
})
- handler = app({'type': 'http', 'path': '/foo'})
+ scope = {'type': 'http', 'path': '/foo'}
receive = AsyncMock(return_value={'type': 'http.request'})
send = AsyncMock()
- _run(handler(receive, send))
+ _run(app(scope, receive, send))
send.mock.assert_called_with({'type': 'http.response.body',
'body': b'<html></html>\n'})
def test_lifespan_startup(self):
app = async_asgi.ASGIApp('eio')
- handler = app({'type': 'lifespan'})
+ scope = {'type': 'lifespan'}
receive = AsyncMock(return_value={'type': 'lifespan.startup'})
send = AsyncMock()
- _run(handler(receive, send))
+ _run(app(scope, receive, send))
send.mock.assert_called_once_with(
{'type': 'lifespan.startup.complete'})
def test_lifespan_shutdown(self):
app = async_asgi.ASGIApp('eio')
- handler = app({'type': 'lifespan'})
+ scope = {'type': 'lifespan'}
receive = AsyncMock(return_value={'type': 'lifespan.shutdown'})
send = AsyncMock()
- _run(handler(receive, send))
+ _run(app(scope, receive, send))
send.mock.assert_called_once_with(
{'type': 'lifespan.shutdown.complete'})
def test_lifespan_invalid(self):
app = async_asgi.ASGIApp('eio')
- handler = app({'type': 'lifespan'})
+ scope = {'type': 'lifespan'}
receive = AsyncMock(return_value={'type': 'lifespan.foo'})
send = AsyncMock()
- _run(handler(receive, send))
+ _run(app(scope, receive, send))
send.mock.assert_not_called()
def test_not_found(self):
app = async_asgi.ASGIApp('eio')
- handler = app({'type': 'http', 'path': '/foo'})
+ scope = {'type': 'http', 'path': '/foo'}
receive = AsyncMock(return_value={'type': 'http.request'})
send = AsyncMock()
- _run(handler(receive, send))
+ _run(app(scope, receive, send))
send.mock.assert_any_call(
{'type': 'http.response.start', 'status': 404,
'headers': [(b'Content-Type', b'text/plain')]})
|
ASGI3
Hi!
About a month ago, the ASGI protocol got an overhaul with [ASGI 3.0](https://www.aeracode.org/2019/03/20/asgi-30/).
All major ASGI servers (uvicorn, daphne, hypercorn) now support ASGI3, and the whole ecosystem seems to be shifting in that direction too.
Shouldn't this package start moving to ASGI3 too? :+1:
(I think the relevant part of the docs is [Uvicorn, Daphne, and other ASGI servers](https://python-engineio.readthedocs.io/en/latest/server.html#uvicorn-daphne-and-other-asgi-servers)).
I'd be happy to provide a PR for this!
|
0.0
|
88400ba57cb5173e36d8305fbdb10b483895be08
|
[
"tests/asyncio/test_async_asgi.py::AsgiTests::test_engineio_routing",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_lifespan_invalid",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_lifespan_shutdown",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_lifespan_startup",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_not_found",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_other_app_routing",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_static_file_routing"
] |
[
"tests/asyncio/test_async_asgi.py::AsgiTests::test_create_app",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_make_response",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_translate_request",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_translate_request_no_query_string",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_translate_request_with_large_body",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_translate_unknown_request",
"tests/asyncio/test_async_asgi.py::AsgiTests::test_translate_websocket_request"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-04-28 16:23:07+00:00
|
mit
| 3,938 |
|
miguelgrinberg__python-socketio-319
|
diff --git a/socketio/asyncio_redis_manager.py b/socketio/asyncio_redis_manager.py
index 2265937..21499c2 100644
--- a/socketio/asyncio_redis_manager.py
+++ b/socketio/asyncio_redis_manager.py
@@ -12,8 +12,9 @@ from .asyncio_pubsub_manager import AsyncPubSubManager
def _parse_redis_url(url):
p = urlparse(url)
- if p.scheme != 'redis':
+ if p.scheme not in {'redis', 'rediss'}:
raise ValueError('Invalid redis url')
+ ssl = p.scheme == 'rediss'
host = p.hostname or 'localhost'
port = p.port or 6379
password = p.password
@@ -21,7 +22,7 @@ def _parse_redis_url(url):
db = int(p.path[1:])
else:
db = 0
- return host, port, password, db
+ return host, port, password, db, ssl
class AsyncRedisManager(AsyncPubSubManager): # pragma: no cover
@@ -39,7 +40,8 @@ class AsyncRedisManager(AsyncPubSubManager): # pragma: no cover
'redis://hostname:port/0'))
:param url: The connection URL for the Redis server. For a default Redis
- store running on the same host, use ``redis://``.
+ store running on the same host, use ``redis://``. To use an
+ SSL connection, use ``rediss://``.
:param channel: The channel name on which the server sends and receives
notifications. Must be the same in all the servers.
:param write_only: If set ot ``True``, only initialize to emit events. The
@@ -54,7 +56,9 @@ class AsyncRedisManager(AsyncPubSubManager): # pragma: no cover
raise RuntimeError('Redis package is not installed '
'(Run "pip install aioredis" in your '
'virtualenv).')
- self.host, self.port, self.password, self.db = _parse_redis_url(url)
+ (
+ self.host, self.port, self.password, self.db, self.ssl
+ ) = _parse_redis_url(url)
self.pub = None
self.sub = None
super().__init__(channel=channel, write_only=write_only, logger=logger)
@@ -66,7 +70,8 @@ class AsyncRedisManager(AsyncPubSubManager): # pragma: no cover
if self.pub is None:
self.pub = await aioredis.create_redis(
(self.host, self.port), db=self.db,
- password=self.password)
+ password=self.password, ssl=self.ssl
+ )
return await self.pub.publish(self.channel,
pickle.dumps(data))
except (aioredis.RedisError, OSError):
@@ -87,7 +92,8 @@ class AsyncRedisManager(AsyncPubSubManager): # pragma: no cover
if self.sub is None:
self.sub = await aioredis.create_redis(
(self.host, self.port), db=self.db,
- password=self.password)
+ password=self.password, ssl=self.ssl
+ )
self.ch = (await self.sub.subscribe(self.channel))[0]
return await self.ch.get()
except (aioredis.RedisError, OSError):
|
miguelgrinberg/python-socketio
|
5e7c4df9753abd4fc6031a6020284d8f9523ed72
|
diff --git a/tests/asyncio/test_asyncio_redis_manager.py b/tests/asyncio/test_asyncio_redis_manager.py
index 02c12d6..cbcaf6a 100644
--- a/tests/asyncio/test_asyncio_redis_manager.py
+++ b/tests/asyncio/test_asyncio_redis_manager.py
@@ -8,37 +8,37 @@ from socketio import asyncio_redis_manager
class TestAsyncRedisManager(unittest.TestCase):
def test_default_url(self):
self.assertEqual(asyncio_redis_manager._parse_redis_url('redis://'),
- ('localhost', 6379, None, 0))
+ ('localhost', 6379, None, 0, False))
def test_only_host_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://redis.host'),
- ('redis.host', 6379, None, 0))
+ ('redis.host', 6379, None, 0, False))
def test_no_db_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://redis.host:123/1'),
- ('redis.host', 123, None, 1))
+ ('redis.host', 123, None, 1, False))
def test_no_port_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://redis.host/1'),
- ('redis.host', 6379, None, 1))
+ ('redis.host', 6379, None, 1, False))
def test_password(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://:[email protected]/1'),
- ('redis.host', 6379, 'pw', 1))
+ ('redis.host', 6379, 'pw', 1, False))
def test_no_host_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://:123/1'),
- ('localhost', 123, None, 1))
+ ('localhost', 123, None, 1, False))
def test_no_host_password_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://:pw@:123/1'),
- ('localhost', 123, 'pw', 1))
+ ('localhost', 123, 'pw', 1, False))
def test_bad_port_url(self):
self.assertRaises(ValueError, asyncio_redis_manager._parse_redis_url,
@@ -51,3 +51,9 @@ class TestAsyncRedisManager(unittest.TestCase):
def test_bad_scheme_url(self):
self.assertRaises(ValueError, asyncio_redis_manager._parse_redis_url,
'http://redis.host:123/1')
+
+ def test_ssl_scheme(self):
+ self.assertEqual(
+ asyncio_redis_manager._parse_redis_url('rediss://'),
+ ('localhost', 6379, None, 0, True)
+ )
|
AsyncRedisManager SSL Support
Is there a way to use SSL with the AsyncRedisManager? This is possible with RedisManager by passing in a "rediss" scheme instead of a "redis" scheme, but I don't see a way to do it with the Async manager.
I have sort of patched in a way to do this just by adding an "ssl" option to `AsyncRedisManager.__init__()`, then passing it through to `aioredis.create_redis()` in `_publish` and `_listen`. Happy to do a pull request if that's the right way to do this.
|
0.0
|
5e7c4df9753abd4fc6031a6020284d8f9523ed72
|
[
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_default_url",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_no_db_url",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_no_host_password_url",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_no_host_url",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_no_port_url",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_only_host_url",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_password",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_ssl_scheme"
] |
[
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_bad_db_url",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_bad_port_url",
"tests/asyncio/test_asyncio_redis_manager.py::TestAsyncRedisManager::test_bad_scheme_url"
] |
{
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-07-19 15:40:23+00:00
|
mit
| 3,939 |
|
mikeckennedy__markdown-subtemplate-8
|
diff --git a/markdown_subtemplate/__init__.py b/markdown_subtemplate/__init__.py
index 82b3d4f..e1fe900 100644
--- a/markdown_subtemplate/__init__.py
+++ b/markdown_subtemplate/__init__.py
@@ -3,7 +3,7 @@ markdown_subtemplate - A template engine to render
Markdown with external template imports and variable replacements.
"""
-__version__ = '0.1.20'
+__version__ = '0.2.21'
__author__ = 'Michael Kennedy <[email protected]>'
__all__ = []
diff --git a/markdown_subtemplate/infrastructure/page.py b/markdown_subtemplate/infrastructure/page.py
index d4e8d94..0f9a67e 100644
--- a/markdown_subtemplate/infrastructure/page.py
+++ b/markdown_subtemplate/infrastructure/page.py
@@ -7,6 +7,7 @@ from markdown_subtemplate.infrastructure import markdown_transformer
from markdown_subtemplate.exceptions import ArgumentExpectedException, TemplateNotFoundException
from markdown_subtemplate import logging as __logging
import markdown_subtemplate.storage as __storage
+from markdown_subtemplate.logging import SubtemplateLogger
from markdown_subtemplate.storage import SubtemplateStorage
@@ -37,11 +38,14 @@ def get_page(template_path: str, data: Dict[str, Any]) -> str:
# Get the markdown with imports and substitutions
markdown = get_markdown(template_path)
+ inline_variables = {}
+ markdown = get_inline_variables(markdown, inline_variables, log)
# Convert markdown to HTML
html = get_html(markdown)
cache.add_html(key, key, html)
- html = process_variables(html, data)
+ full_data = {**data, **inline_variables}
+ html = process_variables(html, full_data)
dt = datetime.datetime.now() - t0
@@ -174,3 +178,42 @@ def process_variables(raw_text: str, data: Dict[str, Any]) -> str:
transformed_text = transformed_text.replace(key_placeholders[key], str(data[key]))
return transformed_text
+
+
+def get_inline_variables(markdown: str, new_vars: Dict[str, str], log: SubtemplateLogger) -> str:
+ lines: List[str] = markdown.split('\n')
+ pattern = '[VARIABLE '
+
+ final_lines = []
+
+ for l in lines:
+
+ if not( l and l.upper().startswith(pattern)):
+ final_lines.append(l)
+ continue
+
+ text = l[len(pattern):].strip("]")
+ parts = text.split('=')
+ if len(parts) != 2:
+ log.error(f"Invalid variable definition in markdown: {l}.")
+ continue
+
+ name = parts[0].strip().upper()
+ value = parts[1].strip()
+ has_quotes = (
+ (value.startswith('"') or value.startswith("'")) and
+ (value.endswith('"') or value.endswith("'"))
+ )
+
+ if not has_quotes:
+ log.error(f"Invalid variable definition in markdown, missing quotes surrounding value: {l}.")
+ continue
+
+ value = value.strip('\'"').strip()
+
+ new_vars[name]=value
+
+ if new_vars:
+ return "\n".join(final_lines)
+ else:
+ return markdown
|
mikeckennedy/markdown-subtemplate
|
29737dbad109ee3d943872751bdb11f64df51431
|
diff --git a/tests/page_tests.py b/tests/page_tests.py
index 419223e..403be3b 100644
--- a/tests/page_tests.py
+++ b/tests/page_tests.py
@@ -2,10 +2,10 @@ import os
import pytest
-from markdown_subtemplate import exceptions
from markdown_subtemplate import engine
-from markdown_subtemplate.storage.file_storage import FileStore
+from markdown_subtemplate import exceptions
from markdown_subtemplate.infrastructure import page
+from markdown_subtemplate.storage.file_storage import FileStore
FileStore.set_template_folder(
os.path.join(os.path.dirname(__file__), 'templates'))
@@ -46,7 +46,6 @@ We have a paragraph with [a link](https://talkpython.fm).
def test_basic_markdown_html():
template = os.path.join('home', 'basic_markdown.md')
html = engine.get_page(template, {'a': 1, 'b': 2})
- print("HTML", html)
text = '''
<h1>This is the basic title</h1>
@@ -147,6 +146,23 @@ And more inline **content**.
assert text == md.strip()
+def test_variable_definition_markdown():
+ template = os.path.join('home', 'variables.md')
+ html = page.get_page(template, {})
+
+ text = '''
+<h1>This page defines a variable.</h1>
+
+<p>We have a paragraph with <a href="https://talkpython.fm">a link</a>.</p>
+
+<h3>This page had a title set: Variables rule!</h3>
+
+<p>And more content with the word TITLE.</p>
+'''.strip()
+
+ assert text == html.strip()
+
+
def test_no_lowercase_replacements_markdown():
template = os.path.join('home', 'replacements_case_error.md')
md = page.get_markdown(template, {'title': 'the title', 'link': 'The link'})
diff --git a/tests/templates/home/variables.md b/tests/templates/home/variables.md
new file mode 100644
index 0000000..afbdf24
--- /dev/null
+++ b/tests/templates/home/variables.md
@@ -0,0 +1,7 @@
+# This page defines a variable.
+
+We have a paragraph with [a link](https://talkpython.fm).
+
+[VARIABLE title="Variables rule!"]
+
+[IMPORT REPLACEMENTS]
|
Allow defining a variable to be subsequently passed to import sections
Here's what I have in mind. We have a landing page and want to specify which campaign this is about all the while reusing most of the content:
```markdown
# The landing page title
Welcome people from this campaign
[VARIABLE name=value]
[IMPORT section1] # {name: value} is added to the variables passed here.
[IMPORT section2]
[IMPORT section3]
```
|
0.0
|
29737dbad109ee3d943872751bdb11f64df51431
|
[
"tests/page_tests.py::test_variable_definition_markdown"
] |
[
"tests/page_tests.py::test_missing_template_by_file",
"tests/page_tests.py::test_missing_template_by_folder",
"tests/page_tests.py::test_empty_template",
"tests/page_tests.py::test_basic_markdown_template",
"tests/page_tests.py::test_basic_markdown_html",
"tests/page_tests.py::test_import_markdown",
"tests/page_tests.py::test_nested_import_markdown",
"tests/page_tests.py::test_variable_replacement_markdown",
"tests/page_tests.py::test_two_imports_markdown",
"tests/page_tests.py::test_no_lowercase_replacements_markdown",
"tests/page_tests.py::test_html_with_replacement",
"tests/page_tests.py::test_html_with_embedded_html",
"tests/page_tests.py::test_missing_import_markdown"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-09-06 22:22:15+00:00
|
mit
| 3,940 |
|
mikedevnull__upnp-av-control-106
|
diff --git a/upnpavcontrol/core/oberserver.py b/upnpavcontrol/core/oberserver.py
index a626045..5be029f 100644
--- a/upnpavcontrol/core/oberserver.py
+++ b/upnpavcontrol/core/oberserver.py
@@ -13,6 +13,7 @@ class Subscription(object):
Can be used to unsubscribe from notifications later on
"""
+
def __init__(self, observable):
self._observable = observable
@@ -47,10 +48,14 @@ class Observable(Generic[T]):
While the callback is invoked, the subscription count is guaranteed not to change.
The callback must not add or remove subscriptions, as this will cause a deadlock.
"""
- def __init__(self):
+
+ def __init__(self, replay=False):
self._subscriptions: Dict[Subscription, Callable[[T], Awaitable[None]]] = {}
self._lock = asyncio.Lock()
self._change_callback_cb: Optional[Callable[[int], Awaitable[None]]] = None
+ self._is_replaying = replay
+ self._last_value: Optional[T] = None
+ self._has_last_value = False
@property
def subscription_count(self):
@@ -78,6 +83,8 @@ class Observable(Generic[T]):
self._subscriptions[subscription] = subscriber
if self._change_callback_cb is not None:
await self._change_callback_cb(len(self._subscriptions))
+ if self._has_last_value and self._is_replaying:
+ await subscriber(self._last_value)
return subscription
async def notify(self, payload: T):
@@ -87,6 +94,8 @@ class Observable(Generic[T]):
subscriptions = []
tasks = []
async with self._lock:
+ self._last_value = payload
+ self._has_last_value = True
for subscription, callable in self._subscriptions.items():
subscriptions.append(subscription)
tasks.append(callable(payload))
@@ -139,7 +148,7 @@ async def wait_for_value_if(observerable: Observable[T], predicate: Callable[[T]
future.set_result(True)
except Exception as e:
_logger.exception('predicate')
- raise e
+ future.set_exception(e)
subscription = await observerable.subscribe(f)
try:
|
mikedevnull/upnp-av-control
|
4e967abfa446065eb955b4e8454cd3ae1fbe4117
|
diff --git a/tests/unit/test_observable.py b/tests/unit/test_observable.py
index 06f1aba..45fd762 100644
--- a/tests/unit/test_observable.py
+++ b/tests/unit/test_observable.py
@@ -1,6 +1,7 @@
from upnpavcontrol.core import oberserver
from ..testsupport import AsyncMock
import pytest
+import typing
import asyncio
@@ -86,6 +87,41 @@ async def test_subscription_callback():
subscription_cb.assert_called_once_with(0)
[email protected]
+async def test_replay_last_value_on_subscription():
+ callback = AsyncMock()
+
+ subscription_cb = AsyncMock()
+ observable = oberserver.Observable[int](replay=True)
+ observable.on_subscription_change = subscription_cb
+ await observable.notify(42)
+
+ await observable.subscribe(callback)
+ subscription_cb.assert_called_once_with(1)
+ callback.assert_called_once_with(42)
+
+ callback.reset_mock()
+
+ await observable.notify(21)
+ callback.assert_called_once_with(21)
+
+
[email protected]
+async def test_no_replay_on_subscription_without_initial_value():
+ callback = AsyncMock()
+
+ subscription_cb = AsyncMock()
+ observable = oberserver.Observable[typing.Optional[int]](replay=True)
+ observable.on_subscription_change = subscription_cb
+
+ await observable.subscribe(callback)
+ subscription_cb.assert_called_once_with(1)
+ callback.assert_not_called()
+
+ await observable.notify(None)
+ callback.assert_called_once_with(None)
+
+
@pytest.mark.asyncio
async def test_wait_for_with_predicate_resolves_immediately():
observable = oberserver.Observable[int]()
@@ -111,6 +147,19 @@ async def test_wait_for_with_predicate_resolves_later():
assert True
[email protected]
+async def test_wait_for_value_reraises_exceptions_from_predicate():
+ observable = oberserver.Observable[int]()
+
+ def throwing_predicate(value):
+ raise RuntimeError('exception raised in predicate')
+
+ with pytest.raises(RuntimeError):
+ async with oberserver.wait_for_value_if(observable, throwing_predicate, 1):
+ await observable.notify(41)
+ assert observable.subscription_count == 0
+
+
@pytest.mark.asyncio
async def test_wait_for_with_predicate_times_out():
observable = oberserver.Observable[int]()
|
Add replay feature to observable
Add the ability to replay the N (or at least 1) last values / notifications to a new subscription on an observable.
This way, we could ensure that any subscriber will now the latest state without actively querying, and any missed updates due to a lost frontend/backend connection might be solved with this as well.
Thus, might be a good way to solve #14 as well.
|
0.0
|
4e967abfa446065eb955b4e8454cd3ae1fbe4117
|
[
"tests/unit/test_observable.py::test_replay_last_value_on_subscription",
"tests/unit/test_observable.py::test_no_replay_on_subscription_without_initial_value",
"tests/unit/test_observable.py::test_wait_for_value_reraises_exceptions_from_predicate"
] |
[
"tests/unit/test_observable.py::test_basic_usage",
"tests/unit/test_observable.py::test_callback_error_unsubscription",
"tests/unit/test_observable.py::test_subscription_callback",
"tests/unit/test_observable.py::test_wait_for_with_predicate_resolves_immediately",
"tests/unit/test_observable.py::test_wait_for_with_predicate_resolves_later",
"tests/unit/test_observable.py::test_wait_for_with_predicate_times_out",
"tests/unit/test_observable.py::test_cleanup_when_exception_raised"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-02-12 21:58:53+00:00
|
mit
| 3,941 |
|
minio__minio-py-1054
|
diff --git a/minio/commonconfig.py b/minio/commonconfig.py
index 735dd42..9d43851 100644
--- a/minio/commonconfig.py
+++ b/minio/commonconfig.py
@@ -179,8 +179,6 @@ class Filter:
)
if not valid:
raise ValueError("only one of and, prefix or tag must be provided")
- if prefix is not None and not prefix:
- raise ValueError("prefix must not be empty")
self._and_operator = and_operator
self._prefix = prefix
self._tag = tag
diff --git a/minio/tagging.py b/minio/tagging.py
index ac186ab..d666106 100644
--- a/minio/tagging.py
+++ b/minio/tagging.py
@@ -47,6 +47,5 @@ class Tagging:
"""Convert to XML."""
element = Element("Tagging")
if self._tags:
- element = SubElement(element, "TagSet")
- self._tags.toxml(element)
+ self._tags.toxml(SubElement(element, "TagSet"))
return element
diff --git a/minio/xml.py b/minio/xml.py
index 438dbb6..f995d2a 100644
--- a/minio/xml.py
+++ b/minio/xml.py
@@ -77,7 +77,7 @@ def findtext(element, name, strict=False):
if strict:
raise ValueError("XML element <{0}> not found".format(name))
return None
- return element.text
+ return element.text or ""
def unmarshal(cls, xmlstring):
|
minio/minio-py
|
bac587a450e0b1e63ea643d86f25006da2fcaba2
|
diff --git a/tests/unit/lifecycleconfig_test.py b/tests/unit/lifecycleconfig_test.py
index d9ecde8..577ad01 100644
--- a/tests/unit/lifecycleconfig_test.py
+++ b/tests/unit/lifecycleconfig_test.py
@@ -41,6 +41,18 @@ class LifecycleConfigTest(TestCase):
)
xml.marshal(config)
+ config = LifecycleConfig(
+ [
+ Rule(
+ ENABLED,
+ rule_filter=Filter(prefix=""),
+ rule_id="rule",
+ expiration=Expiration(days=365),
+ ),
+ ],
+ )
+ xml.marshal(config)
+
config = xml.unmarshal(
LifecycleConfig,
"""<LifeCycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
@@ -68,3 +80,20 @@ class LifecycleConfigTest(TestCase):
</LifeCycleConfiguration>""",
)
xml.marshal(config)
+
+ config = xml.unmarshal(
+ LifecycleConfig,
+ """<LifeCycleConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+ <Rule>
+ <ID>DeleteAfterBecomingNonCurrent</ID>
+ <Filter>
+ <Prefix></Prefix>
+ </Filter>
+ <Status>Enabled</Status>
+ <NoncurrentVersionExpiration>
+ <NoncurrentDays>100</NoncurrentDays>
+ </NoncurrentVersionExpiration>
+ </Rule>
+</LifeCycleConfiguration>""",
+ )
+ xml.marshal(config)
|
Issue setting bucket (and potentially object) tags
I am using minio-py 7.0.0 and receive a MalformedXML S3Error any time I try to set the tags of my bucket. This issue probably occurs with object tags as well, but I have not tested that yet.
The simplified code below follows your API example code but seems to fail. `bucket_name` and `s3Client` client are defined elsewhere in my code and everything is properly imported within my code.
```
tags = Tags.new_bucket_tags()
tags["Project"] = "Project One"
tags["User"] = "jsmith"
try:
s3Client.set_bucket_tags(bucket_name, tags)
except (ValueError, S3Error) as exc:
print(str(exc))
```
Here is the error I am receiving:
```S3 operation failed; code: MalformedXML, message: The XML you provided was not well-formed or did not validate against our published schema, resource: None, request_id: ****, host_id: ****```
|
0.0
|
bac587a450e0b1e63ea643d86f25006da2fcaba2
|
[
"tests/unit/lifecycleconfig_test.py::LifecycleConfigTest::test_config"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-01-05 06:07:00+00:00
|
apache-2.0
| 3,942 |
|
ministryofjustice__mt940-writer-12
|
diff --git a/mt940_writer.py b/mt940_writer.py
index b6a3ad9..f3577ac 100644
--- a/mt940_writer.py
+++ b/mt940_writer.py
@@ -58,11 +58,12 @@ class Balance:
class Transaction:
- def __init__(self, date, amount, transaction_type, narrative):
+ def __init__(self, date, amount, transaction_type, narrative, additional_info=None):
self.date = date
self.amount = amount
self.transaction_type = transaction_type
self.narrative = narrative
+ self.additional_info = additional_info
def __str__(self):
return '{value_date}{entry_date}{category}{amount}{type_code}{narrative}'.format(
@@ -75,6 +76,18 @@ class Transaction:
)
+class TransactionAdditionalInfo:
+ def __init__(self, information):
+ self.information = information
+
+ def __str__(self):
+ return '{information}'.format(
+ information=self.information,
+ )
+
+ def __bool__(self):
+ return bool(self.information)
+
class Statement:
def __init__(self, reference_number, account, statement_number, opening_balance, closing_balance, transactions):
self.reference_number = reference_number
@@ -91,6 +104,8 @@ class Statement:
yield ':60F:%s' % self.opening_balance
for transaction in self.transactions:
yield ':61:%s' % transaction
+ if transaction.additional_info:
+ yield ':86:%s' % transaction.additional_info
yield ':62F:%s' % self.closing_balance
def __str__(self):
|
ministryofjustice/mt940-writer
|
899a25186b9fe12e60f169789de72ade5aa5fbf5
|
diff --git a/tests/test_mt940_writer.py b/tests/test_mt940_writer.py
index cf4e232..aa7afd7 100644
--- a/tests/test_mt940_writer.py
+++ b/tests/test_mt940_writer.py
@@ -5,19 +5,6 @@ from unittest import TestCase
import mt940_writer as mt940
-EXPECTED_OUTPUT = (
- ':20:59716\n'
- ':25:80008000 102030\n'
- ':28C:1/1\n'
- ':60F:C160922GBP12,99\n'
- ':61:1609220922C1,00NTRFPayment 1\n'
- ':61:1609220922C1,00NMSCPayment 2\n'
- ':61:1609220922C1,00NTRFPayment 3\n'
- ':61:1609220922D0,99NMSCPayment 4\n'
- ':62F:C160922GBP15,00'
-)
-
-
class MT940WriterTestCase(TestCase):
def test_write_statement(self):
@@ -32,6 +19,18 @@ class MT940WriterTestCase(TestCase):
mt940.Transaction(stmt_date, Decimal('-0.99'), mt940.TransactionType.miscellaneous, 'Payment 4')
]
+ expected_output = (
+ ':20:59716\n'
+ ':25:80008000 102030\n'
+ ':28C:1/1\n'
+ ':60F:C160922GBP12,99\n'
+ ':61:1609220922C1,00NTRFPayment 1\n'
+ ':61:1609220922C1,00NMSCPayment 2\n'
+ ':61:1609220922C1,00NTRFPayment 3\n'
+ ':61:1609220922D0,99NMSCPayment 4\n'
+ ':62F:C160922GBP15,00'
+ )
+
statement = mt940.Statement(
'59716',
account,
@@ -41,4 +40,42 @@ class MT940WriterTestCase(TestCase):
transactions
)
- self.assertEqual(str(statement), EXPECTED_OUTPUT)
+ self.assertEqual(str(statement), expected_output)
+ def test_write_statement_with_additional_transaction_info(self):
+ stmt_date = date(2016, 9, 22)
+ account = mt940.Account('80008000', '102030')
+ opening_balance = mt940.Balance(Decimal('12.99'), stmt_date, 'GBP')
+ closing_balance = mt940.Balance(Decimal('15'), stmt_date, 'GBP')
+ transactions = [
+ mt940.Transaction(stmt_date, Decimal('1'), mt940.TransactionType.transfer, 'Payment 1',
+ mt940.TransactionAdditionalInfo('ADDITIONAL/DATA/1')),
+ mt940.Transaction(stmt_date, Decimal('1'), mt940.TransactionType.miscellaneous, 'Payment 2',
+ mt940.TransactionAdditionalInfo('ADDITIONAL/DATA/2')),
+ mt940.Transaction(stmt_date, Decimal('1'), mt940.TransactionType.transfer, 'Payment 3',
+ mt940.TransactionAdditionalInfo('')),
+ mt940.Transaction(stmt_date, Decimal('-0.99'), mt940.TransactionType.miscellaneous, 'Payment 4')
+ ]
+
+ expected_output = (
+ ':20:59716\n'
+ ':25:80008000 102030\n'
+ ':28C:1/1\n'
+ ':60F:C160922GBP12,99\n'
+ ':61:1609220922C1,00NTRFPayment 1\n'
+ ':86:ADDITIONAL/DATA/1\n'
+ ':61:1609220922C1,00NMSCPayment 2\n'
+ ':86:ADDITIONAL/DATA/2\n'
+ ':61:1609220922C1,00NTRFPayment 3\n'
+ ':61:1609220922D0,99NMSCPayment 4\n'
+ ':62F:C160922GBP15,00'
+ )
+ statement = mt940.Statement(
+ '59716',
+ account,
+ '1/1',
+ opening_balance,
+ closing_balance,
+ transactions
+ )
+
+ self.assertEqual(str(statement), expected_output)
|
add support for Tag 86
<img width="651" alt="image" src="https://github.com/ministryofjustice/mt940-writer/assets/20453622/fb184e68-7eaf-4b13-89c4-f6075d2f28b8">
<img width="474" alt="image" src="https://github.com/ministryofjustice/mt940-writer/assets/20453622/6e08494e-b5f5-41f5-8c97-50de4b552165">
|
0.0
|
899a25186b9fe12e60f169789de72ade5aa5fbf5
|
[
"tests/test_mt940_writer.py::MT940WriterTestCase::test_write_statement_with_additional_transaction_info"
] |
[
"tests/test_mt940_writer.py::MT940WriterTestCase::test_write_statement"
] |
{
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-15 14:20:55+00:00
|
mit
| 3,943 |
|
minrk__escapism-4
|
diff --git a/.travis.yml b/.travis.yml
index 8cae354..ccda971 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -3,6 +3,8 @@ python:
- 2.7
- 3.4
- 3.6
+- 3.7
+- 3.8
cache:
- pip
install:
diff --git a/escapism.py b/escapism.py
index 5517996..e0cd6ce 100644
--- a/escapism.py
+++ b/escapism.py
@@ -13,8 +13,9 @@ no args are provided.
import re
import string
import sys
+import warnings
-__version__ = '1.0.0'
+__version__ = "1.0.1"
SAFE = set(string.ascii_letters + string.digits)
ESCAPE_CHAR = '_'
@@ -67,7 +68,13 @@ def escape(to_escape, safe=SAFE, escape_char=ESCAPE_CHAR, allow_collisions=False
if allow_collisions:
safe.add(escape_char)
elif escape_char in safe:
- # escape char can't be in safe list
+ warnings.warn(
+ "Escape character %r cannot be a safe character."
+ " Set allow_collisions=True if you want to allow ambiguous escaped strings."
+ % escape_char,
+ RuntimeWarning,
+ stacklevel=2,
+ )
safe.remove(escape_char)
chars = []
@@ -81,7 +88,7 @@ def escape(to_escape, safe=SAFE, escape_char=ESCAPE_CHAR, allow_collisions=False
def _unescape_char(m):
"""Unescape a single byte
-
+
Used as a callback in pattern.subn. `m.group(1)` must be a single byte in hex,
e.g. `a4` or `ff`.
"""
@@ -90,7 +97,7 @@ def _unescape_char(m):
def unescape(escaped, escape_char=ESCAPE_CHAR):
"""Unescape a string escaped with `escape`
-
+
escape_char must be the same as that used in the call to escape.
"""
if isinstance(escaped, bytes):
|
minrk/escapism
|
35f4c194ad6de2bc3339bb8b0e522dca989143ff
|
diff --git a/tests/test_escapism.py b/tests/test_escapism.py
index 9ba0a52..939ccfc 100644
--- a/tests/test_escapism.py
+++ b/tests/test_escapism.py
@@ -1,4 +1,9 @@
# coding: utf-8
+
+import warnings
+
+import pytest
+
from escapism import escape, unescape, SAFE
text = type(u'')
@@ -11,6 +16,7 @@ test_strings = [
u'_\\-+',
]
+
def test_escape_default():
for s in test_strings:
e = escape(s)
@@ -19,6 +25,7 @@ def test_escape_default():
assert isinstance(u, text)
assert u == s
+
def test_escape_custom_char():
for escape_char in r'\-%+_':
for s in test_strings:
@@ -28,6 +35,7 @@ def test_escape_custom_char():
assert isinstance(u, text)
assert u == s
+
def test_escape_custom_safe():
safe = 'ABCDEFabcdef0123456789'
escape_char = '\\'
@@ -38,14 +46,17 @@ def test_escape_custom_safe():
u = unescape(e, escape_char=escape_char)
assert u == s
+
def test_safe_escape_char():
- escape_char = '-'
+ escape_char = "-"
safe = SAFE.union({escape_char})
- e = escape(escape_char, safe=safe, escape_char=escape_char)
- assert e == '{}{:02X}'.format(escape_char, ord(escape_char))
+ with pytest.warns(RuntimeWarning):
+ e = escape(escape_char, safe=safe, escape_char=escape_char)
+ assert e == "{}{:02X}".format(escape_char, ord(escape_char))
u = unescape(e, escape_char=escape_char)
assert u == escape_char
+
def test_allow_collisions():
escaped = escape('foo-bar ', escape_char='-', allow_collisions=True)
assert escaped == 'foo-bar-20'
|
Escaping an underscore adds "5F" to the word
Hi!
I use escapism as it is part of the dockerspawner:
https://github.com/jupyterhub/dockerspawner/blob/master/dockerspawner/dockerspawner.py#L20
I have a string containing an underscore, and after escaping it by an underscore, I have an additional two characters: `5F` (which is a part of an URL-encoded underscore). It appears to me that everytime the replacement character (third argument) is actually contained in the original string, it adds characters.
This is very unexpected. And it is very unpractical, as I cannot of course control the characters in my original string (if I could, I would not escape them).
Whether that replacement character is part of the "safe" characters does not affect this behaviour.
I am using Python 3.6 on a linux machine.
Please see here:
```
yyy@yyy:/srv/jupyterhub# python3
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import escapism
>>> import string
>>> s = 'foo_foo'
>>> safe = set(string.ascii_letters + string.digits + "-")
>>> e = escapism.escape(s, safe, '_')
>>> e
'foo_5Ffoo'
```
It does not change if I add the underscore to the safe chars:
```
>>> import escapism
>>> import string
>>>
>>> s = 'foo_foo'
>>> safe = set(string.ascii_letters + string.digits + "-"+ "_")
>>>
>>> 'f' in safe, 'o' in safe, '_' in safe
(True, True, True)
>>>
>>> escapism.escape(s, safe, '_')
'foo_5Ffoo'
```
And actually, it removes the replacement character from the safe characters:
```
>>> import escapism
>>>
>>> s = 'foo_foo'
>>> safe = {'f','o','_','x'}
>>> safe
{'o', '_', 'f', 'x'}
>>> escapism.escape(s, safe, 'x')
'foo_foo'
>>> safe
{'o', '_', 'f'}
>>> # x was removed
>>> escapism.escape(s, safe, 'x')
'foo_foo'
>>> safe
{'o', '_', 'f'}
```
And it adds characters to every occurrence of the replacement character in the string, no matter whether it is safe or not:
```
>>> import escapism
>>> s = 'foo_foo'
>>> safe = {'f','o','_'}
>>> safe
{'o', '_', 'f'}
>>> escapism.escape(s, safe, 'o')
'fo6Fo6F_fo6Fo6F' ### <-- chars were added!
>>> safe
{'_', 'f'} ### <-- o was removed from safe!
```
Can anybody reproduce this?
|
0.0
|
35f4c194ad6de2bc3339bb8b0e522dca989143ff
|
[
"tests/test_escapism.py::test_safe_escape_char"
] |
[
"tests/test_escapism.py::test_escape_default",
"tests/test_escapism.py::test_escape_custom_char",
"tests/test_escapism.py::test_escape_custom_safe",
"tests/test_escapism.py::test_allow_collisions"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-30 10:41:21+00:00
|
mit
| 3,944 |
|
minrk__wurlitzer-83
|
diff --git a/README.md b/README.md
index 9641b76..e365664 100644
--- a/README.md
+++ b/README.md
@@ -59,13 +59,22 @@ with pipes(logger, stderr=STDOUT):
call_some_c_function()
```
+Forward C-level output to a file (avoids GIL issues with a background thread, new in 3.1):
+
+```python
+from wurlitzer import pipes, STDOUT
+
+with open("log.txt", "ab") as f, pipes(f, stderr=STDOUT):
+ blocking_gil_holding_function()
+```
+
Or even simpler, enable it as an IPython extension:
```
%load_ext wurlitzer
```
-To forward all C-level output to IPython during execution.
+To forward all C-level output to IPython (e.g. Jupyter cell output) during execution.
## Acknowledgments
diff --git a/wurlitzer.py b/wurlitzer.py
index 5626f98..67f61d4 100644
--- a/wurlitzer.py
+++ b/wurlitzer.py
@@ -210,6 +210,17 @@ class Wurlitzer:
save_fd = os.dup(real_fd)
self._save_fds[name] = save_fd
+ try:
+ capture_fd = getattr(self, "_" + name).fileno()
+ except Exception:
+ pass
+ else:
+ # if it has a fileno(),
+ # dup directly to capture file,
+ # no pipes needed
+ dup2(capture_fd, real_fd)
+ return None
+
pipe_out, pipe_in = os.pipe()
# set max pipe buffer size (linux only)
if self._bufsize:
@@ -272,19 +283,32 @@ class Wurlitzer:
self._flush()
# setup handle
self._setup_handle()
- self._control_r, self._control_w = os.pipe()
# create pipe for stdout
- pipes = [self._control_r]
- names = {self._control_r: 'control'}
+ pipes = []
+ names = {}
if self._stdout:
pipe = self._setup_pipe('stdout')
- pipes.append(pipe)
- names[pipe] = 'stdout'
+ if pipe:
+ pipes.append(pipe)
+ names[pipe] = 'stdout'
if self._stderr:
pipe = self._setup_pipe('stderr')
- pipes.append(pipe)
- names[pipe] = 'stderr'
+ if pipe:
+ pipes.append(pipe)
+ names[pipe] = 'stderr'
+
+ if not pipes:
+ # no pipes to handle (e.g. direct FD capture)
+ # so no forwarder thread needed
+ self.thread = None
+ return self.handle
+
+ # setup forwarder thread
+
+ self._control_r, self._control_w = os.pipe()
+ pipes.append(self._control_r)
+ names[self._control_r] = "control"
# flush pipes in a background thread to avoid blocking
# the reader thread when the buffer is full
@@ -366,11 +390,11 @@ class Wurlitzer:
def __exit__(self, exc_type, exc_value, traceback):
# flush before exiting
self._flush()
-
- # signal output is complete on control pipe
- os.write(self._control_w, b'\1')
- self.thread.join()
- os.close(self._control_w)
+ if self.thread:
+ # signal output is complete on control pipe
+ os.write(self._control_w, b'\1')
+ self.thread.join()
+ os.close(self._control_w)
# restore original state
for name, real_fd in self._real_fds.items():
|
minrk/wurlitzer
|
38caf37f352235a7e5dcbaa847442c6a879d2921
|
diff --git a/test.py b/test.py
index 5a0b274..0a604c7 100644
--- a/test.py
+++ b/test.py
@@ -206,3 +206,39 @@ def test_log_pipes(caplog):
# check 'stream' extra
assert record.stream
assert record.name == "wurlitzer." + record.stream
+
+
+def test_two_file_pipes(tmpdir):
+
+ test_stdout = tmpdir / "stdout.txt"
+ test_stderr = tmpdir / "stderr.txt"
+
+ with test_stdout.open("ab") as stdout_f, test_stderr.open("ab") as stderr_f:
+ w = Wurlitzer(stdout_f, stderr_f)
+ with w:
+ assert w.thread is None
+ printf("some stdout")
+ printf_err("some stderr")
+
+ with test_stdout.open() as f:
+ assert f.read() == "some stdout\n"
+ with test_stderr.open() as f:
+ assert f.read() == "some stderr\n"
+
+
+def test_one_file_pipe(tmpdir):
+
+ test_stdout = tmpdir / "stdout.txt"
+
+ with test_stdout.open("ab") as stdout_f:
+ stderr = io.StringIO()
+ w = Wurlitzer(stdout_f, stderr)
+ with w as (stdout, stderr):
+ assert w.thread is not None
+ printf("some stdout")
+ printf_err("some stderr")
+ assert not w.thread.is_alive()
+
+ with test_stdout.open() as f:
+ assert f.read() == "some stdout\n"
+ assert stderr.getvalue() == "some stderr\n"
|
Wurlitzer hangs when the GIL is taken by C code
Hello,
I had to debug an issue in a library where I use Wurlitzer. The script I was willing to monitor was using http://caffe.berkeleyvision.org/ which involves some C code and a Python API. This C code output a lot of outputs directly from the C code and don't release the GIL before running the C code.
The results was that the process froze as the main thread was trying to a full pipe and the wurlitzer consuming threads were blocked waiting for the GIL.
I've attached a redacted thread dump from gdb (all the Python threads are waiting for the GIL, I can send the non-redacted thread dump if needed):
[thread-dumps.log](https://github.com/minrk/wurlitzer/files/2213240/thread-dumps.log)
I've reworked our output monitoring code to reproduce wurlitzer architecture but using multiprocessing.Process instead of threads. This way the consumers process have their own GIL and can run even if the main process is running some C. Moreover I had to monkeypatch `sys.std{out,err}` to force flushing in order to have the last lines of `std{out,err}` before the end of the script.
I also tried to improve the buffer size by following the inspiration from https://github.com/wal-e/wal-e/blob/cdfaa92698ba19bbbff23ab2421fb377f9affb60/wal_e/pipebuf.py#L56. It did worked, but the stdout / stderr was captured after the C code finished, and in my case it could takes hours. So that was not a solution for me.
The changes are pretty big and I'm not sure if they have their place in wurlitzer, what do you think? Anyway I wanted to let you know the potential issue so you can document it or apply wal-e solution to increase pipe buffer size.
|
0.0
|
38caf37f352235a7e5dcbaa847442c6a879d2921
|
[
"test.py::test_two_file_pipes",
"test.py::test_one_file_pipe"
] |
[
"test.py::test_pipes",
"test.py::test_pipe_bytes",
"test.py::test_forward",
"test.py::test_pipes_stderr",
"test.py::test_flush",
"test.py::test_sys_pipes",
"test.py::test_redirect_everything",
"test.py::test_fd_leak",
"test.py::test_buffer_full",
"test.py::test_buffer_full_default",
"test.py::test_pipe_max_size",
"test.py::test_log_pipes"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-04-24 11:36:26+00:00
|
mit
| 3,945 |
|
mintproject__dame_cli-31
|
diff --git a/.travis.yml b/.travis.yml
index 22abdd9..5fa1290 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,57 @@
-dist: xenial
language: python
-python:
-- '3.7'
+
+jobs:
+ include:
+ - name: 'Linux - py3.6, 3.7, 3.8'
+ python:
+ - "3.6" # current default Python on Travis CI
+ - "3.7"
+ - "3.8"
+ dist: xenial
+ - name: "macOS 10.13 - py3.6.5"
+ os: osx
+ osx_image: xcode9.4
+ language: shell
+ before_install:
+ - python3 --version
+ - pip3 install -U pip
+ - pip3 install -U tox
+ - pip3 install codecov
+ script: python3 -m tox
+ after_success: python 3 -m codecov
+ - name: "xcode10.2 - py3.7.3"
+ os: osx
+ osx_image: xcode10.2
+ language: shell
+ before_install:
+ - python3 --version
+ - pip3 install -U pip
+ - pip3 install -U tox
+ - pip3 install codecov
+ script: python3 -m tox
+ after_success: python 3 -m codecov
+ - name: "Python 3.6.8 on Windows"
+ os: windows # Windows 10.0.17134 N/A Build 17134
+ language: shell # 'language: python' is an error on Travis CI Windows
+ before_install:
+ - choco install python --version 3.6.8
+ - python --version
+ - python -m pip install --upgrade pip
+ - pip3 install --upgrade tox
+ - pip3 install codecov
+ env: PATH=/c/Python36:/c/Python35/Scripts:$PATH
+ - name: "Python 3.7.4 on Windows"
+ os: windows # Windows 10.0.17134 N/A Build 17134
+ language: shell # 'language: python' is an error on Travis CI Windows
+ before_install:
+ - choco install python --version 3.7.4
+ - python --version
+ - python -m pip install --upgrade pip
+ - pip3 install --upgrade tox
+ - pip3 install codecov
+ env: PATH=/c/Python37:/c/Python35/Scripts:$PATH
+ allow_failures:
+ - os: windows
install: pip install tox-travis
script: tox
deploy:
diff --git a/README.md b/README.md
index fa575d0..ff9eb7b 100644
--- a/README.md
+++ b/README.md
@@ -13,9 +13,9 @@ The application needs Singularity to run the containers.
If you would like support for Docker, let us know: [Support Docker](https://github.com/mintproject/dame_cli/issues/15)
-### Python 3
+### Python
-The applications needs Python.
+The applications needs Python >=3.6
- [Installation on Linux](https://realpython.com/installing-python/#linux)
- [Installation on Windows](https://realpython.com/installing-python/#windows)
diff --git a/VERSION b/VERSION
deleted file mode 100644
index 3debf3b..0000000
--- a/VERSION
+++ /dev/null
@@ -1,1 +0,0 @@
-2.3.0-0
diff --git a/src/dame/__main__.py b/src/dame/__main__.py
index 05d8fcd..6780264 100644
--- a/src/dame/__main__.py
+++ b/src/dame/__main__.py
@@ -12,7 +12,7 @@ from modelcatalog import OpenApiException
import dame
from dame import _utils
-from dame.cli_methods import verify_input_parameters, run_method_setup
+from dame.cli_methods import verify_input_parameters, run_method_setup, show_model_configuration_details
from dame.modelcatalogapi import get_setup, get_model_configuration
try:
@@ -65,10 +65,10 @@ def run(name):
if "ModelConfigurationSetup" in config.type:
resource = get_setup(name)
- verify_input_parameters(resource)
elif "ModelConfiguration" in config.type:
resource = get_model_configuration(name)
- verify_input_parameters(resource)
+ show_model_configuration_details(resource)
+ verify_input_parameters(resource)
# setup = get_setup(name)
# edit_inputs_setup(setup)
run_method_setup(resource)
diff --git a/src/dame/cli_methods.py b/src/dame/cli_methods.py
index ddf94ee..ddf96ba 100644
--- a/src/dame/cli_methods.py
+++ b/src/dame/cli_methods.py
@@ -12,6 +12,33 @@ from dame._utils import log
from dame.modelcatalogapi import get_setup
from modelcatalog import ApiException, SampleResource
+data_set_property = ["id", "label"]
+parameter_set_property = ["id", "label", "has_default_value"]
+
+
+def show_model_configuration_details(model_configuration):
+ click.echo(click.style("Information about the model configuration", bold=True))
+ if model_configuration and hasattr(model_configuration, "has_input"):
+ click.echo(click.style("Inputs", bold=True))
+ for _input in model_configuration.has_input:
+ if hasattr(_input, "has_fixed_resource") and hasattr(_input.has_fixed_resource[0], "value"):
+ click.echo("{}: {}".format(_input.label[0], _input.has_fixed_resource[0].value[0]))
+ else:
+ label = getattr(_input, "label") if hasattr(_input, "label") else getattr(_input, "id")
+ click.echo("{}: {}".format(label[0], "No information"))
+ if model_configuration and hasattr(model_configuration, "has_parameter"):
+ click.echo(click.style("Parameters", bold=True))
+ for _parameter in model_configuration.has_parameter:
+ short_value(_parameter, "has_default_value")
+
+
+
+def short_value(resource, prop):
+ if hasattr(resource, prop):
+ value = getattr(resource, prop)
+ click.echo("{}: {}".format(getattr(resource, "label")[0], value[0]))
+
+
def verify_input_parameters(model_configuration):
for _input in model_configuration.has_input:
if not hasattr(_input, "has_fixed_resource"):
@@ -45,7 +72,10 @@ def edit_parameter_config_or_setup(resource, auto=False):
value = click.prompt('Enter the value for the parameter:', default=default_value)
parameter["hasFixedValue"] = [value]
-def print_data_property_table(resource):
+
+
+
+def print_data_property_table(resource, property_selected={}):
resource_dict = resource.to_dict()
tab = tt.Texttable(max_width=100)
headings = ['Property', 'Value']
@@ -53,6 +83,9 @@ def print_data_property_table(resource):
for key, value in resource_dict.items():
if isinstance(value, dict) or key == "type" or key == "has_presentation":
continue
+ if property_selected:
+ if key not in property_selected:
+ continue
tab.add_row([key,value])
print(tab.draw())
diff --git a/tox.ini b/tox.ini
index 797e5ee..4601ef1 100644
--- a/tox.ini
+++ b/tox.ini
@@ -5,7 +5,7 @@ envlist = py37,py35
[testenv]
-commands = pytest --cov {envsitepackagesdir}/mint {posargs}
+commands = pytest --cov {envsitepackagesdir}/dame {posargs}
setenv = PYTHONPATH = {toxinidir}/src
PYTHONUNBUFFERED = yes
|
mintproject/dame_cli
|
e6f0344fbb4bc1d6109bfb341196d7ec3328ecb7
|
diff --git a/src/dame/tests/test___main__.py b/src/dame/tests/test___main__.py
new file mode 100644
index 0000000..a241b97
--- /dev/null
+++ b/src/dame/tests/test___main__.py
@@ -0,0 +1,28 @@
+from unittest import TestCase
+
+from click.testing import CliRunner
+
+from dame.__main__ import version, run
+import dame
+
+SETUP_FULL_INFO = "cycles-0.10.2-alpha-collection-oromia-single-point"
+
+
+class Test(TestCase):
+ def test_version(self):
+ runner = CliRunner()
+ result = runner.invoke(version)
+ assert result.exit_code == 0
+ assert result.output == f"DAME: v{dame.__version__}\n"
+
+
+ # def test_run(self):
+ # runner = CliRunner()
+ # result = runner.invoke(run, SETUP_FULL_INFO)
+ # assert not result.exception
+
+
+ # def test_run_partial(self):
+ # runner = CliRunner()
+ # result = runner.invoke(run, SETUP_FULL_INFO)
+ # assert not result.exception
diff --git a/src/dame/tests/test_cli_methods.py b/src/dame/tests/test_cli_methods.py
new file mode 100644
index 0000000..ccc9476
--- /dev/null
+++ b/src/dame/tests/test_cli_methods.py
@@ -0,0 +1,35 @@
+from unittest import TestCase
+
+from dame.cli_methods import verify_input_parameters, print_data_property_table, show_model_configuration_details
+from dame.modelcatalogapi import get_setup, list_setup, list_model_configuration
+
+from click.testing import CliRunner
+
+SETUP_PARTIAL_INFO = "dsi_1.0_cfg"
+SETUP_FULL_INFO = "cycles-0.10.2-alpha-collection-oromia-single-point"
+
+
+class Test(TestCase):
+ def test_verify_input_parameters(self):
+ runner = CliRunner()
+ partial_setup = get_setup(SETUP_FULL_INFO)
+ assert verify_input_parameters(partial_setup) == partial_setup
+
+ def test_print_data_property_table(self):
+ full = get_setup(SETUP_FULL_INFO)
+ partial = get_setup(SETUP_PARTIAL_INFO)
+ print_data_property_table(full)
+ print_data_property_table(partial)
+
+ def test_show_model_configuration_details(self):
+ full = get_setup(SETUP_FULL_INFO)
+ partial = get_setup(SETUP_PARTIAL_INFO)
+ show_model_configuration_details(full)
+ show_model_configuration_details(partial)
+
+
+ def test_show_model_configuration_details(self):
+ for setup in list_setup():
+ show_model_configuration_details(setup)
+ for model_configuration in list_model_configuration():
+ show_model_configuration_details(model_configuration)
diff --git a/src/dame/tests/test_modelcatalogapi.py b/src/dame/tests/test_modelcatalogapi.py
new file mode 100644
index 0000000..0e93ae3
--- /dev/null
+++ b/src/dame/tests/test_modelcatalogapi.py
@@ -0,0 +1,12 @@
+from unittest import TestCase
+
+from dame.modelcatalogapi import get_setup
+from dame.utils import obtain_id
+
+SETUP_FULL_INFO = "cycles-0.10.2-alpha-collection-oromia-single-point"
+SETUP_PARTIAL_INFO = "dsi_1.0_cfg"
+
+class Test(TestCase):
+ def test_get_setup(self):
+ assert obtain_id(get_setup(SETUP_FULL_INFO).id) == SETUP_FULL_INFO
+ assert obtain_id(get_setup(SETUP_PARTIAL_INFO).id) == SETUP_PARTIAL_INFO
diff --git a/src/dame/tests/test_utils.py b/src/dame/tests/test_utils.py
new file mode 100644
index 0000000..8fb86be
--- /dev/null
+++ b/src/dame/tests/test_utils.py
@@ -0,0 +1,9 @@
+from unittest import TestCase
+
+from dame.utils import obtain_id
+
+
+class Test(TestCase):
+ def test_obtain_id(self):
+ url = "https://w3id.org/okn/i/mint/cycles-0.10.2-alpha-collection-oromia-single-point"
+ assert obtain_id(url) == "cycles-0.10.2-alpha-collection-oromia-single-point"
|
add testing
test a simple command in:
- osx, windows, python
language: python
python:
- "3.4"
- "3.5"
- "3.6" # current default Python on Travis CI
- "3.7"
- "3.8"
|
0.0
|
e6f0344fbb4bc1d6109bfb341196d7ec3328ecb7
|
[
"src/dame/tests/test___main__.py::Test::test_version",
"src/dame/tests/test_utils.py::Test::test_obtain_id"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_removed_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-04-17 19:09:02+00:00
|
apache-2.0
| 3,946 |
|
mir-group__flare-92
|
diff --git a/flare/gp.py b/flare/gp.py
index 07a2eb7a..876db51d 100644
--- a/flare/gp.py
+++ b/flare/gp.py
@@ -25,7 +25,8 @@ class GaussianProcess:
energy_force_kernel: Callable = None,
energy_kernel: Callable = None,
opt_algorithm: str = 'L-BFGS-B',
- maxiter=10, par=False,
+ opt_params: dict = None,
+ maxiter=10, par: bool=False,
output=None):
"""Initialize GP parameters and training data."""
@@ -38,6 +39,7 @@ class GaussianProcess:
self.hyp_labels = hyp_labels
self.cutoffs = cutoffs
self.algo = opt_algorithm
+ self.opt_params = opt_params if opt_params is not None else {}
self.training_data = []
self.training_labels = []
@@ -119,14 +121,17 @@ class GaussianProcess:
return forces_np
- def train(self, output=None, custom_bounds=None,
- grad_tol: float = 1e-4,
- x_tol: float = 1e-5,
- line_steps: int = 20):
- """Train Gaussian Process model on training data. Tunes the \
+ def train(self, output=None, opt_param_override: dict = None):
+ """
+ Train Gaussian Process model on training data. Tunes the \
hyperparameters to maximize the likelihood, then computes L and alpha \
-(related to the covariance matrix of the training set)."""
+(related to the covariance matrix of the training set).
+ :param output: Output to write to
+ :param opt_param_override: Dictionary of parameters to override
+ instace's optimzation parameters.
+ :return:
+ """
x_0 = self.hyps
args = (self.training_data, self.training_labels_np,
@@ -134,7 +139,21 @@ hyperparameters to maximize the likelihood, then computes L and alpha \
self.par)
res = None
- if self.algo == 'L-BFGS-B':
+ # Make local copy of opt params so as to not overwrite with override
+ opt_param_temp = dict(self.opt_params)
+ if opt_param_override is not None:
+ for key, value in opt_param_override.items():
+ opt_param_temp[key] = value
+
+ grad_tol = opt_param_temp.get('grad_tol', 1e-4)
+ x_tol = opt_param_temp.get('x_tol', 1e-5)
+ line_steps = opt_param_temp.get('max_ls', 20)
+ max_iter = opt_param_temp.get('max_iter', self.maxiter)
+ algo = opt_param_temp.get('algorithm', self.algo)
+ disp = opt_param_temp.get('disp', False)
+
+
+ if algo == 'L-BFGS-B':
# bound signal noise below to avoid overfitting
bounds = np.array([(1e-6, np.inf)] * len(x_0))
@@ -144,35 +163,36 @@ hyperparameters to maximize the likelihood, then computes L and alpha \
try:
res = minimize(get_neg_like_grad, x_0, args,
method='L-BFGS-B', jac=True, bounds=bounds,
- options={'disp': False, 'gtol': grad_tol,
+ options={'disp': disp, 'gtol': grad_tol,
'maxls': line_steps,
- 'maxiter': self.maxiter})
+ 'maxiter': max_iter})
except:
print("Warning! Algorithm for L-BFGS-B failed. Changing to "
"BFGS for remainder of run.")
- self.algo = 'BFGS'
+ self.opt_params['algorithm'] = 'BFGS'
- if custom_bounds is not None:
+ if opt_param_temp.get('custom_bounds', None) is not None:
res = minimize(get_neg_like_grad, x_0, args,
- method='L-BFGS-B', jac=True, bounds=custom_bounds,
- options={'disp': False, 'gtol': grad_tol,
+ method='L-BFGS-B', jac=True,
+ bounds=opt_param_temp.get('custom_bonuds'),
+ options={'disp': disp, 'gtol': grad_tol,
'maxls': line_steps,
- 'maxiter': self.maxiter})
+ 'maxiter': max_iter})
- elif self.algo == 'BFGS':
+ elif algo == 'BFGS':
res = minimize(get_neg_like_grad, x_0, args,
method='BFGS', jac=True,
- options={'disp': False, 'gtol': grad_tol,
- 'maxiter': self.maxiter})
+ options={'disp': disp, 'gtol': grad_tol,
+ 'maxiter': max_iter})
- elif self.algo == 'nelder-mead':
+ elif algo == 'nelder-mead':
res = minimize(get_neg_likelihood, x_0, args,
method='nelder-mead',
- options={'disp': False,
- 'maxiter': self.maxiter,
+ options={'disp': disp,
+ 'maxiter': max_iter,
'xtol': x_tol})
if res is None:
- raise RuntimeError("Optimization failed for some reason.")
+ raise RuntimeError("Optimization failed for unknown reason.")
self.hyps = res.x
self.set_L_alpha()
self.likelihood = -res.fun
@@ -410,6 +430,7 @@ environment and the environments in the training set."""
hyp_labels=dictionary['hyp_labels'],
par=dictionary['par'],
maxiter=dictionary['maxiter'],
+ opt_params=dictionary['opt_params'],
opt_algorithm=dictionary['algo'])
# Save time by attempting to load in computed attributes
|
mir-group/flare
|
0d55cab252f80bc3dbc3d15fdd693a5f9fa74823
|
diff --git a/tests/test_gp.py b/tests/test_gp.py
index b014a74f..85270d2e 100644
--- a/tests/test_gp.py
+++ b/tests/test_gp.py
@@ -242,6 +242,16 @@ def test_serialization_method(two_body_gp, test_point):
if isinstance(x, np.ndarray):
assert np.equal(x, y).all()
+
+ elif isinstance(x, dict):
+ xkeys = set(x.keys())
+ ykeys = set(y.keys())
+ assert xkeys == ykeys
+
+ # Once keys are same determine if all values are equal
+ for xk in sorted(list(xkeys)):
+ assert x[xk] == y[xk]
+
elif hasattr(x, '__len__'):
if isinstance(x[0], np.ndarray):
diff --git a/tests/test_gp_from_aimd.py b/tests/test_gp_from_aimd.py
index 4ea6986a..d6203546 100644
--- a/tests/test_gp_from_aimd.py
+++ b/tests/test_gp_from_aimd.py
@@ -21,8 +21,7 @@ def methanol_gp():
1.70172923e-03]),
cutoffs=np.array([7, 7]),
hyp_labels=['l2', 's2', 'l3', 's3', 'n0'],
- maxiter=1,
- opt_algorithm='L-BFGS-B')
+ maxiter=1)
with open('./test_files/methanol_envs.json') as f:
dicts = [loads(s) for s in f.readlines()]
|
Finer control over GP optimization parameters by instance
The TrajectoryTrainer and OTF classes contain calls to the `gp.train` method but do not pass in arguments that the `train` method can accept. In order to expose more control to the user, being able to set optimization parameters (such as `grad_tol` and `x_tol`) on an individual instance would be helpful, since it makes sense for those to be parameters associated with a given `GaussianProcess` instance. This could involve, for instance, re-factoring the train method to draw from an internal `opt_parameter_kwarg` dictionary which could be passed when instantiating the `GaussianProcess`.
|
0.0
|
0d55cab252f80bc3dbc3d15fdd693a5f9fa74823
|
[
"tests/test_gp.py::test_update_db"
] |
[
"tests/test_gp_from_aimd.py::test_instantiation_of_trajectory_trainer",
"tests/test_gp_from_aimd.py::test_uncertainty_threshold",
"tests/test_gp.py::test_set_L_alpha",
"tests/test_gp.py::test_train",
"tests/test_gp.py::test_predict",
"tests/test_gp.py::test_representation_method"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-10-14 19:25:58+00:00
|
mit
| 3,947 |
|
mirumee__ariadne-1057
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c62e076..75796d7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Next (UNRELEASED)
+- Added `InputType` for setting Python representations of GraphQL Input types
- Added support for passing `Enum` types directly to `make_executable_schema`
- Added `convert_names_case` option to `make_federated_schema`.
diff --git a/ariadne/__init__.py b/ariadne/__init__.py
index eb1eb3b..fe0c343 100644
--- a/ariadne/__init__.py
+++ b/ariadne/__init__.py
@@ -13,6 +13,7 @@ from .format_error import (
get_formatted_error_traceback,
)
from .graphql import graphql, graphql_sync, subscribe
+from .inputs import InputType
from .interfaces import InterfaceType, type_implements_interface
from .load_schema import load_schema_from_path
from .objects import MutationType, ObjectType, QueryType
@@ -43,6 +44,7 @@ __all__ = [
"ExtensionManager",
"ExtensionSync",
"FallbackResolversSetter",
+ "InputType",
"InterfaceType",
"MutationType",
"ObjectType",
diff --git a/ariadne/executable_schema.py b/ariadne/executable_schema.py
index 03968fe..0d99184 100644
--- a/ariadne/executable_schema.py
+++ b/ariadne/executable_schema.py
@@ -18,7 +18,9 @@ from .schema_visitor import SchemaDirectiveVisitor
from .types import SchemaBindable
SchemaBindables = Union[
- SchemaBindable, Type[Enum], List[Union[SchemaBindable, Type[Enum]]]
+ SchemaBindable,
+ Type[Enum],
+ List[Union[SchemaBindable, Type[Enum]]],
]
@@ -365,7 +367,9 @@ def join_type_defs(type_defs: List[str]) -> str:
return "\n\n".join(t.strip() for t in type_defs)
-def normalize_bindables(*bindables: SchemaBindables) -> List[SchemaBindable]:
+def normalize_bindables(
+ *bindables: SchemaBindables,
+) -> List[SchemaBindable]:
normal_bindables: List[SchemaBindable] = []
for bindable in flatten_bindables(*bindables):
if isinstance(bindable, SchemaBindable):
diff --git a/ariadne/inputs.py b/ariadne/inputs.py
new file mode 100644
index 0000000..53d3dd1
--- /dev/null
+++ b/ariadne/inputs.py
@@ -0,0 +1,204 @@
+from typing import Dict, Optional, cast
+
+from graphql import GraphQLInputObjectType, GraphQLSchema
+from graphql.type.definition import GraphQLInputFieldOutType, GraphQLNamedType
+
+from .types import SchemaBindable
+
+
+class InputType(SchemaBindable):
+ """Bindable populating input types in a GraphQL schema with Python logic.
+
+ # Example input value represented as dataclass
+
+ Following code creates a GraphQL schema with object type named `Query`
+ with single field which has an argument of an input type. It then uses
+ the `InputType` to set `ExampleInput` dataclass as Python representation
+ of this GraphQL type:
+
+ ```python
+ from dataclasses import dataclass
+
+ from ariadne import InputType, QueryType, make_executable_schema
+
+ @dataclass
+ class ExampleInput:
+ id: str
+ message: str
+
+ query_type = QueryType()
+
+ @query_type.field("repr")
+ def resolve_repr(*_, input: ExampleInput):
+ return repr(input)
+
+ schema = make_executable_schema(
+ \"\"\"
+ type Query {
+ repr(input: ExampleInput): String!
+ }
+
+ input ExampleInput {
+ id: ID!
+ message: String!
+ }
+ \"\"\",
+ query_type,
+ # Lambda is used because out type (second argument of InputType)
+ # is called with single dict and dataclass requires each value as
+ # separate argument.
+ InputType("ExampleInput", lambda data: ExampleInput(**data)),
+ )
+ ```
+
+ # Example input with its fields mapped to custom dict keys
+
+ Following code creates a GraphQL schema with object type named `Query`
+ with single field which has an argument of an input type. It then uses
+ the `InputType` to set custom "out names" values, mapping GraphQL
+ `shortMessage` to `message` key in Python dict:
+
+ ```python
+ from ariadne import InputType, QueryType, make_executable_schema
+
+ query_type = QueryType()
+
+ @query_type.field("repr")
+ def resolve_repr(*_, input: dict):
+ # Dict will have `id` and `message` keys
+ input_id = input["id"]
+ input_message = input["message"]
+ return f"id: {input_id}, message: {input_message}"
+
+ schema = make_executable_schema(
+ \"\"\"
+ type Query {
+ repr(input: ExampleInput): String!
+ }
+
+ input ExampleInput {
+ id: ID!
+ shortMessage: String!
+ }
+ \"\"\",
+ query_type,
+ InputType("ExampleInput", out_names={"shortMessage": "message"}),
+ )
+ ```
+
+ # Example input value as dataclass with custom named fields
+
+ Following code creates a GraphQL schema with object type named `Query`
+ with single field which has an argument of an input type. It then uses
+ the `InputType` to set `ExampleInput` dataclass as Python representation
+ of this GraphQL type, and maps `shortMessage` input field to it's
+ `message` attribute:
+
+ ```python
+ from dataclasses import dataclass
+
+ from ariadne import InputType, QueryType, make_executable_schema
+
+ @dataclass
+ class ExampleInput:
+ id: str
+ message: str
+
+ query_type = QueryType()
+
+ @query_type.field("repr")
+ def resolve_repr(*_, input: ExampleInput):
+ return repr(input)
+
+ schema = make_executable_schema(
+ \"\"\"
+ type Query {
+ repr(input: ExampleInput): String!
+ }
+
+ input ExampleInput {
+ id: ID!
+ shortMessage: String!
+ }
+ \"\"\",
+ query_type,
+ InputType(
+ "ExampleInput",
+ lambda data: ExampleInput(**data),
+ {"shortMessage": "message"},
+ ),
+ )
+ ```
+ """
+
+ _out_type: Optional[GraphQLInputFieldOutType]
+ _out_names: Optional[Dict[str, str]]
+
+ def __init__(
+ self,
+ name: str,
+ out_type: Optional[GraphQLInputFieldOutType] = None,
+ out_names: Optional[Dict[str, str]] = None,
+ ) -> None:
+ """Initializes the `InputType` with a `name` and optionally out type
+ and out names.
+
+ # Required arguments
+
+ `name`: a `str` with the name of GraphQL object type in GraphQL schema to
+ bind to.
+
+ # Optional arguments
+
+ `out_type`: a `GraphQLInputFieldOutType`, Python callable accepting single
+ argument, a dict with data from GraphQL query, required to return
+ a Python representation of input type.
+
+ `out_names`: a `Dict[str, str]` with mappings from GraphQL field names
+ to dict keys in a Python dictionary used to contain a data passed as
+ input.
+ """
+ self.name = name
+ self._out_type = out_type
+ self._out_names = out_names
+
+ def bind_to_schema(self, schema: GraphQLSchema) -> None:
+ """Binds this `InputType` instance to the instance of GraphQL schema.
+
+ if it has an out type function, it assigns it to GraphQL type's
+ `out_type` attribute. If type already has other function set on
+ it's `out_type` attribute, this type is replaced with new one.
+
+ If it has any out names set, it assigns those to GraphQL type's
+ fields `out_name` attributes. If field already has other out name set on
+ its `out_name` attribute, this name is replaced with the new one.
+ """
+ graphql_type = schema.type_map.get(self.name)
+ self.validate_graphql_type(graphql_type)
+ graphql_type = cast(GraphQLInputObjectType, graphql_type)
+
+ if self._out_type:
+ graphql_type.out_type = self._out_type # type: ignore
+
+ if self._out_names:
+ for graphql_name, python_name in self._out_names.items():
+ if graphql_name not in graphql_type.fields:
+ raise ValueError(
+ f"Field {graphql_name} is not defined on type {self.name}"
+ )
+ graphql_type.fields[graphql_name].out_name = python_name
+
+ def validate_graphql_type(self, graphql_type: Optional[GraphQLNamedType]) -> None:
+ """Validates that schema's GraphQL type associated with this `InputType`
+ is an `input`."""
+ if not graphql_type:
+ raise ValueError("Type %s is not defined in the schema" % self.name)
+ if not isinstance(graphql_type, GraphQLInputObjectType):
+ raise ValueError(
+ "%s is defined in the schema, but it is instance of %s (expected %s)"
+ % (
+ self.name,
+ type(graphql_type).__name__,
+ GraphQLInputObjectType.__name__,
+ )
+ )
|
mirumee/ariadne
|
776bed8a5fb6d0932d560c540ce81ab08e2a5064
|
diff --git a/tests/test_inputs.py b/tests/test_inputs.py
new file mode 100644
index 0000000..3bccb13
--- /dev/null
+++ b/tests/test_inputs.py
@@ -0,0 +1,167 @@
+from dataclasses import dataclass
+
+import pytest
+from graphql import graphql_sync
+
+from ariadne import InputType, make_executable_schema
+
+
[email protected]
+def schema():
+ return make_executable_schema(
+ """
+ type Query {
+ repr(input: ExampleInput!): Boolean!
+ }
+
+ input ExampleInput {
+ id: ID
+ message: String
+ yearOfBirth: Int
+ }
+ """
+ )
+
+
+def set_repr_resolver(schema, repr_resolver):
+ # pylint: disable=redefined-builtin
+ def resolve_repr(*_, input):
+ repr_resolver(input)
+ return True
+
+ schema.type_map["Query"].fields["repr"].resolve = resolve_repr
+
+
+TEST_QUERY = """
+query InputTest($input: ExampleInput!) {
+ repr(input: $input)
+}
+"""
+
+
+def test_attempt_bind_input_type_to_undefined_type_raises_error(schema):
+ input_type = InputType("Test")
+ with pytest.raises(ValueError):
+ input_type.bind_to_schema(schema)
+
+
+def test_attempt_bind_input_type_to_invalid_type_raises_error(schema):
+ input_type = InputType("Query")
+ with pytest.raises(ValueError):
+ input_type.bind_to_schema(schema)
+
+
+def test_attempt_bind_input_type_out_name_to_undefined_field_raises_error(schema):
+ input_type = InputType("Query", out_names={"undefined": "Ok"})
+ with pytest.raises(ValueError):
+ input_type.bind_to_schema(schema)
+
+
+def test_bind_input_type_out_type_sets_custom_python_type_for_input(schema):
+ # pylint: disable=redefined-builtin
+
+ @dataclass
+ class InputDataclass:
+ id: str
+ message: str
+ yearOfBirth: int
+
+ input_type = InputType(
+ "ExampleInput",
+ out_type=lambda data: InputDataclass(**data),
+ )
+ input_type.bind_to_schema(schema)
+
+ def assert_input_type(input):
+ assert isinstance(input, InputDataclass)
+ assert input.id == "123"
+ assert input.message == "Lorem ipsum"
+ assert input.yearOfBirth == 2022
+
+ set_repr_resolver(schema, assert_input_type)
+
+ result = graphql_sync(
+ schema,
+ TEST_QUERY,
+ variable_values={
+ "input": {
+ "id": "123",
+ "message": "Lorem ipsum",
+ "yearOfBirth": 2022,
+ }
+ },
+ )
+
+ assert not result.errors
+
+
+def test_bind_input_type_out_names_sets_custom_python_dict_keys_for_input(schema):
+ # pylint: disable=redefined-builtin
+
+ input_type = InputType(
+ "ExampleInput",
+ out_names={"yearOfBirth": "year_of_birth"},
+ )
+ input_type.bind_to_schema(schema)
+
+ def assert_input_type(input):
+ assert input == {
+ "id": "123",
+ "message": "Lorem ipsum",
+ "year_of_birth": 2022,
+ }
+
+ set_repr_resolver(schema, assert_input_type)
+
+ result = graphql_sync(
+ schema,
+ TEST_QUERY,
+ variable_values={
+ "input": {
+ "id": "123",
+ "message": "Lorem ipsum",
+ "yearOfBirth": 2022,
+ }
+ },
+ )
+
+ assert not result.errors
+
+
+def test_bind_input_type_out_type_and_names_sets_custom_python_type_for_input(schema):
+ # pylint: disable=redefined-builtin
+
+ @dataclass
+ class InputDataclass:
+ id: str
+ message: str
+ year_of_birth: int
+
+ input_type = InputType(
+ "ExampleInput",
+ out_type=lambda data: InputDataclass(**data),
+ out_names={"yearOfBirth": "year_of_birth"},
+ )
+ input_type.bind_to_schema(schema)
+
+ def assert_input_type(input):
+ assert isinstance(input, InputDataclass)
+ assert input.id == "123"
+ assert input.message == "Lorem ipsum"
+ assert input.year_of_birth == 2022
+
+ set_repr_resolver(schema, assert_input_type)
+
+ result = graphql_sync(
+ schema,
+ TEST_QUERY,
+ variable_values={
+ "input": {
+ "id": "123",
+ "message": "Lorem ipsum",
+ "yearOfBirth": 2022,
+ }
+ },
+ )
+
+ assert not result.errors
diff --git a/tests_mypy/inputs.py b/tests_mypy/inputs.py
new file mode 100644
index 0000000..686c738
--- /dev/null
+++ b/tests_mypy/inputs.py
@@ -0,0 +1,14 @@
+from dataclasses import dataclass
+
+from ariadne import InputType
+
+
+@dataclass
+class SomeInput:
+ id: str
+ message: str
+
+
+dataclass_input = InputType("Name", lambda data: SomeInput(**data))
+
+dict_input = InputType("Name", out_names={"fieldName": "field_name"})
|
Bind Python Types to GraphQL Input Types [How To]
Perhaps it's just unclear in the docs, but I don't see any way to automatically convert from the input dictionaries given by Ariadne, to my resolvers, into custom Python types (i.e. dataclasses)
Is this supported? I found the docs on bindables, but from just that I can't tell if that's what I want.
Example
```python
@dataclass
class Person:
id: int
name: str
phone_number: str
@mutation.field('updatePerson')
def update_person(_, info, person: Person):
# Currently what comes in is a dict.
# Is there a way to automatically map this to Person?
do_update(
person.id,
name=person.name,
phone=person.phone_number
)
```
|
0.0
|
776bed8a5fb6d0932d560c540ce81ab08e2a5064
|
[
"tests/test_inputs.py::test_attempt_bind_input_type_to_undefined_type_raises_error",
"tests/test_inputs.py::test_attempt_bind_input_type_to_invalid_type_raises_error",
"tests/test_inputs.py::test_attempt_bind_input_type_out_name_to_undefined_field_raises_error",
"tests/test_inputs.py::test_bind_input_type_out_type_sets_custom_python_type_for_input",
"tests/test_inputs.py::test_bind_input_type_out_names_sets_custom_python_dict_keys_for_input",
"tests/test_inputs.py::test_bind_input_type_out_type_and_names_sets_custom_python_type_for_input"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-21 19:13:32+00:00
|
bsd-3-clause
| 3,948 |
|
mirumee__ariadne-1071
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa6ed03..6b8d5bd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,10 +1,13 @@
# CHANGELOG
## 0.20 (UNRELEASED)
+
- Added `query_validator` option to ASGI and WSGI `GraphQL` applications that enables customization of query validation step.
+- Fixed `ERROR` message in GraphQL-WS protocol having invalid payload type.
## 0.19.1 (2023-03-28)
+
- Fixed `.graphql` definitions files not being included in the dist files
diff --git a/ariadne/asgi/handlers/graphql_transport_ws.py b/ariadne/asgi/handlers/graphql_transport_ws.py
index 4f05238..26c48c9 100644
--- a/ariadne/asgi/handlers/graphql_transport_ws.py
+++ b/ariadne/asgi/handlers/graphql_transport_ws.py
@@ -326,7 +326,7 @@ class GraphQLTransportWSHandler(GraphQLWebsocketHandler):
{
"type": GraphQLTransportWSHandler.GQL_ERROR,
"id": operation_id,
- "payload": self.error_formatter(error, self.debug),
+ "payload": [self.error_formatter(error, self.debug)],
}
)
return
@@ -375,7 +375,7 @@ class GraphQLTransportWSHandler(GraphQLWebsocketHandler):
{
"type": GraphQLTransportWSHandler.GQL_ERROR,
"id": operation_id,
- "payload": results_producer[0],
+ "payload": [results_producer[0]],
}
)
else:
|
mirumee/ariadne
|
81a77136b4a28c6ec0da2462e3207c8a4804847d
|
diff --git a/tests/asgi/snapshots/snap_test_query_execution.py b/tests/asgi/snapshots/snap_test_query_execution.py
index 341310b..855b9de 100644
--- a/tests/asgi/snapshots/snap_test_query_execution.py
+++ b/tests/asgi/snapshots/snap_test_query_execution.py
@@ -73,15 +73,17 @@ snapshots['test_attempt_execute_subscription_with_invalid_query_returns_error_js
'message': "Cannot query field 'error' on type 'Subscription'."
}
-snapshots['test_attempt_execute_subscription_with_invalid_query_returns_error_json_graphql_transport_ws 1'] = {
- 'locations': [
- {
- 'column': 16,
- 'line': 1
- }
- ],
- 'message': "Cannot query field 'error' on type 'Subscription'."
-}
+snapshots['test_attempt_execute_subscription_with_invalid_query_returns_error_json_graphql_transport_ws 1'] = [
+ {
+ 'locations': [
+ {
+ 'column': 16,
+ 'line': 1
+ }
+ ],
+ 'message': "Cannot query field 'error' on type 'Subscription'."
+ }
+]
snapshots['test_complex_query_is_executed_for_post_json_request 1'] = {
'data': {
diff --git a/tests/asgi/test_websockets_graphql_transport_ws.py b/tests/asgi/test_websockets_graphql_transport_ws.py
index 0a10f8b..649070c 100644
--- a/tests/asgi/test_websockets_graphql_transport_ws.py
+++ b/tests/asgi/test_websockets_graphql_transport_ws.py
@@ -236,7 +236,7 @@ def test_custom_query_validator_is_used_for_subscription_over_websocket_transpor
else:
assert response["type"] == GraphQLTransportWSHandler.GQL_ERROR
assert response["id"] == "test2"
- assert response["payload"]["message"] == "Nope"
+ assert response["payload"][0]["message"] == "Nope"
def test_custom_query_parser_is_used_for_query_over_websocket_transport_ws(
|
GraphQLTransportWSHandler sends invalid errors message breaking `graphql-ws` clients on error (should be an array)
Lately I switched over to fully using the GraphQLTransportWSHandler for everything (including mutations and queries). However, I am receiving the following error on the client (`"graphql-ws": "^5.11.2",`).
```plain
index.ts:43 Error: "error" message expects the 'payload' property to be an array of GraphQL errors, but got {"message":".......","locations":[{"line":1,"column":36}],"extensions":{"exception":null}}
at validateMessage (common.mjs:128:23)
at parseMessage (common.mjs:168:12)
at socket2.onmessage (client.mjs:202:37)
```
After checking `graphql-ws` source code and protocol specification I think Apollo is not sending errors correctly:
https://github.com/enisdenjo/graphql-ws/blob/fbb763a662802a6a2584b0cbeb9cf1bde38158e0/src/utils.ts#L57-L66
https://github.com/enisdenjo/graphql-ws/blob/fbb763a662802a6a2584b0cbeb9cf1bde38158e0/PROTOCOL.md#error
The client expects an array of errors, but instead Apollo only sends a single error?
https://github.com/mirumee/ariadne/blob/3218cff61ce12dc649b1f425c26e23715c3241a1/ariadne/asgi/handlers/graphql_transport_ws.py#L318-L332
https://github.com/mirumee/ariadne/blob/3218cff61ce12dc649b1f425c26e23715c3241a1/ariadne/asgi/handlers/graphql_transport_ws.py#L368-L379
|
0.0
|
81a77136b4a28c6ec0da2462e3207c8a4804847d
|
[
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_query_validator_is_used_for_subscription_over_websocket_transport_ws[errors1]"
] |
[
"tests/asgi/test_websockets_graphql_transport_ws.py::test_field_can_be_subscribed_using_websocket_connection_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_field_can_be_subscribed_using_unnamed_operation_in_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_field_can_be_subscribed_using_named_operation_in_websocket_connection_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_query_can_be_executed_using_websocket_connection_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_mutation_can_be_executed_using_websocket_connection_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_query_parser_is_used_for_subscription_over_websocket_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_query_validator_is_used_for_subscription_over_websocket_transport_ws[errors0]",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_query_parser_is_used_for_query_over_websocket_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_immediate_disconnect_on_invalid_type_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_complete_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_pong_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_connect_is_called_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_connect_is_called_with_payload_graph_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_connect_is_awaited_if_its_async_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_error_in_custom_websocket_on_connect_closes_connection_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_connection_error_closes_connection_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_operation_is_called_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_operation_is_awaited_if_its_async_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_error_in_custom_websocket_on_operation_is_handled_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_complete_is_called_on_disconnect_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_complete_is_called_on_operation_complete_grapqhl_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_complete_is_awaited_if_its_async_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_error_in_custom_websocket_on_complete_is_handled_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_disconnect_is_called_on_invalid_operation_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_custom_websocket_on_disconnect_is_called_on_connection_close_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_error_in_custom_websocket_on_disconnect_is_handled_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_get_operation_type",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_invalid_operation_id_is_handled_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_schema_not_set_graphql_transport_ws",
"tests/asgi/test_websockets_graphql_transport_ws.py::test_http_handler_not_set_graphql_transport_ws"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-18 17:16:10+00:00
|
bsd-3-clause
| 3,949 |
|
mirumee__ariadne-1080
|
diff --git a/ariadne/validation/query_cost.py b/ariadne/validation/query_cost.py
index f46775b..d5b29a6 100644
--- a/ariadne/validation/query_cost.py
+++ b/ariadne/validation/query_cost.py
@@ -144,14 +144,18 @@ class CostValidator(ValidationRule):
fragment_type = self.context.schema.get_type(
fragment.type_condition.name.value
)
- node_cost = self.compute_node_cost(fragment, fragment_type)
+ node_cost = self.compute_node_cost(
+ fragment, fragment_type, self.operation_multipliers
+ )
if isinstance(child_node, InlineFragmentNode):
inline_fragment_type = type_def
if child_node.type_condition and child_node.type_condition.name:
inline_fragment_type = self.context.schema.get_type(
child_node.type_condition.name.value
)
- node_cost = self.compute_node_cost(child_node, inline_fragment_type)
+ node_cost = self.compute_node_cost(
+ child_node, inline_fragment_type, self.operation_multipliers
+ )
total += node_cost
return total
|
mirumee/ariadne
|
1f62d2da08abc8ed5dfd50c83befa8f965a840ed
|
diff --git a/tests/test_query_cost_validation.py b/tests/test_query_cost_validation.py
index 692743f..79403a8 100644
--- a/tests/test_query_cost_validation.py
+++ b/tests/test_query_cost_validation.py
@@ -458,3 +458,191 @@ def test_child_field_cost_defined_in_directive_is_multiplied_by_values_from_lite
extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
)
]
+
+
+def test_child_inline_fragment_cost_defined_in_map_is_multiplied_by_values_from_variables(
+ schema,
+):
+ query = """
+ query testQuery($value: Int!) {
+ child(value: $value) {
+ ... on Child {
+ online
+ }
+ }
+ }
+ """
+ ast = parse(query)
+ rule = cost_validator(maximum_cost=3, variables={"value": 5}, cost_map=cost_map)
+ result = validate(schema, ast, [rule])
+ assert result == [
+ GraphQLError(
+ "The query exceeds the maximum cost of 3. Actual cost is 20",
+ extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
+ )
+ ]
+
+
+def test_child_inline_fragment_cost_defined_in_map_is_multiplied_by_values_from_literal(
+ schema,
+):
+ query = """
+ {
+ child(value: 5) {
+ ... on Child{
+ online
+ }
+ }
+ }
+ """
+ ast = parse(query)
+ rule = cost_validator(maximum_cost=3, cost_map=cost_map)
+ result = validate(schema, ast, [rule])
+ assert result == [
+ GraphQLError(
+ "The query exceeds the maximum cost of 3. Actual cost is 20",
+ extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
+ )
+ ]
+
+
+def test_child_inline_fragment_cost_defined_in_directive_is_multiplied_by_values_from_variables(
+ schema_with_costs,
+):
+ query = """
+ query testQuery($value: Int!) {
+ child(value: $value) {
+ ... on Child {
+ online
+ }
+ }
+ }
+ """
+ ast = parse(query)
+ rule = cost_validator(maximum_cost=3, variables={"value": 5})
+ result = validate(schema_with_costs, ast, [rule])
+ assert result == [
+ GraphQLError(
+ "The query exceeds the maximum cost of 3. Actual cost is 20",
+ extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
+ )
+ ]
+
+
+def test_child_inline_fragment_cost_defined_in_directive_is_multiplied_by_values_from_literal(
+ schema_with_costs,
+):
+ query = """
+ {
+ child(value: 5) {
+ ... on Child{
+ online
+ }
+ }
+ }
+ """
+ ast = parse(query)
+ rule = cost_validator(maximum_cost=3)
+ result = validate(schema_with_costs, ast, [rule])
+ assert result == [
+ GraphQLError(
+ "The query exceeds the maximum cost of 3. Actual cost is 20",
+ extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
+ )
+ ]
+
+
+def test_child_fragment_cost_defined_in_map_is_multiplied_by_values_from_variables(
+ schema,
+):
+ query = """
+ fragment child on Child {
+ online
+ }
+ query testQuery($value: Int!) {
+ child(value: $value) {
+ ...child
+ }
+ }
+ """
+ ast = parse(query)
+ rule = cost_validator(maximum_cost=3, variables={"value": 5}, cost_map=cost_map)
+ result = validate(schema, ast, [rule])
+ assert result == [
+ GraphQLError(
+ "The query exceeds the maximum cost of 3. Actual cost is 20",
+ extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
+ )
+ ]
+
+
+def test_child_fragment_cost_defined_in_map_is_multiplied_by_values_from_literal(
+ schema,
+):
+ query = """
+ fragment child on Child {
+ online
+ }
+ {
+ child(value: 5) {
+ ...child
+ }
+ }
+ """
+ ast = parse(query)
+ rule = cost_validator(maximum_cost=3, cost_map=cost_map)
+ result = validate(schema, ast, [rule])
+ assert result == [
+ GraphQLError(
+ "The query exceeds the maximum cost of 3. Actual cost is 20",
+ extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
+ )
+ ]
+
+
+def test_child_fragment_cost_defined_in_directive_is_multiplied_by_values_from_variables(
+ schema_with_costs,
+):
+ query = """
+ fragment child on Child {
+ online
+ }
+ query testQuery($value: Int!) {
+ child(value: $value) {
+ ...child
+ }
+ }
+ """
+ ast = parse(query)
+ rule = cost_validator(maximum_cost=3, variables={"value": 5})
+ result = validate(schema_with_costs, ast, [rule])
+ assert result == [
+ GraphQLError(
+ "The query exceeds the maximum cost of 3. Actual cost is 20",
+ extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
+ )
+ ]
+
+
+def test_child_fragment_cost_defined_in_directive_is_multiplied_by_values_from_literal(
+ schema_with_costs,
+):
+ query = """
+ fragment child on Child {
+ online
+ }
+ {
+ child(value: 5) {
+ ...child
+ }
+ }
+ """
+ ast = parse(query)
+ rule = cost_validator(maximum_cost=3)
+ result = validate(schema_with_costs, ast, [rule])
+ assert result == [
+ GraphQLError(
+ "The query exceeds the maximum cost of 3. Actual cost is 20",
+ extensions={"cost": {"requestedQueryCost": 20, "maximumAvailable": 3}},
+ )
+ ]
|
Query cost validation is skipping `InlineFragmentNode`
I've got tipped by @przlada that our query cost validator skips `InlineFragmentNode` when calculating the costs.
`InlineFragmentNode` is a fragment used when querying interfaces and unions:
```graphql
{
search(query: "lorem ipsum") {
... on User {
id
username
}
... on Comment {
id
content
}
}
}
```
|
0.0
|
1f62d2da08abc8ed5dfd50c83befa8f965a840ed
|
[
"tests/test_query_cost_validation.py::test_child_inline_fragment_cost_defined_in_map_is_multiplied_by_values_from_variables",
"tests/test_query_cost_validation.py::test_child_inline_fragment_cost_defined_in_map_is_multiplied_by_values_from_literal",
"tests/test_query_cost_validation.py::test_child_inline_fragment_cost_defined_in_directive_is_multiplied_by_values_from_variables",
"tests/test_query_cost_validation.py::test_child_inline_fragment_cost_defined_in_directive_is_multiplied_by_values_from_literal",
"tests/test_query_cost_validation.py::test_child_fragment_cost_defined_in_map_is_multiplied_by_values_from_variables",
"tests/test_query_cost_validation.py::test_child_fragment_cost_defined_in_map_is_multiplied_by_values_from_literal",
"tests/test_query_cost_validation.py::test_child_fragment_cost_defined_in_directive_is_multiplied_by_values_from_variables",
"tests/test_query_cost_validation.py::test_child_fragment_cost_defined_in_directive_is_multiplied_by_values_from_literal"
] |
[
"tests/test_query_cost_validation.py::test_cost_map_is_used_to_calculate_query_cost",
"tests/test_query_cost_validation.py::test_query_validation_fails_if_cost_map_contains_undefined_type",
"tests/test_query_cost_validation.py::test_query_validation_fails_if_cost_map_contains_undefined_type_field",
"tests/test_query_cost_validation.py::test_query_validation_fails_if_cost_map_contains_non_object_type",
"tests/test_query_cost_validation.py::test_cost_directive_is_used_to_calculate_query_cost",
"tests/test_query_cost_validation.py::test_field_cost_defined_in_map_is_multiplied_by_value_from_variables",
"tests/test_query_cost_validation.py::test_field_cost_defined_in_map_is_multiplied_by_nested_value_from_variables",
"tests/test_query_cost_validation.py::test_field_cost_defined_in_map_is_multiplied_by_value_from_literal",
"tests/test_query_cost_validation.py::test_field_cost_defined_in_directive_is_multiplied_by_value_from_variables",
"tests/test_query_cost_validation.py::test_default_values_are_used_to_calculate_query_cost_without_directive_args",
"tests/test_query_cost_validation.py::test_field_cost_defined_in_directive_is_multiplied_by_nested_value_from_variables",
"tests/test_query_cost_validation.py::test_field_cost_defined_in_directive_is_multiplied_by_value_from_literal",
"tests/test_query_cost_validation.py::test_complex_field_cost_defined_in_map_is_multiplied_by_values_from_variables",
"tests/test_query_cost_validation.py::test_complex_field_cost_defined_in_map_is_multiplied_by_values_from_literal",
"tests/test_query_cost_validation.py::test_complex_field_cost_multiplication_by_values_from_variables_handles_nulls",
"tests/test_query_cost_validation.py::test_complex_field_cost_multiplication_by_values_from_literals_handles_nulls",
"tests/test_query_cost_validation.py::test_complex_field_cost_multiplication_by_values_from_variables_handles_optional",
"tests/test_query_cost_validation.py::test_complex_field_cost_multiplication_by_values_from_literals_handles_optional",
"tests/test_query_cost_validation.py::test_complex_field_cost_defined_in_directive_is_multiplied_by_values_from_variables",
"tests/test_query_cost_validation.py::test_complex_field_cost_defined_in_directive_is_multiplied_by_values_from_literal",
"tests/test_query_cost_validation.py::test_child_field_cost_defined_in_map_is_multiplied_by_values_from_variables",
"tests/test_query_cost_validation.py::test_child_field_cost_defined_in_map_is_multiplied_by_values_from_literal",
"tests/test_query_cost_validation.py::test_child_field_cost_defined_in_directive_is_multiplied_by_values_from_variables",
"tests/test_query_cost_validation.py::test_child_field_cost_defined_in_directive_is_multiplied_by_values_from_literal"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-04-27 20:25:23+00:00
|
bsd-3-clause
| 3,950 |
|
mirumee__ariadne-1098
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f44f302..5934b6b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,15 +2,16 @@
## 0.20 (UNRELEASED)
+- Dropped support for Python 3.7.
+- Added `OpenTelemetry` and `opentelemetry_extension` extension, importable form `ariadne.tracing.opentelemetry`.
- Added `query_validator` option to ASGI and WSGI `GraphQL` applications that enables customization of query validation step.
- Fixed `ERROR` message in GraphQL-WS protocol having invalid payload type.
- Fixed query cost validator incorrect handling of inline fragments.
+- Fixed `make_executable_schema` error when `null` is used as default value for `input` typed field argument.
+- Updated default GraphiQL2 template to use production build of React.js.
- Removed `ExtensionSync`. `Extension` now supports both async and sync contexts.
- Removed `OpenTracingSync` and `opentracing_extension_sync`. `OpenTracing` and `opentracing_extension` now support both async and sync contexts.
- Removed `ApolloTracingSync`. `ApolloTracing` now supports both async and sync contexts.
-- Added `OpenTelemetry` and `opentelemetry_extension` extension, importable form `ariadne.tracing.opentelemetry`.
-- Updated default GraphiQL2 template to use production build of React.js.
-- Dropped support for Python 3.7.
## 0.19.1 (2023-03-28)
diff --git a/ariadne/enums.py b/ariadne/enums.py
index 05e0ccd..544127a 100644
--- a/ariadne/enums.py
+++ b/ariadne/enums.py
@@ -308,7 +308,11 @@ def _get_field_with_keys(field_name, fields):
yield field_name, input_name, field, None
if isinstance(resolved_type, GraphQLInputObjectType):
- if field.ast_node is not None and field.ast_node.default_value is not None:
+ if (
+ field.ast_node is not None
+ and field.ast_node.default_value is not None
+ and isinstance(field.ast_node.default_value, ObjectValueNode)
+ ):
routes = get_enum_keys_from_ast(field.ast_node)
for route in routes:
yield field_name, input_name, field, route
|
mirumee/ariadne
|
545a957c4aa6fbb3a5bc563160763a4acde1db21
|
diff --git a/tests/test_enums.py b/tests/test_enums.py
index bde296b..4eeff7b 100644
--- a/tests/test_enums.py
+++ b/tests/test_enums.py
@@ -515,3 +515,18 @@ def test_error_is_raised_for_python_enum_with_name_not_in_schema():
with pytest.raises(ValueError):
make_executable_schema([enum_definition, enum_field], query, UnknownEnum)
+
+
+def test_schema_enum_values_fixer_handles_null_input_default():
+ # regression test for: https://github.com/mirumee/ariadne/issues/1074
+ make_executable_schema(
+ """
+ input SearchInput {
+ name: String!
+ }
+
+ type Query {
+ search(filters: SearchInput = null): String
+ }
+ """
+ )
|
Query filter with default `null` filter causes error
**GraphQL Schema:**
```gql
Query {
"""Get sensors with filtering"""
sensors(filters: SensorFilters = null): [Sensor!]!
}
```
**Expected Behavior:**
Schema is built with no errors. This happens in Ariadne 0.13.0.
**Actual Behavior:**
In Ariadne >= 0.14.0 (currently running 0.19.1), the following error is raised when running the `make_executable_schema()` method:
```python
ImportError while loading conftest '/Users/*****/Code/mycode/tests/conftest.py'.
tests/conftest.py:21: in <module>
from src import (
mycode/src/graphql/__init__.py:103: in <module>
schema = make_executable_schema(type_defs, types)
venv/lib/python3.9/site-packages/ariadne/executable_schema.py:354: in make_executable_schema
validate_schema_enum_values(schema)
venv/lib/python3.9/site-packages/ariadne/enums.py:239: in validate_schema_enum_values
for type_name, field_name, arg, _ in find_enum_values_in_schema(schema):
venv/lib/python3.9/site-packages/ariadne/enums.py:260: in find_enum_values_in_schema
yield from result
venv/lib/python3.9/site-packages/ariadne/enums.py:278: in enum_values_in_object_type
yield from enum_values_in_field_args(field_name, field)
venv/lib/python3.9/site-packages/ariadne/enums.py:301: in enum_values_in_field_args
yield from _get_field_with_keys(field_name, args)
venv/lib/python3.9/site-packages/ariadne/enums.py:312: in _get_field_with_keys
routes = get_enum_keys_from_ast(field.ast_node)
venv/lib/python3.9/site-packages/ariadne/enums.py:320: in get_enum_keys_from_ast
nodes = [([field.name.value], field) for field in object_node.fields]
E AttributeError: 'NullValueNode' object has no attribute 'fields'
```
**Workaround:**
If I remove the default `null` value from the query filter, this works as expected, but removing the default value is not desired.
**Solution:**
Checking the `default_value` to ensure it is an instance of `ObjectValueNode` (which is expected by `get_enum_keys_from_ast`) resolves this issue.
```diff
diff --git a/ariadne/enums.py b/ariadne/enums.py
index 05e0ccd..544127a 100644
--- a/ariadne/enums.py
+++ b/ariadne/enums.py
@@ -308,7 +308,11 @@ def _get_field_with_keys(field_name, fields):
yield field_name, input_name, field, None
if isinstance(resolved_type, GraphQLInputObjectType):
- if field.ast_node is not None and field.ast_node.default_value is not None:
+ if (
+ field.ast_node is not None
+ and field.ast_node.default_value is not None
+ and isinstance(field.ast_node.default_value, ObjectValueNode)
+ ):
routes = get_enum_keys_from_ast(field.ast_node)
for route in routes:
yield field_name, input_name, field, route
```
|
0.0
|
545a957c4aa6fbb3a5bc563160763a4acde1db21
|
[
"tests/test_enums.py::test_schema_enum_values_fixer_handles_null_input_default"
] |
[
"tests/test_enums.py::test_succesfull_enum_typed_field",
"tests/test_enums.py::test_unsuccesfull_invalid_enum_value_evaluation",
"tests/test_enums.py::test_successful_enum_value_passed_as_argument",
"tests/test_enums.py::test_unbound_enum_arg_is_transformed_to_string",
"tests/test_enums.py::test_unsuccessful_invalid_enum_value_passed_as_argument",
"tests/test_enums.py::test_attempt_bind_custom_enum_to_undefined_type_raises_error",
"tests/test_enums.py::test_attempt_bind_custom_enum_to_wrong_schema_type_raises_error",
"tests/test_enums.py::test_attempt_bind_custom_enum_to_schema_enum_missing_value_raises_error",
"tests/test_enums.py::test_dict_enum_is_resolved_from_internal_value",
"tests/test_enums.py::test_dict_enum_arg_is_transformed_to_internal_value",
"tests/test_enums.py::test_enum_is_resolved_from_member_value",
"tests/test_enums.py::test_enum_arg_is_transformed_to_internal_value",
"tests/test_enums.py::test_str_enum_is_resolved_from_member_value",
"tests/test_enums.py::test_str_enum_is_resolved_from_internal_value",
"tests/test_enums.py::test_str_enum_arg_is_transformed_to_internal_value",
"tests/test_enums.py::test_int_enum_is_resolved_from_field_value",
"tests/test_enums.py::test_int_enum_is_resolved_from_internal_value",
"tests/test_enums.py::test_int_enum_arg_is_transformed_to_internal_value",
"tests/test_enums.py::test_int_enum_arg_default_python_value_is_set",
"tests/test_enums.py::test_int_enum_input_default_python_value_is_set",
"tests/test_enums.py::test_int_enum_input_nested_default_python_value_is_set",
"tests/test_enums.py::test_input_exc_schema_raises_exception_for_undefined_enum_value_in_flat_input",
"tests/test_enums.py::test_input_exc_schema_raises_exception_for_undefined_enum_value_in_nested_object",
"tests/test_enums.py::test_input_exc_schema_raises_exception_for_undefined_enum_value_in_nested_field_arg",
"tests/test_enums.py::test_find_enum_values_in_schema_for_undefined_and_invalid_values",
"tests/test_enums.py::test_enum_type_is_able_to_represent_enum_default_value_in_schema",
"tests/test_enums.py::test_python_enums_can_be_passed_directly_to_make_executable_schema",
"tests/test_enums.py::test_python_str_enums_can_be_passed_directly_to_make_executable_schema",
"tests/test_enums.py::test_error_is_raised_for_python_enum_with_name_not_in_schema"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-06-07 15:44:24+00:00
|
bsd-3-clause
| 3,951 |
|
mirumee__ariadne-1170
|
diff --git a/ariadne/graphql.py b/ariadne/graphql.py
index c17f885..474581a 100644
--- a/ariadne/graphql.py
+++ b/ariadne/graphql.py
@@ -36,6 +36,7 @@ from .extensions import ExtensionManager
from .format_error import format_error
from .logger import log_error
from .types import (
+ BaseProxyRootValue,
ErrorFormatter,
ExtensionList,
GraphQLResult,
@@ -146,6 +147,8 @@ async def graphql(
`**kwargs`: any kwargs not used by `graphql` are passed to
`graphql.graphql`.
"""
+ result_update: Optional[BaseProxyRootValue] = None
+
extension_manager = ExtensionManager(extensions, context_value)
with extension_manager.request():
@@ -200,7 +203,11 @@ async def graphql(
if isawaitable(root_value):
root_value = await root_value
- result = execute(
+ if isinstance(root_value, BaseProxyRootValue):
+ result_update = root_value
+ root_value = root_value.root_value
+
+ exec_result = execute(
schema,
document,
root_value=root_value,
@@ -214,10 +221,10 @@ async def graphql(
**kwargs,
)
- if isawaitable(result):
- result = await cast(Awaitable[ExecutionResult], result)
+ if isawaitable(exec_result):
+ exec_result = await cast(Awaitable[ExecutionResult], exec_result)
except GraphQLError as error:
- return handle_graphql_errors(
+ error_result = handle_graphql_errors(
[error],
logger=logger,
error_formatter=error_formatter,
@@ -225,14 +232,24 @@ async def graphql(
extension_manager=extension_manager,
)
- return handle_query_result(
- result,
+ if result_update:
+ return result_update.update_result(error_result)
+
+ return error_result
+
+ result = handle_query_result(
+ exec_result,
logger=logger,
error_formatter=error_formatter,
debug=debug,
extension_manager=extension_manager,
)
+ if result_update:
+ return result_update.update_result(result)
+
+ return result
+
def graphql_sync(
schema: GraphQLSchema,
@@ -321,6 +338,8 @@ def graphql_sync(
`**kwargs`: any kwargs not used by `graphql_sync` are passed to
`graphql.graphql_sync`.
"""
+ result_update: Optional[BaseProxyRootValue] = None
+
extension_manager = ExtensionManager(extensions, context_value)
with extension_manager.request():
@@ -379,7 +398,11 @@ def graphql_sync(
"in synchronous query executor."
)
- result = execute_sync(
+ if isinstance(root_value, BaseProxyRootValue):
+ result_update = root_value
+ root_value = root_value.root_value
+
+ exec_result = execute_sync(
schema,
document,
root_value=root_value,
@@ -393,13 +416,13 @@ def graphql_sync(
**kwargs,
)
- if isawaitable(result):
- ensure_future(cast(Awaitable[ExecutionResult], result)).cancel()
+ if isawaitable(exec_result):
+ ensure_future(cast(Awaitable[ExecutionResult], exec_result)).cancel()
raise RuntimeError(
"GraphQL execution failed to complete synchronously."
)
except GraphQLError as error:
- return handle_graphql_errors(
+ error_result = handle_graphql_errors(
[error],
logger=logger,
error_formatter=error_formatter,
@@ -407,14 +430,24 @@ def graphql_sync(
extension_manager=extension_manager,
)
- return handle_query_result(
- result,
+ if result_update:
+ return result_update.update_result(error_result)
+
+ return error_result
+
+ result = handle_query_result(
+ exec_result,
logger=logger,
error_formatter=error_formatter,
debug=debug,
extension_manager=extension_manager,
)
+ if result_update:
+ return result_update.update_result(result)
+
+ return result
+
async def subscribe(
schema: GraphQLSchema,
diff --git a/ariadne/types.py b/ariadne/types.py
index 3dc21f0..f77211d 100644
--- a/ariadne/types.py
+++ b/ariadne/types.py
@@ -34,6 +34,7 @@ __all__ = [
"ErrorFormatter",
"ContextValue",
"RootValue",
+ "BaseProxyRootValue",
"QueryParser",
"QueryValidator",
"ValidationRules",
@@ -228,6 +229,35 @@ RootValue = Union[
Callable[[Optional[Any], Optional[str], Optional[dict], DocumentNode], Any],
]
+
+class BaseProxyRootValue:
+ """A `RootValue` wrapper that includes result JSON update logic.
+
+ Can be returned by the `RootValue` callable. Not used by Ariadne directly
+ but part of the support for Ariadne GraphQL Proxy.
+
+ # Attributes
+
+ - `root_value: Optional[dict]`: `RootValue` to use during query execution.
+ """
+
+ __slots__ = ("root_value",)
+
+ root_value: Optional[dict]
+
+ def __init__(self, root_value: Optional[dict] = None):
+ self.root_value = root_value
+
+ def update_result(self, result: GraphQLResult) -> GraphQLResult:
+ """An update function used to create a final `GraphQL` result tuple to
+ create a JSON response from.
+
+ Default implementation in `BaseProxyRootValue` is a passthrough that
+ returns `result` value without any changes.
+ """
+ return result
+
+
"""Type of `query_parser` option of GraphQL servers.
Enables customization of server's GraphQL parsing logic. If not set or `None`,
|
mirumee/ariadne
|
85f538cd3bdfcc18bd61a9c83d4388fe44496e3e
|
diff --git a/tests/conftest.py b/tests/conftest.py
index a48173b..9333a78 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -23,6 +23,7 @@ def type_defs():
testContext: String
testRoot: String
testError: Boolean
+ context: String
}
type Mutation {
diff --git a/tests/test_graphql.py b/tests/test_graphql.py
index 2fd4ea4..eb110df 100644
--- a/tests/test_graphql.py
+++ b/tests/test_graphql.py
@@ -3,6 +3,7 @@ from graphql import ExecutionContext, GraphQLError
from graphql.validation.rules import ValidationRule
from ariadne import graphql, graphql_sync, subscribe
+from ariadne.types import BaseProxyRootValue
class AlwaysInvalid(ValidationRule):
@@ -12,6 +13,12 @@ class AlwaysInvalid(ValidationRule):
self.context.report_error(GraphQLError("Invalid"))
+class ProxyRootValue(BaseProxyRootValue):
+ def update_result(self, result):
+ success, data = result
+ return success, {"updated": True, **data}
+
+
def test_graphql_sync_executes_the_query(schema):
success, result = graphql_sync(schema, {"query": '{ hello(name: "world") }'})
assert success
@@ -51,8 +58,21 @@ def test_graphql_sync_prevents_introspection_query_when_option_is_disabled(schem
)
+def test_graphql_sync_executes_the_query_using_result_update_obj(schema):
+ success, result = graphql_sync(
+ schema,
+ {"query": "{ context }"},
+ root_value=ProxyRootValue({"context": "Works!"}),
+ )
+ assert success
+ assert result == {
+ "data": {"context": "Works!"},
+ "updated": True,
+ }
+
+
@pytest.mark.asyncio
-async def test_graphql_execute_the_query(schema):
+async def test_graphql_executes_the_query(schema):
success, result = await graphql(schema, {"query": '{ hello(name: "world") }'})
assert success
assert result["data"] == {"hello": "Hello, world!"}
@@ -94,6 +114,20 @@ async def test_graphql_prevents_introspection_query_when_option_is_disabled(sche
)
[email protected]
+async def test_graphql_executes_the_query_using_result_update_obj(schema):
+ success, result = await graphql(
+ schema,
+ {"query": "{ context }"},
+ root_value=ProxyRootValue({"context": "Works!"}),
+ )
+ assert success
+ assert result == {
+ "data": {"context": "Works!"},
+ "updated": True,
+ }
+
+
@pytest.mark.asyncio
async def test_subscription_returns_an_async_iterator(schema):
success, result = await subscribe(schema, {"query": "subscription { ping }"})
|
Return data and errors from root resolver callable
Related to: https://github.com/mirumee/ariadne-graphql-proxy/issues/45
~~Root resolver could return a tuple of `data` and `error` or `GraphQLResult`. Errors would then be merged with final result.~~
New idea: a dedicated class (eg. `RootValueResult`) that will implement a `create_result` method. This
|
0.0
|
85f538cd3bdfcc18bd61a9c83d4388fe44496e3e
|
[
"tests/test_graphql.py::test_graphql_sync_executes_the_query",
"tests/test_graphql.py::test_graphql_sync_uses_validation_rules",
"tests/test_graphql.py::test_graphql_sync_uses_execution_context_class",
"tests/test_graphql.py::test_graphql_sync_prevents_introspection_query_when_option_is_disabled",
"tests/test_graphql.py::test_graphql_sync_executes_the_query_using_result_update_obj",
"tests/test_graphql.py::test_graphql_executes_the_query",
"tests/test_graphql.py::test_graphql_uses_validation_rules",
"tests/test_graphql.py::test_graphql_uses_execution_context_class",
"tests/test_graphql.py::test_graphql_prevents_introspection_query_when_option_is_disabled",
"tests/test_graphql.py::test_graphql_executes_the_query_using_result_update_obj",
"tests/test_graphql.py::test_subscription_returns_an_async_iterator",
"tests/test_graphql.py::test_subscription_uses_validation_rules",
"tests/test_graphql.py::test_subscription_prevents_introspection_query_when_option_is_disabled"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-02-28 17:19:00+00:00
|
bsd-3-clause
| 3,952 |
|
mirumee__ariadne-153
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 140a270..befe10e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
- Updated `graphql-core-next` to 1.0.3 which has feature parity with GraphQL.js 14.2.1 and better type annotations.
- `ariadne.asgi.GraphQL` is now an ASGI3 application. ASGI3 is now handled by all ASGI servers.
+- `ObjectType.field` and `SubscriptionType.source` decorators now raise ValueError when used without name argument (eg. `@foo.field`).
- Removed explicit `typing` dependency.
- Added Flask integration example.
diff --git a/ariadne/objects.py b/ariadne/objects.py
index 80e1829..12c869b 100644
--- a/ariadne/objects.py
+++ b/ariadne/objects.py
@@ -14,6 +14,10 @@ class ObjectType(SchemaBindable):
self._resolvers = {}
def field(self, name: str) -> Callable[[Resolver], Resolver]:
+ if not isinstance(name, str):
+ raise ValueError(
+ 'field decorator should be passed a field name: @foo.field("name")'
+ )
return self.create_register_resolver(name)
def create_register_resolver(self, name: str) -> Callable[[Resolver], Resolver]:
diff --git a/ariadne/subscriptions.py b/ariadne/subscriptions.py
index 8c371ff..8a180e3 100644
--- a/ariadne/subscriptions.py
+++ b/ariadne/subscriptions.py
@@ -14,6 +14,10 @@ class SubscriptionType(ObjectType):
self._subscribers = {}
def source(self, name: str) -> Callable[[Subscriber], Subscriber]:
+ if not isinstance(name, str):
+ raise ValueError(
+ 'source decorator should be passed a field name: @foo.source("name")'
+ )
return self.create_register_subscriber(name)
def create_register_subscriber(
|
mirumee/ariadne
|
aa3d994c27a740306edace41ce66842e6a8a02a3
|
diff --git a/tests/test_objects.py b/tests/test_objects.py
index 231c5cc..eaf5b3e 100644
--- a/tests/test_objects.py
+++ b/tests/test_objects.py
@@ -46,6 +46,12 @@ def test_field_resolver_can_be_set_using_decorator(schema):
assert result.data == {"hello": "World"}
+def test_value_error_is_raised_if_field_decorator_was_used_without_argument():
+ query = ObjectType("Query")
+ with pytest.raises(ValueError):
+ query.field(lambda *_: "World")
+
+
def test_field_resolver_can_be_set_using_setter(schema):
query = ObjectType("Query")
query.set_field("hello", lambda *_: "World")
diff --git a/tests/test_subscriptions.py b/tests/test_subscriptions.py
index aede02b..cec70c7 100644
--- a/tests/test_subscriptions.py
+++ b/tests/test_subscriptions.py
@@ -23,9 +23,9 @@ def test_field_source_can_be_set_using_setter(schema):
async def source(*_):
yield "test" # pragma: no cover
- sub = SubscriptionType()
- sub.set_source("message", source)
- sub.bind_to_schema(schema)
+ subscription = SubscriptionType()
+ subscription.set_source("message", source)
+ subscription.bind_to_schema(schema)
field = schema.type_map.get("Subscription").fields["message"]
assert field.subscribe is source
@@ -34,18 +34,27 @@ def test_field_source_can_be_set_using_decorator(schema):
async def source(*_):
yield "test" # pragma: no cover
- sub = SubscriptionType()
- sub.source("message")(source)
- sub.bind_to_schema(schema)
+ subscription = SubscriptionType()
+ subscription.source("message")(source)
+ subscription.bind_to_schema(schema)
field = schema.type_map.get("Subscription").fields["message"]
assert field.subscribe is source
+def test_value_error_is_raised_if_source_decorator_was_used_without_argument():
+ async def source(*_):
+ yield "test" # pragma: no cover
+
+ subscription = SubscriptionType()
+ with pytest.raises(ValueError):
+ subscription.source(source)
+
+
def test_attempt_bind_subscription_to_undefined_field_raises_error(schema):
async def source(*_):
yield "test" # pragma: no cover
- sub_map = SubscriptionType()
- sub_map.set_source("fake", source)
+ subscription = SubscriptionType()
+ subscription.set_source("fake", source)
with pytest.raises(ValueError):
- sub_map.bind_to_schema(schema)
+ subscription.bind_to_schema(schema)
|
Raise ValueError when `field` or `source` decorator was called incorrectly
Currently there's no error when the developer forgets to follow the `field` or `source` decorator with `("name")`, tricking them into thinking that decorated function has been registered while in fact it wasn't.
We could update implementation for those functions to raise ValueError when `name` attr is not `str`.
|
0.0
|
aa3d994c27a740306edace41ce66842e6a8a02a3
|
[
"tests/test_objects.py::test_value_error_is_raised_if_field_decorator_was_used_without_argument",
"tests/test_subscriptions.py::test_value_error_is_raised_if_source_decorator_was_used_without_argument"
] |
[
"tests/test_objects.py::test_attempt_bind_object_type_to_undefined_type_raises_error",
"tests/test_objects.py::test_attempt_bind_object_type_to_invalid_type_raises_error",
"tests/test_objects.py::test_attempt_bind_object_type_field_to_undefined_field_raises_error",
"tests/test_objects.py::test_field_resolver_can_be_set_using_decorator",
"tests/test_objects.py::test_field_resolver_can_be_set_using_setter",
"tests/test_objects.py::test_set_alias_method_creates_resolver_for_specified_attribute",
"tests/test_subscriptions.py::test_field_source_can_be_set_using_setter",
"tests/test_subscriptions.py::test_field_source_can_be_set_using_decorator",
"tests/test_subscriptions.py::test_attempt_bind_subscription_to_undefined_field_raises_error"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-07 10:41:37+00:00
|
bsd-3-clause
| 3,953 |
|
mirumee__ariadne-172
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8064549..4e2c0e0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,7 +12,7 @@
- Added support for `extend type` in schema definitions.
- Removed unused `format_errors` utility function and renamed `ariadne.format_errors` module to `ariadne.format_error`.
- Removed explicit `typing` dependency.
-- Added Flask integration example.
+- Fixed default ENUM values not being set.
## 0.3.0 (2019-04-08)
diff --git a/ariadne/enums.py b/ariadne/enums.py
index bba2fa8..68ce512 100644
--- a/ariadne/enums.py
+++ b/ariadne/enums.py
@@ -37,3 +37,15 @@ class EnumType(SchemaBindable):
"%s is defined in the schema, but it is instance of %s (expected %s)"
% (self.name, type(graphql_type).__name__, GraphQLEnumType.__name__)
)
+
+
+def set_default_enum_values_on_schema(schema: GraphQLSchema):
+ for type_object in schema.type_map.values():
+ if isinstance(type_object, GraphQLEnumType):
+ set_default_enum_values(type_object)
+
+
+def set_default_enum_values(graphql_type: GraphQLEnumType):
+ for key in graphql_type.values:
+ if graphql_type.values[key].value is None:
+ graphql_type.values[key].value = key
diff --git a/ariadne/executable_schema.py b/ariadne/executable_schema.py
index a498316..f3f151a 100644
--- a/ariadne/executable_schema.py
+++ b/ariadne/executable_schema.py
@@ -2,6 +2,7 @@ from typing import List, Union
from graphql import DocumentNode, GraphQLSchema, build_ast_schema, extend_schema, parse
+from .enums import set_default_enum_values_on_schema
from .types import SchemaBindable
@@ -21,6 +22,8 @@ def make_executable_schema(
elif bindables:
bindables.bind_to_schema(schema)
+ set_default_enum_values_on_schema(schema)
+
return schema
|
mirumee/ariadne
|
ccf9e5cb89570bc99f5ebc0f28d6f016642d74b3
|
diff --git a/tests/test_enums.py b/tests/test_enums.py
index ee3e2bc..bd2fb15 100644
--- a/tests/test_enums.py
+++ b/tests/test_enums.py
@@ -30,6 +30,7 @@ def test_succesfull_enum_typed_field():
schema = make_executable_schema([enum_definition, enum_field], query)
result = graphql_sync(schema, "{ testEnum }")
assert result.errors is None
+ assert result.data == {"testEnum": TEST_VALUE}
def test_unsuccesfull_invalid_enum_value_evaluation():
@@ -57,6 +58,18 @@ def test_successful_enum_value_passed_as_argument():
assert result.errors is None, result.errors
+def test_unbound_enum_arg_is_transformed_to_string():
+ query = QueryType()
+ query.set_field("testEnum", lambda *_, value: value == "NEWHOPE")
+
+ schema = make_executable_schema([enum_definition, enum_param], [query])
+ result = graphql_sync(schema, "{ testEnum(value: NEWHOPE) }")
+ assert result.data["testEnum"] is True
+
+ result = graphql_sync(schema, "{ testEnum(value: EMPIRE) }")
+ assert result.data["testEnum"] is False
+
+
def test_unsuccessful_invalid_enum_value_passed_as_argument():
query = QueryType()
query.set_field("testEnum", lambda *_, value: True)
@@ -137,9 +150,12 @@ def test_enum_arg_is_transformed_to_internal_value():
query.set_field("testEnum", lambda *_, value: value == PyEnum.NEWHOPE)
schema = make_executable_schema([enum_definition, enum_param], [query, py_enum])
- result = graphql_sync(schema, "{ testEnum(value: %s) }" % TEST_VALUE)
+ result = graphql_sync(schema, "{ testEnum(value: NEWHOPE) }")
assert result.data["testEnum"] is True
+ result = graphql_sync(schema, "{ testEnum(value: EMPIRE) }")
+ assert result.data["testEnum"] is False
+
class PyIntEnum(IntEnum):
NEWHOPE = 1977
@@ -164,5 +180,8 @@ def test_int_enum_arg_is_transformed_to_internal_value():
query.set_field("testEnum", lambda *_, value: value == PyIntEnum.NEWHOPE)
schema = make_executable_schema([enum_definition, enum_param], [query, int_enum])
- result = graphql_sync(schema, "{ testEnum(value: %s) }" % TEST_VALUE)
+ result = graphql_sync(schema, "{ testEnum(value: NEWHOPE) }")
assert result.data["testEnum"] is True
+
+ result = graphql_sync(schema, "{ testEnum(value: EMPIRE) }")
+ assert result.data["testEnum"] is False
|
Unbound enum values are None when used in arguments
When used as a mutation input, enum parameter should be `str`, but actually is `None`.
```python
def test_executing_mutation_takes_enum():
type_defs = """
type Query {
_: String
}
type Mutation {
eat(meal: Meal!): Int!
}
enum Meal {
SPAM
}
"""
mutation = MutationType()
@mutation.field("eat")
def resolve_eat(*_, meal): # pylint: disable=unused-variable
assert meal == "SPAM"
return 42
schema = make_executable_schema(type_defs, mutation)
result = graphql_sync(schema, 'mutation { eat(meal: SPAM) }')
assert result.errors is None
assert result.data == {"eat": 42}
```
|
0.0
|
ccf9e5cb89570bc99f5ebc0f28d6f016642d74b3
|
[
"tests/test_enums.py::test_unbound_enum_arg_is_transformed_to_string"
] |
[
"tests/test_enums.py::test_succesfull_enum_typed_field",
"tests/test_enums.py::test_unsuccesfull_invalid_enum_value_evaluation",
"tests/test_enums.py::test_successful_enum_value_passed_as_argument",
"tests/test_enums.py::test_unsuccessful_invalid_enum_value_passed_as_argument",
"tests/test_enums.py::test_attempt_bind_custom_enum_to_undefined_type_raises_error",
"tests/test_enums.py::test_attempt_bind_custom_enum_to_wrong_schema_type_raises_error",
"tests/test_enums.py::test_attempt_bind_custom_enum_to_schema_enum_missing_value_raises_error",
"tests/test_enums.py::test_dict_enum_is_resolved_from_internal_value",
"tests/test_enums.py::test_dict_enum_arg_is_transformed_to_internal_value",
"tests/test_enums.py::test_enum_is_resolved_from_internal_value",
"tests/test_enums.py::test_enum_arg_is_transformed_to_internal_value",
"tests/test_enums.py::test_int_enum_is_resolved_from_internal_value",
"tests/test_enums.py::test_int_enum_arg_is_transformed_to_internal_value"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-05-10 15:36:35+00:00
|
bsd-3-clause
| 3,954 |
|
mirumee__ariadne-266
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 180e02a..83a51ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,7 @@
## 0.8.0 (UNRELEASED)
- Added recursive loading of GraphQL schema files from provided path.
+- Added support for passing multiple bindables as `*args` to `make_executable_schema`.
- Updated Starlette dependency to 0.13.
- Made `python-multipart` optional dependency for `asgi-uploads`.
diff --git a/ariadne/executable_schema.py b/ariadne/executable_schema.py
index caf2bca..2eaa44b 100644
--- a/ariadne/executable_schema.py
+++ b/ariadne/executable_schema.py
@@ -17,8 +17,7 @@ from .types import SchemaBindable
def make_executable_schema(
type_defs: Union[str, List[str]],
- bindables: Union[SchemaBindable, List[SchemaBindable], None] = None,
- *,
+ *bindables: Union[SchemaBindable, List[SchemaBindable]],
directives: Dict[str, Type[SchemaDirectiveVisitor]] = None,
) -> GraphQLSchema:
if isinstance(type_defs, list):
@@ -28,11 +27,12 @@ def make_executable_schema(
schema = build_and_extend_schema(ast_document)
validate_schema(schema)
- if isinstance(bindables, list):
- for obj in bindables:
- obj.bind_to_schema(schema)
- elif bindables:
- bindables.bind_to_schema(schema)
+ for bindable in bindables:
+ if isinstance(bindable, list):
+ for obj in bindable:
+ obj.bind_to_schema(schema)
+ else:
+ bindable.bind_to_schema(schema)
set_default_enum_values_on_schema(schema)
|
mirumee/ariadne
|
c74037919273300ecc5ceee68097f21faba3954e
|
diff --git a/tests/test_modularization.py b/tests/test_modularization.py
index 8fac5c9..89f23d9 100644
--- a/tests/test_modularization.py
+++ b/tests/test_modularization.py
@@ -107,3 +107,27 @@ def test_defined_type_can_be_extended_with_new_field():
result = graphql_sync(schema, "{ admin { username } }")
assert result.errors is None
assert result.data == {"admin": {"username": "Abby"}}
+
+
+def test_multiple_bindables_can_be_passed_as_separate_args():
+ type_defs = """
+ type Query {
+ user: User
+ }
+
+ type User {
+ username: String
+ }
+ """
+
+ query = QueryType()
+ query.set_field("user", lambda *_: Mock(first_name="Joe"))
+
+ user = ObjectType("User")
+ user.set_alias("username", "first_name")
+
+ schema = make_executable_schema(type_defs, query, user)
+
+ result = graphql_sync(schema, "{ user { username } }")
+ assert result.errors is None
+ assert result.data == {"user": {"username": "Joe"}}
|
Change `make_executable_schema` API to accept multiple bindables args
Currently, the second argument to `make_executable_schema` is list of `SchemaBindlables` or single bindable:
```python
# Single bindable:
schema = make_executable_schema(type_defs, query_type, debug=True)
# Multiple bindables:
schema = make_executable_schema(type_defs, [query_type, mutation_type], debug=True)
```
Looking at Ariadne uses in the wild, a pattern is starting to emerge where developers create dedicated modules/packages in their project for `scalars`, `mutations` or `types`, that use their `__init__.py`'s to gather all bindables into single lists:
```
from .scalars import scalars
from .types import types
from .mutations import mutations
```
Those are then combined into single list and passed to `make_executable_schema`:
```
schema = make_executable_schema(type_defs, scalars + types + mutations, debug=True)
```
This looks ugly, but things get uglier when there's bindable involved:
```
schema = make_executable_schema(type_defs, scalars + types + mutations + [fallback_resolvers], debug=True)
```
We can simplify this by changing bindables to `*bindables`:
```
schema = make_executable_schema(type_defs, scalars, types, mutations, fallback_resolvers, debug=True)
```
|
0.0
|
c74037919273300ecc5ceee68097f21faba3954e
|
[
"tests/test_modularization.py::test_multiple_bindables_can_be_passed_as_separate_args"
] |
[
"tests/test_modularization.py::test_list_of_type_defs_is_merged_into_executable_schema",
"tests/test_modularization.py::test_redefining_existing_type_causes_type_error",
"tests/test_modularization.py::test_same_type_resolver_maps_are_merged_into_executable_schema",
"tests/test_modularization.py::test_different_types_resolver_maps_are_merged_into_executable_schema",
"tests/test_modularization.py::test_defined_type_can_be_extended_with_new_field"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-11-23 22:40:31+00:00
|
bsd-3-clause
| 3,955 |
|
mirumee__ariadne-481
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d7b568a..87cfb29 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,7 +2,7 @@
## 0.13.0 (unreleased)
-- Updated GraphQL-core requirement to 3.1.0.
+- Updated GraphQL-core requirement to 3.1.3.
## 0.12.0 (2020-08-04)
diff --git a/ariadne/asgi.py b/ariadne/asgi.py
index f97cfaa..2402e74 100644
--- a/ariadne/asgi.py
+++ b/ariadne/asgi.py
@@ -26,7 +26,13 @@ from .file_uploads import combine_multipart_data
from .format_error import format_error
from .graphql import graphql, subscribe
from .logger import log_error
-from .types import ContextValue, ErrorFormatter, ExtensionList, RootValue, ValidationRules
+from .types import (
+ ContextValue,
+ ErrorFormatter,
+ ExtensionList,
+ RootValue,
+ ValidationRules,
+)
GQL_CONNECTION_INIT = "connection_init" # Client -> Server
GQL_CONNECTION_ACK = "connection_ack" # Server -> Client
diff --git a/ariadne/contrib/federation/utils.py b/ariadne/contrib/federation/utils.py
index 14acb1c..be7c5a8 100644
--- a/ariadne/contrib/federation/utils.py
+++ b/ariadne/contrib/federation/utils.py
@@ -115,7 +115,7 @@ def includes_directive(
return False
directives = gather_directives(type_object)
- return any([d.name.value == directive_name for d in directives])
+ return any(d.name.value == directive_name for d in directives)
def gather_directives(
diff --git a/ariadne/schema_visitor.py b/ariadne/schema_visitor.py
index b4aabe1..9ac24f9 100644
--- a/ariadne/schema_visitor.py
+++ b/ariadne/schema_visitor.py
@@ -563,7 +563,9 @@ def heal_schema(schema: GraphQLSchema) -> GraphQLSchema:
each(type_.fields, _heal_field)
- def heal_type(type_: GraphQLNamedType) -> GraphQLNamedType:
+ def heal_type(
+ type_: Union[GraphQLList, GraphQLNamedType, GraphQLNonNull]
+ ) -> Union[GraphQLList, GraphQLNamedType, GraphQLNonNull]:
# Unwrap the two known wrapper types
if isinstance(type_, GraphQLList):
type_ = GraphQLList(heal_type(type_.of_type))
diff --git a/ariadne/utils.py b/ariadne/utils.py
index 13c34d0..2a3e3bf 100644
--- a/ariadne/utils.py
+++ b/ariadne/utils.py
@@ -6,20 +6,29 @@ from graphql import GraphQLError, parse
def convert_camel_case_to_snake(graphql_name: str) -> str:
+ # pylint: disable=too-many-boolean-expressions
+ max_index = len(graphql_name) - 1
+ lowered_name = graphql_name.lower()
+
python_name = ""
- for i, c in enumerate(graphql_name.lower()):
- if (
- i > 0
- and (
- all(
- (
- c != graphql_name[i],
- graphql_name[i - 1] != "_",
- graphql_name[i - 1] == python_name[-1],
- )
- )
+ for i, c in enumerate(lowered_name):
+ if i > 0 and (
+ # testWord -> test_word
+ (
+ c != graphql_name[i]
+ and graphql_name[i - 1] != "_"
+ and graphql_name[i - 1] == python_name[-1]
+ )
+ # TESTWord -> test_word
+ or (
+ i < max_index
+ and graphql_name[i] != lowered_name[i]
+ and graphql_name[i + 1] == lowered_name[i + 1]
)
- or all((c.isdigit(), graphql_name[i - 1].isdigit() is False))
+ # test134 -> test_134
+ or (c.isdigit() and not graphql_name[i - 1].isdigit())
+ # 134test -> 134_test
+ or (not c.isdigit() and graphql_name[i - 1].isdigit())
):
python_name += "_"
python_name += c
diff --git a/requirements.txt b/requirements.txt
index 3f9302c..9ddc28a 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -4,7 +4,6 @@
#
# pip-compile --output-file=requirements.txt setup.py
#
-
-graphql-core==3.1.1 # via ariadne (setup.py)
-starlette==0.13.2 # via ariadne (setup.py)
-typing-extensions==3.7.4.1 # via ariadne (setup.py)
+graphql-core==3.1.3
+starlette==0.14.2
+typing-extensions==3.7.4.3
|
mirumee/ariadne
|
3550f5ee281d87d2c988d00ed3c83bcdcbf7e29d
|
diff --git a/tests/test_case_convertion_util.py b/tests/test_camel_case_to_snake_case_convertion.py
similarity index 78%
rename from tests/test_case_convertion_util.py
rename to tests/test_camel_case_to_snake_case_convertion.py
index 3b27626..b55040d 100644
--- a/tests/test_case_convertion_util.py
+++ b/tests/test_camel_case_to_snake_case_convertion.py
@@ -1,3 +1,5 @@
+import pytest
+
from ariadne import convert_camel_case_to_snake
@@ -41,8 +43,16 @@ def test_no_underscore_added_if_previous_character_is_an_underscore():
def test_no_underscore_added_if_previous_character_is_uppercase():
- assert convert_camel_case_to_snake("testWithUPPERPart") == "test_with_upperpart"
-
-
-def test_digits_are_treated_as_word():
- assert convert_camel_case_to_snake("testWith365InIt") == "test_with_365_in_it"
+ assert convert_camel_case_to_snake("testWithUPPERPart") == "test_with_upper_part"
+
+
[email protected](
+ ("test_str", "result"),
+ [
+ ("testWith365InIt", "test_with_365_in_it"),
+ ("365testWithInIt", "365_test_with_in_it"),
+ ("testWithInIt365", "test_with_in_it_365"),
+ ],
+)
+def test_digits_are_treated_as_word(test_str, result):
+ assert convert_camel_case_to_snake(test_str) == result
|
Unexpected Snake Case for Acronyms
The snake case conversion of the `snake_case_fallback_resolvers` yields unexpected results for words with multiple uppercase letters in a row, e.g.
- `getHTTPResponse` is converted to `get_h_t_t_p_response`, or
- `externalID` is converted to "external_i_d`.
These are unlikely names for python attributes and I would expect the resolver to look for `get_http_response` / `external_id` instead.
Possible implementations for the camel to snake case conversions are discussed here: https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
|
0.0
|
3550f5ee281d87d2c988d00ed3c83bcdcbf7e29d
|
[
"tests/test_camel_case_to_snake_case_convertion.py::test_no_underscore_added_if_previous_character_is_uppercase",
"tests/test_camel_case_to_snake_case_convertion.py::test_digits_are_treated_as_word[365testWithInIt-365_test_with_in_it]"
] |
[
"tests/test_camel_case_to_snake_case_convertion.py::test_lower_case_name_is_not_changed",
"tests/test_camel_case_to_snake_case_convertion.py::test_two_words_snake_case_name_is_not_changed",
"tests/test_camel_case_to_snake_case_convertion.py::test_three_words_snake_case_name_is_not_changed",
"tests/test_camel_case_to_snake_case_convertion.py::test_pascal_case_name_is_lowercased",
"tests/test_camel_case_to_snake_case_convertion.py::test_two_words_pascal_case_name_is_converted",
"tests/test_camel_case_to_snake_case_convertion.py::test_two_words_camel_case_name_is_converted",
"tests/test_camel_case_to_snake_case_convertion.py::test_three_words_pascal_case_name_is_converted",
"tests/test_camel_case_to_snake_case_convertion.py::test_three_words_camel_case_name_is_converted",
"tests/test_camel_case_to_snake_case_convertion.py::test_no_underscore_added_if_previous_character_is_an_underscore",
"tests/test_camel_case_to_snake_case_convertion.py::test_digits_are_treated_as_word[testWith365InIt-test_with_365_in_it]",
"tests/test_camel_case_to_snake_case_convertion.py::test_digits_are_treated_as_word[testWithInIt365-test_with_in_it_365]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-03-02 20:55:34+00:00
|
bsd-3-clause
| 3,956 |
|
mirumee__ariadne-565
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4198b89..14971ee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,7 @@
- Added `on_connect` and `on_disconnect` options to `ariadne.asgi.GraphQL`, enabling developers to run additional initialization and cleanup for websocket connections.
- Updated Starlette dependency to 0.15.
- Added support for multiple keys for GraphQL federations.
-
+- Made `Query` type optional in federated schemas.
## 0.13.0 (2021-03-17)
diff --git a/ariadne/contrib/federation/schema.py b/ariadne/contrib/federation/schema.py
index 686cabb..9d5b302 100644
--- a/ariadne/contrib/federation/schema.py
+++ b/ariadne/contrib/federation/schema.py
@@ -2,6 +2,7 @@ from typing import Dict, List, Type, Union, cast
from graphql import extend_schema, parse
from graphql.language import DocumentNode
+from graphql.language.ast import ObjectTypeDefinitionNode
from graphql.type import (
GraphQLObjectType,
GraphQLSchema,
@@ -17,13 +18,13 @@ from .utils import get_entity_types, purge_schema_directives, resolve_entities
federation_service_type_defs = """
scalar _Any
- type _Service {
+ type _Service {{
sdl: String
- }
+ }}
- extend type Query {
+ {type_token} Query {{
_service: _Service!
- }
+ }}
directive @external on FIELD_DEFINITION
directive @requires(fields: String!) on FIELD_DEFINITION
@@ -41,6 +42,17 @@ federation_entity_type_defs = """
"""
+def has_query_type(type_defs: str) -> bool:
+ ast_document = parse(type_defs)
+ for definition in ast_document.definitions:
+ if (
+ isinstance(definition, ObjectTypeDefinitionNode)
+ and definition.name.value == "Query"
+ ):
+ return True
+ return False
+
+
def make_federated_schema(
type_defs: Union[str, List[str]],
*bindables: Union[SchemaBindable, List[SchemaBindable]],
@@ -52,8 +64,10 @@ def make_federated_schema(
# Remove custom schema directives (to avoid apollo-gateway crashes).
# NOTE: This does NOT interfere with ariadne's directives support.
sdl = purge_schema_directives(type_defs)
+ type_token = "extend type" if has_query_type(sdl) else "type"
+ federation_service_type = federation_service_type_defs.format(type_token=type_token)
- type_defs = join_type_defs([type_defs, federation_service_type_defs])
+ type_defs = join_type_defs([type_defs, federation_service_type])
schema = make_executable_schema(
type_defs,
*bindables,
@@ -66,10 +80,7 @@ def make_federated_schema(
# Add the federation type definitions.
if has_entities:
- schema = extend_federated_schema(
- schema,
- parse(federation_entity_type_defs),
- )
+ schema = extend_federated_schema(schema, parse(federation_entity_type_defs))
# Add _entities query.
entity_type = schema.get_type("_Entity")
|
mirumee/ariadne
|
8b23fbe5305fc88f4a5f320e22ff717c027ccb80
|
diff --git a/tests/federation/test_schema.py b/tests/federation/test_schema.py
index 5ff8b5d..99e0e31 100644
--- a/tests/federation/test_schema.py
+++ b/tests/federation/test_schema.py
@@ -810,3 +810,29 @@ def test_federated_schema_query_service_ignore_custom_directives():
}
"""
)
+
+
+def test_federated_schema_without_query_is_valid():
+ type_defs = """
+ type Product @key(fields: "upc") {
+ upc: String!
+ name: String
+ price: Int
+ weight: Int
+ }
+ """
+
+ schema = make_federated_schema(type_defs)
+ result = graphql_sync(
+ schema,
+ """
+ query GetServiceDetails {
+ _service {
+ sdl
+ }
+ }
+ """,
+ )
+
+ assert result.errors is None
+ assert sic(result.data["_service"]["sdl"]) == sic(type_defs)
|
Federated schemas should not require at least one query to be implemented
In a Federated environment, the Gateway instantiates the Query type by default. This means that an implementing services should _not_ be required to implement or extend a query.
# Ideal Scenario
This is an example scenario of what is valid in Node and Java implementations. For example, it should be valid to expose a service that exposes no root queries, but only the federated query fields, like below.
Produced Query type:
**Example**: This is what the schemas would look like for two federated services:
## Product Service
product/schema.gql
```gql
extend type Query {
products: [Product]
}
type Product {
id: ID!
name: String
reviews: [ProductReview]
}
extend type ProductReview @key(fields: "id") {
id: ID! @external
}
```
**Output**:
```
products: [Product]
_entities(representations: [_Any]): [_Entity]
_service: _Service
```
## Review Service
review/schema.gql
```gql
# Notice how we don't have to extend the Query type
type ProductReview @key(fields: "id") {
id: ID!
comment: String!
}
```
**Output**:
This should be valid.
```
_entities(representations: [_Any]): [_Entity]
_service: _Service
```
# Breaking Scenario
When attempting to implement the `ProductReview` service (see example above) without extending the Query type, Ariadne will fail to [generate a federated schema](https://github.com/mirumee/ariadne/blob/master/ariadne/contrib/federation/schema.py#L57). This is because `make_executable_schema` attempts to generate a federated schema by [extending a Query type](https://github.com/mirumee/ariadne/blob/master/ariadne/contrib/federation/schema.py#L24) with the assumption that a Query type has been defined, which technically it isn't.
|
0.0
|
8b23fbe5305fc88f4a5f320e22ff717c027ccb80
|
[
"tests/federation/test_schema.py::test_federated_schema_without_query_is_valid"
] |
[
"tests/federation/test_schema.py::test_federated_schema_mark_type_with_key",
"tests/federation/test_schema.py::test_federated_schema_mark_type_with_key_split_type_defs",
"tests/federation/test_schema.py::test_federated_schema_mark_type_with_multiple_keys",
"tests/federation/test_schema.py::test_federated_schema_not_mark_type_with_no_keys",
"tests/federation/test_schema.py::test_federated_schema_type_with_multiple_keys",
"tests/federation/test_schema.py::test_federated_schema_mark_interface_with_key",
"tests/federation/test_schema.py::test_federated_schema_mark_interface_with_multiple_keys",
"tests/federation/test_schema.py::test_federated_schema_augment_root_query_with_type_key",
"tests/federation/test_schema.py::test_federated_schema_augment_root_query_with_interface_key",
"tests/federation/test_schema.py::test_federated_schema_augment_root_query_with_no_keys",
"tests/federation/test_schema.py::test_federated_schema_execute_reference_resolver",
"tests/federation/test_schema.py::test_federated_schema_execute_reference_resolver_with_multiple_keys[sku]",
"tests/federation/test_schema.py::test_federated_schema_execute_reference_resolver_with_multiple_keys[upc]",
"tests/federation/test_schema.py::test_federated_schema_execute_async_reference_resolver",
"tests/federation/test_schema.py::test_federated_schema_execute_default_reference_resolver",
"tests/federation/test_schema.py::test_federated_schema_execute_reference_resolver_that_returns_none",
"tests/federation/test_schema.py::test_federated_schema_raises_error_on_missing_type",
"tests/federation/test_schema.py::test_federated_schema_query_service_with_key",
"tests/federation/test_schema.py::test_federated_schema_query_service_with_multiple_keys",
"tests/federation/test_schema.py::test_federated_schema_query_service_provide_federation_directives",
"tests/federation/test_schema.py::test_federated_schema_query_service_ignore_custom_directives"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-29 15:01:52+00:00
|
bsd-3-clause
| 3,957 |
|
mirumee__ariadne-661
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14971ee..d3898fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,8 @@
- Updated Starlette dependency to 0.15.
- Added support for multiple keys for GraphQL federations.
- Made `Query` type optional in federated schemas.
-
+- Updated default resolvers to test for `Mapping` instead of `dict`.
+
## 0.13.0 (2021-03-17)
- Updated `graphQL-core` requirement to 3.1.3.
diff --git a/ariadne/resolvers.py b/ariadne/resolvers.py
index 9e9bf80..e01bdbc 100644
--- a/ariadne/resolvers.py
+++ b/ariadne/resolvers.py
@@ -1,3 +1,4 @@
+from collections.abc import Mapping
from typing import Any
from graphql import default_field_resolver
@@ -41,7 +42,7 @@ snake_case_fallback_resolvers = SnakeCaseFallbackResolversSetter()
def resolve_parent_field(parent: Any, field_name: str) -> Any:
- if isinstance(parent, dict):
+ if isinstance(parent, Mapping):
return parent.get(field_name)
return getattr(parent, field_name, None)
diff --git a/ariadne/utils.py b/ariadne/utils.py
index 2a3e3bf..e855588 100644
--- a/ariadne/utils.py
+++ b/ariadne/utils.py
@@ -1,4 +1,5 @@
import asyncio
+from collections.abc import Mapping
from functools import wraps
from typing import Optional, Union, Callable, Dict, Any
@@ -49,13 +50,15 @@ def unwrap_graphql_error(
def convert_kwargs_to_snake_case(func: Callable) -> Callable:
- def convert_to_snake_case(d: Dict) -> Dict:
+ def convert_to_snake_case(m: Mapping) -> Dict:
converted: Dict = {}
- for k, v in d.items():
- if isinstance(v, dict):
+ for k, v in m.items():
+ if isinstance(v, Mapping):
v = convert_to_snake_case(v)
if isinstance(v, list):
- v = [convert_to_snake_case(i) if isinstance(i, dict) else i for i in v]
+ v = [
+ convert_to_snake_case(i) if isinstance(i, Mapping) else i for i in v
+ ]
converted[convert_camel_case_to_snake(k)] = v
return converted
|
mirumee/ariadne
|
851dc4774407cb07cd698ce9fa870b3f0ace0416
|
diff --git a/tests/conftest.py b/tests/conftest.py
index eef6627..b545a3d 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,3 +1,5 @@
+from collections.abc import Mapping
+
import pytest
from graphql.validation.rules import ValidationRule
@@ -123,3 +125,21 @@ def validation_rule():
pass
return NoopRule
+
+
[email protected]
+def fake_mapping():
+ class FakeMapping(Mapping):
+ def __init__(self, **kwargs):
+ self._dummy = {**kwargs}
+
+ def __getitem__(self, key):
+ return self._dummy[key]
+
+ def __iter__(self):
+ return iter(self._dummy)
+
+ def __len__(self):
+ return len(self._dummy.keys())
+
+ return FakeMapping
diff --git a/tests/test_kwargs_camel_case_conversion.py b/tests/test_kwargs_camel_case_conversion.py
index f1812e1..4a37103 100644
--- a/tests/test_kwargs_camel_case_conversion.py
+++ b/tests/test_kwargs_camel_case_conversion.py
@@ -5,30 +5,46 @@ from ariadne import convert_kwargs_to_snake_case
def test_decorator_converts_kwargs_to_camel_case():
@convert_kwargs_to_snake_case
- def my_func(*_, **kwargs):
+ def wrapped_func(*_, **kwargs):
assert kwargs == {
"first_parameter": True,
"second_parameter": "value",
"nested_parameter": {"first_sub_entry": 1, "second_sub_entry": 2},
}
- my_func(
+ wrapped_func(
firstParameter=True,
secondParameter="value",
nestedParameter={"firstSubEntry": 1, "secondSubEntry": 2},
)
+def test_decorator_converts_kwargs_to_camel_case_for_mapping(fake_mapping):
+ @convert_kwargs_to_snake_case
+ def wrapped_func(*_, **kwargs):
+ assert kwargs == {
+ "first_parameter": True,
+ "second_parameter": "value",
+ "nested_parameter": {"first_sub_entry": 1, "second_sub_entry": 2},
+ }
+
+ wrapped_func(
+ firstParameter=True,
+ secondParameter="value",
+ nestedParameter=fake_mapping(firstSubEntry=1, secondSubEntry=2),
+ )
+
+
def test_decorator_leaves_snake_case_kwargs_unchanged():
@convert_kwargs_to_snake_case
- def my_func(*_, **kwargs):
+ def wrapped_func(*_, **kwargs):
assert kwargs == {
"first_parameter": True,
"second_parameter": "value",
"nested_parameter": {"first_sub_entry": 1, "second_sub_entry": 2},
}
- my_func(
+ wrapped_func(
first_parameter=True,
second_parameter="value",
nested_parameter={"first_sub_entry": 1, "second_sub_entry": 2},
@@ -37,7 +53,7 @@ def test_decorator_leaves_snake_case_kwargs_unchanged():
def test_decorator_converts_objects_in_lists_to_camel_case():
@convert_kwargs_to_snake_case
- def my_func(*_, **kwargs):
+ def wrapped_func(*_, **kwargs):
assert kwargs == {
"first_parameter": True,
"list_of_items": [
@@ -45,21 +61,37 @@ def test_decorator_converts_objects_in_lists_to_camel_case():
],
}
- my_func(
+ wrapped_func(
firstParameter=True,
listOfItems=[{"firstProperty": 1, "secondProperty": 2}],
)
+def test_decorator_converts_mappings_in_lists_to_camel_case(fake_mapping):
+ @convert_kwargs_to_snake_case
+ def wrapped_func(*_, **kwargs):
+ assert kwargs == {
+ "first_parameter": True,
+ "list_of_items": [
+ {"first_property": 1, "second_property": 2},
+ ],
+ }
+
+ wrapped_func(
+ firstParameter=True,
+ listOfItems=[fake_mapping(firstProperty=1, secondProperty=2)],
+ )
+
+
def test_decorator_leaves_primitives_in_lists_unchanged():
@convert_kwargs_to_snake_case
- def my_func(*_, **kwargs):
+ def wrapped_func(*_, **kwargs):
assert kwargs == {
"first_parameter": True,
"list_of_items": ["firstItem", "secondItem"],
}
- my_func(
+ wrapped_func(
firstParameter=True,
listOfItems=["firstItem", "secondItem"],
)
@@ -68,14 +100,14 @@ def test_decorator_leaves_primitives_in_lists_unchanged():
@pytest.mark.asyncio
async def test_decorator_converts_kwargs_to_camel_case_for_async_resolver():
@convert_kwargs_to_snake_case
- async def my_func(*_, **kwargs):
+ async def wrapped_func(*_, **kwargs):
assert kwargs == {
"first_parameter": True,
"second_parameter": "value",
"nested_parameter": {"first_sub_entry": 1, "second_sub_entry": 2},
}
- await my_func(
+ await wrapped_func(
firstParameter=True,
secondParameter="value",
nestedParameter={"firstSubEntry": 1, "secondSubEntry": 2},
@@ -85,14 +117,14 @@ async def test_decorator_converts_kwargs_to_camel_case_for_async_resolver():
@pytest.mark.asyncio
async def test_decorator_leaves_snake_case_kwargs_unchanged_for_async_resolver():
@convert_kwargs_to_snake_case
- async def my_func(*_, **kwargs):
+ async def wrapped_func(*_, **kwargs):
assert kwargs == {
"first_parameter": True,
"second_parameter": "value",
"nested_parameter": {"first_sub_entry": 1, "second_sub_entry": 2},
}
- await my_func(
+ await wrapped_func(
first_parameter=True,
second_parameter="value",
nested_parameter={"first_sub_entry": 1, "second_sub_entry": 2},
|
snake_case_fallback_resolvers not calling obj.get(attr_name)
**Ariadne version:** 0.13.0
**Python version:** 3.8.11
Hello. I am using the [databases](https://www.encode.io/databases/) package with an [asyncpg](https://magicstack.github.io/asyncpg/current/) backend to interact with a PostgreSQL database. The objects returned from my queries are of the type `databases.backends.postgres.Record`. The desired attributes can only can accessed via the get method. However, when I use `snake_case_fallback_resolvers`, Ariadne has trouble resolving the requested fields and I receive the following error: `Cannot return null for non-nullable field`
If I instead use the regular `fallback_resolvers` (adjusting my schema's naming conventions), Ariadne is able to resolve the requested fields.
Is this a bug or am I doing something wrong? Thank you for your time.
|
0.0
|
851dc4774407cb07cd698ce9fa870b3f0ace0416
|
[
"tests/test_kwargs_camel_case_conversion.py::test_decorator_converts_kwargs_to_camel_case_for_mapping",
"tests/test_kwargs_camel_case_conversion.py::test_decorator_converts_mappings_in_lists_to_camel_case"
] |
[
"tests/test_kwargs_camel_case_conversion.py::test_decorator_converts_kwargs_to_camel_case",
"tests/test_kwargs_camel_case_conversion.py::test_decorator_leaves_snake_case_kwargs_unchanged",
"tests/test_kwargs_camel_case_conversion.py::test_decorator_converts_objects_in_lists_to_camel_case",
"tests/test_kwargs_camel_case_conversion.py::test_decorator_leaves_primitives_in_lists_unchanged",
"tests/test_kwargs_camel_case_conversion.py::test_decorator_converts_kwargs_to_camel_case_for_async_resolver",
"tests/test_kwargs_camel_case_conversion.py::test_decorator_leaves_snake_case_kwargs_unchanged_for_async_resolver"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-01 13:55:58+00:00
|
bsd-3-clause
| 3,958 |
|
mirumee__ariadne-67
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 857e135..7e569de 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
- Removed support for Python 3.5 and added support for 3.7.
- Moved to `GraphQL-core-next` that supports `async` resolvers, query execution and implements more recent version of GraphQL spec. If you are updating existing project, you will need to uninstall `graphql-core` before installing `graphql-core-next`, as both libraries use `graphql` namespace.
+- Added `gql()` utility that provides GraphQL string validation on declaration time, and enables use of [Apollo-GraphQL](https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo) plugin in Python code.
- `Boolean` built-in scalar now checks the type of each serialized value. Returning values of type other than `bool`, `int` or `float` from a field resolver will result in a `Boolean cannot represent a non boolean value` error.
- Redefining type in `type_defs` will now result in `TypeError` being raised. This is breaking change from previous behaviour where old type was simply replaced with new one.
-- Returning `None` from scalar `parse_literal` and `parse_value` function no longer results in GraphQL API producing default error message. Instead `None` will be passed further down to resolver or producing "value is required" error if its marked as such with `!` For old behaviour raise either `ValueError` or `TypeError`. See documentation for more details.
+- Returning `None` from scalar `parse_literal` and `parse_value` function no longer results in GraphQL API producing default error message. Instead `None` will be passed further down to resolver or producing "value is required" error if its marked as such with `!` For old behaviour raise either `ValueError` or `TypeError`. See documentation for more details.
\ No newline at end of file
diff --git a/README.md b/README.md
index d2c0e09..bea59e0 100644
--- a/README.md
+++ b/README.md
@@ -27,10 +27,11 @@ Ariadne can be installed with pip:
Following example creates API defining `Person` type and single query field `people` returning list of two persons. It also starts local dev server with [GraphQL Playground](https://github.com/prisma/graphql-playground) available on the `http://127.0.0.1:8888` address.
```python
-from ariadne import GraphQLMiddleware
+from ariadne import GraphQLMiddleware, gql
# Define types using Schema Definition Language (https://graphql.org/learn/schema/)
-type_defs = """
+# Wrapping string in gql function provides validation and better error traceback
+type_defs = gql("""
type Query {
people: [Person!]!
}
@@ -41,7 +42,7 @@ type_defs = """
age: Int
fullName: String
}
-"""
+""")
# Resolvers are simple python functions
diff --git a/ariadne/__init__.py b/ariadne/__init__.py
index d9fdbf1..5784542 100644
--- a/ariadne/__init__.py
+++ b/ariadne/__init__.py
@@ -1,5 +1,6 @@
from .executable_schema import make_executable_schema
from .resolvers import add_resolve_functions_to_schema, default_resolver, resolve_to
+from .utils import gql
from .wsgi_middleware import GraphQLMiddleware
__all__ = [
@@ -8,4 +9,5 @@ __all__ = [
"default_resolver",
"make_executable_schema",
"resolve_to",
+ "gql",
]
diff --git a/ariadne/utils.py b/ariadne/utils.py
new file mode 100644
index 0000000..d10576e
--- /dev/null
+++ b/ariadne/utils.py
@@ -0,0 +1,6 @@
+from graphql import parse
+
+
+def gql(value: str) -> str:
+ parse(value)
+ return value
diff --git a/docs/introduction.rst b/docs/introduction.rst
index 528881d..fd766f1 100644
--- a/docs/introduction.rst
+++ b/docs/introduction.rst
@@ -30,6 +30,32 @@ Using the SDL, our ``Query`` type definition will look like this::
The ``type Query { }`` block declares the type, ``hello`` is the field definition, ``String`` is the return value type, and the exclamation mark following it means that returned value will never be ``null``.
+Validating schema
+-----------------
+
+Ariadne provides tiny ``gql`` utility function that takes single argument: GraphQL string, validates it and raises descriptive ``GraphQLSyntaxError``, or returns original unmodified string if its correct::
+
+ from ariadne import gql
+
+ type_defs = gql("""
+ type Query {
+ hello String!
+ }
+ """)
+
+If we try to run above code now, we will get an error pointing to our incorrect syntax within our ``type_defs`` declaration::
+
+ graphql.error.syntax_error.GraphQLSyntaxError: Syntax Error: Expected :, found Name
+
+ GraphQL request (3:19)
+ type Query {
+ hello String!
+ ^
+ }
+
+Using ``gql`` is optional, but without it above error would occur during your server's initialization and point to somewhere inside Ariadne's GraphQL initialization logic, making tracking down incorrect place trickier if your API is large and spread across many modules.
+
+
Resolvers
---------
@@ -105,13 +131,13 @@ Completed code
For reference here is complete code of the API from this guide::
- from ariadne import GraphQLMiddleware
+ from ariadne import GraphQLMiddleware, gql
- type_defs = """
+ type_defs = gql("""
type Query {
hello: String!
}
- """
+ """)
def resolve_hello(_, info):
|
mirumee/ariadne
|
f3b3bfba3da18f1a566c125f0e56632deaeee5d4
|
diff --git a/tests/test_gql_util.py b/tests/test_gql_util.py
new file mode 100644
index 0000000..ab66580
--- /dev/null
+++ b/tests/test_gql_util.py
@@ -0,0 +1,54 @@
+import pytest
+from graphql.error import GraphQLSyntaxError
+
+from ariadne import gql
+
+
+def test_valid_graphql_schema_string_is_returned_unchanged():
+ sdl = """
+ type User {
+ username: String!
+ }
+ """
+ result = gql(sdl)
+ assert sdl == result
+
+
+def test_invalid_graphql_schema_string_causes_syntax_error():
+ with pytest.raises(GraphQLSyntaxError):
+ gql(
+ """
+ type User {
+ username String!
+ }
+ """
+ )
+
+
+def test_valid_graphql_query_string_is_returned_unchanged():
+ query = """
+ query TestQuery {
+ auth
+ users {
+ id
+ username
+ }
+ }
+ """
+ result = gql(query)
+ assert query == result
+
+
+def test_invalid_graphql_query_string_causes_syntax_error():
+ with pytest.raises(GraphQLSyntaxError):
+ gql(
+ """
+ query TestQuery {
+ auth
+ users
+ id
+ username
+ }
+ }
+ """
+ )
|
Provide gql() utility function for wrapping/validating SDL on spot
Currently, syntax errors in SDL are raised by `graphql()`, which itself is called deep in GraphQL server initialization logic. This makes it trickier to trace back to invalid type definitions - especially in complex projects.
Ariadne could provide `gql()` utility function that would allow developers to mark pieces of code as SDL, and validate those SDL strings on scripts execution, raising execetions with traceback pointing to point of definition, making those easier to find and debug:
```python
from ariadne import gql
type_defs = gql("""
type User {
username: String!
posts: [Post!]
threads: [Thread!]
follows [User!]
likes: [Post!]
}
""")
```
Above code would raise `GraphQLSyntaxError` pointing to `type_defs`, instead of somewhere in GraphQL server initialization logic.
This approach adds one more advantage: If we know that strings wrapped with `gql()` are SDL, we can develop a pattern for GraphQL syntax highlighters for IDEs to use to color GraphQL syntax in Python projects.
Lastly, `gql()` should pass through the strings, because our current modularization implementation is very simple: internally it does string joining using `\n` as glue. We'll rather avoid reimplementing it to create custom mechanism operating on `ast`'s.
|
0.0
|
f3b3bfba3da18f1a566c125f0e56632deaeee5d4
|
[
"tests/test_gql_util.py::test_valid_graphql_schema_string_is_returned_unchanged",
"tests/test_gql_util.py::test_invalid_graphql_schema_string_causes_syntax_error",
"tests/test_gql_util.py::test_valid_graphql_query_string_is_returned_unchanged",
"tests/test_gql_util.py::test_invalid_graphql_query_string_causes_syntax_error"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-11-20 17:28:07+00:00
|
bsd-3-clause
| 3,959 |
|
mirumee__ariadne-68
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e569de..de30277 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
- Removed support for Python 3.5 and added support for 3.7.
- Moved to `GraphQL-core-next` that supports `async` resolvers, query execution and implements more recent version of GraphQL spec. If you are updating existing project, you will need to uninstall `graphql-core` before installing `graphql-core-next`, as both libraries use `graphql` namespace.
- Added `gql()` utility that provides GraphQL string validation on declaration time, and enables use of [Apollo-GraphQL](https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo) plugin in Python code.
+- Added `start_simple_server()` shortcut for creating simple server with `GraphQLMiddleware.make_server()` and then running it with `serve_forever()`.
- `Boolean` built-in scalar now checks the type of each serialized value. Returning values of type other than `bool`, `int` or `float` from a field resolver will result in a `Boolean cannot represent a non boolean value` error.
- Redefining type in `type_defs` will now result in `TypeError` being raised. This is breaking change from previous behaviour where old type was simply replaced with new one.
- Returning `None` from scalar `parse_literal` and `parse_value` function no longer results in GraphQL API producing default error message. Instead `None` will be passed further down to resolver or producing "value is required" error if its marked as such with `!` For old behaviour raise either `ValueError` or `TypeError`. See documentation for more details.
\ No newline at end of file
diff --git a/README.md b/README.md
index bea59e0..f139833 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,7 @@ Ariadne can be installed with pip:
Following example creates API defining `Person` type and single query field `people` returning list of two persons. It also starts local dev server with [GraphQL Playground](https://github.com/prisma/graphql-playground) available on the `http://127.0.0.1:8888` address.
```python
-from ariadne import GraphQLMiddleware, gql
+from ariadne import gql, start_simple_server
# Define types using Schema Definition Language (https://graphql.org/learn/schema/)
# Wrapping string in gql function provides validation and better error traceback
@@ -65,8 +65,7 @@ resolvers = {
# Create and run dev server that provides api browser
-graphql_server = GraphQLMiddleware.make_simple_server(type_defs, resolvers)
-graphql_server.serve_forever() # Visit http://127.0.0.1:8888 to see API browser!
+start_simple_server(type_defs, resolvers) # Visit http://127.0.0.1:8888 to see API browser!
```
For more guides and examples, please see the [documentation](https://ariadne.readthedocs.io/en/latest/?badge=latest).
diff --git a/ariadne/__init__.py b/ariadne/__init__.py
index 5784542..a8738f0 100644
--- a/ariadne/__init__.py
+++ b/ariadne/__init__.py
@@ -1,6 +1,6 @@
from .executable_schema import make_executable_schema
from .resolvers import add_resolve_functions_to_schema, default_resolver, resolve_to
-from .utils import gql
+from .utils import gql, start_simple_server
from .wsgi_middleware import GraphQLMiddleware
__all__ = [
@@ -10,4 +10,5 @@ __all__ = [
"make_executable_schema",
"resolve_to",
"gql",
+ "start_simple_server",
]
diff --git a/ariadne/utils.py b/ariadne/utils.py
index d10576e..4975d30 100644
--- a/ariadne/utils.py
+++ b/ariadne/utils.py
@@ -1,6 +1,26 @@
+from typing import List, Union
+
from graphql import parse
+from .wsgi_middleware import GraphQLMiddleware
+
def gql(value: str) -> str:
parse(value)
return value
+
+
+def start_simple_server(
+ type_defs: Union[str, List[str]],
+ resolvers: Union[dict, List[dict]],
+ host: str = "127.0.0.1",
+ port: int = 8888,
+):
+ try:
+ print("Simple GraphQL server is running on the http://%s:%s" % (host, port))
+ graphql_server = GraphQLMiddleware.make_simple_server(
+ type_defs, resolvers, host, port
+ )
+ graphql_server.serve_forever()
+ except KeyboardInterrupt:
+ pass
diff --git a/docs/introduction.rst b/docs/introduction.rst
index fd766f1..4192577 100644
--- a/docs/introduction.rst
+++ b/docs/introduction.rst
@@ -100,24 +100,17 @@ Testing the API
Now we have everything we need to finish our API, with only piece missing being the http server that would receive the HTTP requests, execute GraphQL queries and return responses.
-This is where Ariadne comes into play. One of the utilities that Ariadne provides to developers is a WSGI middleware that can also be run as simple http server for developers to experiment with GraphQL locally.
+This is where Ariadne comes into play. One of the utilities that Ariadne provides is a ``start_simple_server`` that enables developers to experiment with GraphQL locally without need for full-fledged HTTP stack or web framework::
-.. warning::
- Please never run ``GraphQLMiddleware`` in production without a proper WSGI container such as uWSGI or Gunicorn.
+ from ariadne import start_simple_server
-This middleware can be imported directly from ``ariadne`` package, so lets add an appropriate import at the beginning of our Python script::
+We will now call ``start_simple_server`` with ``type_defs`` and ``resolvers`` as its arguments to start a simple dev server::
- from ariadne import GraphQLMiddleware
+ start_simple_server(type_defs, resolvers)
-We will now call ``GraphQLMiddleware.make_simple_server`` class method with ``type_defs`` and ``resolvers`` as its arguments to construct a simple dev server that we can then start::
+Run your script with ``python myscript.py`` (remember to replace ``myscript.py`` with name of your file!). If all is well, you will see a message telling you that simple GraphQL server is running on the http://127.0.0.1:8888. Open this link in your web browser.
- print("Visit the http://127.0.0.1:8888 in the browser and say { hello }!")
- my_api_server = GraphQLMiddleware.make_simple_server(type_defs, resolvers)
- my_api_server.serve_forever()
-
-Run your script with ``python myscript.py`` (remember to replace ``myscript.py`` with name of your file!). If all is well, you will see a message telling you to visit the http://127.0.0.1:8888 and say ``{ hello }``.
-
-This the GraphQL Playground, the open source API explorer for GraphQL APIs. You can enter ``{ hello }`` query on the left, press the big bright "run" button, and see the result on the right:
+You will see the GraphQL Playground, the open source API explorer for GraphQL APIs. You can enter ``{ hello }`` query on the left, press the big bright "run" button, and see the result on the right:
.. image:: _static/hello-world.png
:alt: Your first Ariadne GraphQL in action!
@@ -131,7 +124,7 @@ Completed code
For reference here is complete code of the API from this guide::
- from ariadne import GraphQLMiddleware, gql
+ from ariadne import gql, start_simple_server
type_defs = gql("""
type Query {
@@ -152,6 +145,4 @@ For reference here is complete code of the API from this guide::
}
}
- print("Visit the http://127.0.0.1:8888 in the browser and say { hello }!")
- my_api_server = GraphQLMiddleware.make_simple_server(type_defs, resolvers)
- my_api_server.serve_forever()
+ start_simple_server(type_defs, resolvers)
diff --git a/docs/wsgi-middleware.rst b/docs/wsgi-middleware.rst
index b9c5bd4..8eadf8f 100644
--- a/docs/wsgi-middleware.rst
+++ b/docs/wsgi-middleware.rst
@@ -92,4 +92,10 @@ The ``make_simple_server`` respects inheritance chain, so you can use it in cust
return MyContext(environ, request_data)
simple_server = MyGraphQLMiddleware(type_defs, resolvers)
- simple_server.serve_forever() # info.context will now be instance of MyContext
\ No newline at end of file
+ simple_server.serve_forever() # info.context will now be instance of MyContext
+
+.. warning::
+ Please never run ``GraphQLMiddleware`` in production without a proper WSGI container such as uWSGI or Gunicorn.
+
+.. note::
+ ``ariadne.start_simple_server`` is actually a simple shortcut that internally creates HTTP server with ``GraphQLMiddleware.make_simple_server``, starts it with `serve_forever`, displays instruction message and handles ``KeyboardInterrupt`` gracefully.
|
mirumee/ariadne
|
deefa9945a02efe04e8653d6ef758f9661d190ae
|
diff --git a/tests/test_start_simple_server.py b/tests/test_start_simple_server.py
new file mode 100644
index 0000000..2468984
--- /dev/null
+++ b/tests/test_start_simple_server.py
@@ -0,0 +1,78 @@
+import pytest
+
+from ariadne import GraphQLMiddleware, start_simple_server
+
+
[email protected]
+def simple_server_mock(mocker):
+ return mocker.Mock(serve_forever=mocker.Mock(return_value=True))
+
+
[email protected]
+def middleware_make_simple_server_mock(mocker):
+ return mocker.patch.object(
+ GraphQLMiddleware, "make_simple_server", new=mocker.Mock()
+ )
+
+
[email protected]
+def type_defs():
+ return """
+ type Query {
+ hello: String
+ }
+ """
+
+
[email protected]
+def resolvers():
+ return {}
+
+
+def test_wsgi_simple_server_serve_forever_is_called(
+ mocker, type_defs, resolvers, simple_server_mock
+):
+ mocker.patch("wsgiref.simple_server.make_server", return_value=simple_server_mock)
+ start_simple_server(type_defs, resolvers)
+ simple_server_mock.serve_forever.assert_called_once()
+
+
+def test_keyboard_interrupt_is_handled_gracefully(mocker, type_defs, resolvers):
+ mocker.patch(
+ "wsgiref.simple_server.make_server", side_effect=KeyboardInterrupt("test")
+ )
+ start_simple_server(type_defs, resolvers)
+
+
+def test_type_defs_resolvers_host_and_ip_are_passed_to_graphql_middleware(
+ middleware_make_simple_server_mock
+):
+ start_simple_server("type_defs", "resolvers", "0.0.0.0", 4444)
+ middleware_make_simple_server_mock.assert_called_once_with(
+ "type_defs", "resolvers", "0.0.0.0", 4444
+ )
+
+
+def test_default_host_and_ip_are_passed_to_graphql_middleware_if_not_set(
+ middleware_make_simple_server_mock
+):
+ start_simple_server("type_defs", "resolvers")
+ middleware_make_simple_server_mock.assert_called_once_with(
+ "type_defs", "resolvers", "127.0.0.1", 8888
+ )
+
+
+def test_default_host_and_ip_are_printed_on_server_creation(
+ middleware_make_simple_server_mock, capsys
+): # pylint: disable=unused-argument
+ start_simple_server("", {})
+ captured = capsys.readouterr()
+ assert "http://127.0.0.1:8888" in captured.out
+
+
+def test_custom_host_and_ip_are_printed_on_server_creation(
+ middleware_make_simple_server_mock, capsys
+): # pylint: disable=unused-argument
+ start_simple_server("", {}, "0.0.0.0", 4444)
+ captured = capsys.readouterr()
+ assert "http://0.0.0.0:4444" in captured.out
|
Create shortcut function for GraphQLMiddleware.make_simple_server
Getting started with Ariadne could be made even simpler by providing shortcut function abstracting the `GraphQLMiddleware` away on first contact, thus saving users possible confusion about what they really are doing.
|
0.0
|
deefa9945a02efe04e8653d6ef758f9661d190ae
|
[
"tests/test_start_simple_server.py::test_wsgi_simple_server_serve_forever_is_called",
"tests/test_start_simple_server.py::test_keyboard_interrupt_is_handled_gracefully",
"tests/test_start_simple_server.py::test_type_defs_resolvers_host_and_ip_are_passed_to_graphql_middleware",
"tests/test_start_simple_server.py::test_default_host_and_ip_are_passed_to_graphql_middleware_if_not_set",
"tests/test_start_simple_server.py::test_default_host_and_ip_are_printed_on_server_creation",
"tests/test_start_simple_server.py::test_custom_host_and_ip_are_printed_on_server_creation"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-11-22 14:39:06+00:00
|
bsd-3-clause
| 3,960 |
|
mirumee__ariadne-75
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 63a8fbd..66b9bfe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
- Removed support for Python 3.5 and added support for 3.7.
- Moved to `GraphQL-core-next` that supports `async` resolvers, query execution and implements more recent version of GraphQL spec. If you are updating existing project, you will need to uninstall `graphql-core` before installing `graphql-core-next`, as both libraries use `graphql` namespace.
- Added `gql()` utility that provides GraphQL string validation on declaration time, and enables use of [Apollo-GraphQL](https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo) plugin in Python code.
+- Added `load_schema_from_path()` utility function that loads GraphQL types from file or directory containing `.graphql` files, also performing syntax validation.
- Added `start_simple_server()` shortcut function for a quick dev server creation, abstracting away the `GraphQLMiddleware.make_server()` from first time users.
- `Boolean` built-in scalar now checks the type of each serialized value. Returning values of type other than `bool`, `int` or `float` from a field resolver will result in a `Boolean cannot represent a non boolean value` error.
- Redefining type in `type_defs` will now result in `TypeError` being raised. This is breaking change from previous behaviour where old type was simply replaced with new one.
@@ -15,4 +16,4 @@
- Added `snake_case_fallback_resolvers` that populates schema with default resolvers that map `CamelCase` and `PascalCase` field names from schema to `snake_sase` names in Python.
- Added `ResolverMap` object that enables assignment of resolver functions to schema types.
- Added `Scalar` object that enables assignment of `serialize`, `parse_value` and `parse_literal` functions to custom scalars.
-- Both `ResolverMap` and `Scalar` are validating if schema defines specified types and/or fields at moment of creation of executable schema, providing better feedback to developer.
\ No newline at end of file
+- Both `ResolverMap` and `Scalar` are validating if schema defines specified types and/or fields at moment of creation of executable schema, providing better feedback to developer.
diff --git a/ariadne/__init__.py b/ariadne/__init__.py
index 8f68984..8e938fd 100644
--- a/ariadne/__init__.py
+++ b/ariadne/__init__.py
@@ -1,4 +1,5 @@
from .executable_schema import make_executable_schema
+from .load_schema import load_schema_from_path
from .resolvers import (
FallbackResolversSetter,
ResolverMap,
@@ -13,6 +14,7 @@ from .simple_server import start_simple_server
from .utils import convert_camel_case_to_snake, gql
from .wsgi_middleware import GraphQLMiddleware
+
__all__ = [
"FallbackResolversSetter",
"GraphQLMiddleware",
@@ -23,6 +25,7 @@ __all__ = [
"default_resolver",
"fallback_resolvers",
"gql",
+ "load_schema_from_path",
"make_executable_schema",
"resolve_to",
"snake_case_fallback_resolvers",
diff --git a/ariadne/exceptions.py b/ariadne/exceptions.py
index 22c4542..6f7d015 100644
--- a/ariadne/exceptions.py
+++ b/ariadne/exceptions.py
@@ -15,3 +15,15 @@ class HttpBadRequestError(HttpError):
class HttpMethodNotAllowedError(HttpError):
status = HTTP_STATUS_405_METHOD_NOT_ALLOWED
+
+
+class GraphQLFileSyntaxError(Exception):
+ def __init__(self, schema_file, message):
+ super().__init__()
+ self.message = self.format_message(schema_file, message)
+
+ def format_message(self, schema_file, message):
+ return f"Could not load {schema_file}:\n{message}"
+
+ def __str__(self):
+ return self.message
diff --git a/ariadne/load_schema.py b/ariadne/load_schema.py
new file mode 100644
index 0000000..2919a38
--- /dev/null
+++ b/ariadne/load_schema.py
@@ -0,0 +1,31 @@
+import os
+from typing import Generator
+
+from graphql import parse
+from graphql.error import GraphQLSyntaxError
+
+from .exceptions import GraphQLFileSyntaxError
+
+
+def load_schema_from_path(path: str) -> str:
+ if os.path.isdir(path):
+ schema_list = [read_graphql_file(f) for f in walk_graphql_files(path)]
+ return "\n".join(schema_list)
+ return read_graphql_file(os.path.abspath(path))
+
+
+def walk_graphql_files(path: str) -> Generator:
+ def abs_path(f):
+ return os.path.abspath(os.path.join(path, f))
+
+ return (abs_path(f) for f in sorted(os.listdir(path)) if f.endswith(".graphql"))
+
+
+def read_graphql_file(path: str) -> str:
+ with open(path, "r") as graphql_file:
+ schema = graphql_file.read()
+ try:
+ parse(schema)
+ except GraphQLSyntaxError as e:
+ raise GraphQLFileSyntaxError(path, str(e))
+ return schema
|
mirumee/ariadne
|
19b89f4368dd9aa669d8b8eb6d86c7af4bb4b5cc
|
diff --git a/tests/test_schema_file_load.py b/tests/test_schema_file_load.py
new file mode 100644
index 0000000..4ff09d1
--- /dev/null
+++ b/tests/test_schema_file_load.py
@@ -0,0 +1,71 @@
+import pytest
+from ariadne import exceptions, load_schema_from_path
+
+FIRST_SCHEMA = """
+ type Query {
+ test: Custom
+ }
+
+ type Custom {
+ node: String
+ default: String
+ }
+"""
+
+
[email protected](scope="session")
+def single_file_schema(tmpdir_factory):
+ f = tmpdir_factory.mktemp("schema").join("schema.graphql")
+ f.write(FIRST_SCHEMA)
+ return f
+
+
+def test_load_schema_from_single_file(single_file_schema):
+ assert load_schema_from_path(str(single_file_schema)) == FIRST_SCHEMA
+
+
+INCORRECT_SCHEMA = """
+ type Query {
+ test: Custom
+
+ type Custom {
+ node: String
+ default: String
+ }
+"""
+
+
[email protected](scope="session")
+def incorrect_schema_file(tmpdir_factory):
+ f = tmpdir_factory.mktemp("schema").join("schema.graphql")
+ f.write(INCORRECT_SCHEMA)
+ return f
+
+
+def test_loading_schema_fails_on_bad_syntax(incorrect_schema_file):
+ with pytest.raises(exceptions.GraphQLFileSyntaxError) as e:
+ load_schema_from_path(str(incorrect_schema_file))
+ assert str(incorrect_schema_file) in str(e)
+
+
+SECOND_SCHEMA = """
+ type User {
+ name: String
+ }
+"""
+
+
[email protected]
+def schema_directory(tmpdir_factory):
+ directory = tmpdir_factory.mktemp("schema")
+ first_file = directory.join("base.graphql")
+ first_file.write(FIRST_SCHEMA)
+ second_file = directory.join("user.graphql")
+ second_file.write(SECOND_SCHEMA)
+ return directory
+
+
+def test_loading_schema_from_directory(schema_directory):
+ assert load_schema_from_path(str(schema_directory)) == "\n".join(
+ [FIRST_SCHEMA, SECOND_SCHEMA]
+ )
|
Provide utility for loading types from file/directory
We could provide a utility function that would take a path to the filesystem, and:
- if its a file, read it, validate that its correct file, and return SDL string
- if its a directory, glob `.graphql` files, validate each file, and concat them into single SDL string
That way users could easily use single schema definition for both graphql API and frontend tools.
|
0.0
|
19b89f4368dd9aa669d8b8eb6d86c7af4bb4b5cc
|
[
"tests/test_schema_file_load.py::test_load_schema_from_single_file",
"tests/test_schema_file_load.py::test_loading_schema_from_directory"
] |
[] |
{
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-12-11 16:58:41+00:00
|
bsd-3-clause
| 3,961 |
|
mirumee__ariadne-980
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cae3086..027bb41 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,7 +10,7 @@
- Added support for `@tag` directive used by Apollo Federation.
- Updated `starlette` dependency in setup.py to `<1.0`.
- Moved project configuration from `setup.py` to `pyproject.toml`.
-- Added `execution_context_class` option.
+- Added `execution_context_class` option to ASGI and WSGI `applications`.
- Added `query_parser` option to ASGI and WSGI `GraphQL` applications that enables query parsing customization.
- Added Python 3.11 support.
diff --git a/ariadne/asgi/graphql.py b/ariadne/asgi/graphql.py
index 272fd6d..3ad62ce 100644
--- a/ariadne/asgi/graphql.py
+++ b/ariadne/asgi/graphql.py
@@ -1,7 +1,7 @@
from logging import Logger, LoggerAdapter
-from typing import Optional, Union
+from typing import Optional, Type, Union
-from graphql import GraphQLSchema
+from graphql import ExecutionContext, GraphQLSchema
from starlette.types import Receive, Scope, Send
from ..explorer import Explorer, ExplorerGraphiQL
@@ -34,6 +34,7 @@ class GraphQL:
explorer: Optional[Explorer] = None,
logger: Union[None, str, Logger, LoggerAdapter] = None,
error_formatter: ErrorFormatter = format_error,
+ execution_context_class: Optional[Type[ExecutionContext]] = None,
http_handler: Optional[GraphQLHTTPHandler] = None,
websocket_handler: Optional[GraphQLWebsocketHandler] = None,
) -> None:
@@ -61,6 +62,7 @@ class GraphQL:
explorer,
logger,
error_formatter,
+ execution_context_class,
)
self.websocket_handler.configure(
schema,
@@ -73,6 +75,7 @@ class GraphQL:
explorer,
logger,
error_formatter,
+ execution_context_class,
http_handler=self.http_handler,
)
diff --git a/ariadne/asgi/handlers/base.py b/ariadne/asgi/handlers/base.py
index 2ec6df3..48fa219 100644
--- a/ariadne/asgi/handlers/base.py
+++ b/ariadne/asgi/handlers/base.py
@@ -1,9 +1,9 @@
from abc import ABC, abstractmethod
from inspect import isawaitable
from logging import Logger, LoggerAdapter
-from typing import Any, Optional, Union
+from typing import Any, Optional, Type, Union
-from graphql import DocumentNode, GraphQLSchema
+from graphql import DocumentNode, ExecutionContext, GraphQLSchema
from starlette.types import Receive, Scope, Send
from ...explorer import Explorer
@@ -34,6 +34,7 @@ class GraphQLHandler(ABC):
self.root_value: Optional[RootValue] = None
self.query_parser: Optional[QueryParser] = None
self.validation_rules: Optional[ValidationRules] = None
+ self.execution_context_class: Optional[Type[ExecutionContext]] = None
@abstractmethod
async def handle(self, scope: Scope, receive: Receive, send: Send):
@@ -51,10 +52,12 @@ class GraphQLHandler(ABC):
explorer: Optional[Explorer] = None,
logger: Union[None, str, Logger, LoggerAdapter] = None,
error_formatter: ErrorFormatter = format_error,
+ execution_context_class: Optional[Type[ExecutionContext]] = None,
):
self.context_value = context_value
self.debug = debug
self.error_formatter = error_formatter
+ self.execution_context_class = execution_context_class
self.introspection = introspection
self.explorer = explorer
self.logger = logger
diff --git a/ariadne/asgi/handlers/http.py b/ariadne/asgi/handlers/http.py
index 3f80118..91e1ad6 100644
--- a/ariadne/asgi/handlers/http.py
+++ b/ariadne/asgi/handlers/http.py
@@ -112,6 +112,7 @@ class GraphQLHTTPHandler(GraphQLHttpHandlerBase):
error_formatter=self.error_formatter,
extensions=extensions,
middleware=middleware,
+ execution_context_class=self.execution_context_class,
)
async def graphql_http_server(self, request: Request) -> Response:
diff --git a/ariadne/wsgi.py b/ariadne/wsgi.py
index 79fd84e..54ebbb5 100644
--- a/ariadne/wsgi.py
+++ b/ariadne/wsgi.py
@@ -1,8 +1,8 @@
import json
from inspect import isawaitable
-from typing import Any, Callable, Dict, List, Optional, Union, cast
+from typing import Any, Callable, Dict, List, Optional, Type, Union, cast
-from graphql import GraphQLError, GraphQLSchema
+from graphql import ExecutionContext, GraphQLError, GraphQLSchema
from graphql.execution import Middleware, MiddlewareManager
from .constants import (
@@ -65,6 +65,7 @@ class GraphQL:
error_formatter: ErrorFormatter = format_error,
extensions: Optional[Extensions] = None,
middleware: Optional[Middlewares] = None,
+ execution_context_class: Optional[Type[ExecutionContext]] = None,
) -> None:
self.context_value = context_value
self.root_value = root_value
@@ -76,6 +77,7 @@ class GraphQL:
self.error_formatter = error_formatter
self.extensions = extensions
self.middleware = middleware
+ self.execution_context_class = execution_context_class
self.schema = schema
if explorer:
@@ -214,6 +216,7 @@ class GraphQL:
error_formatter=self.error_formatter,
extensions=extensions,
middleware=middleware,
+ execution_context_class=self.execution_context_class,
)
def get_context_for_request(self, environ: dict) -> Optional[ContextValue]:
|
mirumee/ariadne
|
36c72e0a9aabc76aeb5955831c0e88bddd7fea22
|
diff --git a/tests/wsgi/test_configuration.py b/tests/wsgi/test_configuration.py
index 95f2d89..47f8608 100644
--- a/tests/wsgi/test_configuration.py
+++ b/tests/wsgi/test_configuration.py
@@ -1,15 +1,25 @@
import json
+import sys
from io import BytesIO
from unittest.mock import ANY, Mock
+import pytest
from graphql import parse
from werkzeug.test import Client
from werkzeug.wrappers import Response
+from ariadne import QueryType, make_executable_schema
from ariadne.constants import DATA_TYPE_JSON
from ariadne.types import ExtensionSync
from ariadne.wsgi import GraphQL
+PY_37 = sys.version_info < (3, 8)
+
+if not PY_37:
+ # Sync dataloader is python 3.8 and later only
+ # pylint: disable=import-error
+ from graphql_sync_dataloaders import DeferredExecutionContext, SyncDataLoader
+
# Add TestClient to keep test similar to ASGI
class TestClient(Client):
@@ -205,3 +215,33 @@ def test_middleware_function_result_is_passed_to_query_executor(schema):
app = GraphQL(schema, middleware=get_middleware)
_, result = app.execute_query({}, {"query": '{ hello(name: "BOB") }'})
assert result == {"data": {"hello": "**Hello, BOB!**"}}
+
+
[email protected](PY_37, reason="requires python 3.8")
+def test_wsgi_app_supports_sync_dataloader_with_custom_execution_context():
+ type_defs = """
+ type Query {
+ test(arg: ID!): String!
+ }
+ """
+
+ def dataloader_fn(keys):
+ return keys
+
+ dataloader = SyncDataLoader(dataloader_fn)
+
+ query = QueryType()
+ query.set_field("test", lambda *_, arg: dataloader.load(arg))
+
+ schema = make_executable_schema(
+ type_defs,
+ [query],
+ )
+
+ app = GraphQL(schema, execution_context_class=DeferredExecutionContext)
+ client = TestClient(app)
+
+ response = client.post(
+ "/", json={"query": "{ test1: test(arg: 1), test2: test(arg: 2) }"}
+ )
+ assert response.json == {"data": {"test1": "1", "test2": "2"}}
|
Add `execution_context_class` to ASGI and WSGI GraphQL apps
#968 added support for `execution_context_class` customization in our `graphql` wrappers around `execute`, but there's no way currently to set those on GraphQL apps.
|
0.0
|
36c72e0a9aabc76aeb5955831c0e88bddd7fea22
|
[
"tests/wsgi/test_configuration.py::test_wsgi_app_supports_sync_dataloader_with_custom_execution_context"
] |
[
"tests/wsgi/test_configuration.py::test_custom_context_value_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_is_set_and_called_by_app",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_is_called_with_request_value",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_result_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_root_value_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_root_value_function_is_set_and_called_by_app",
"tests/wsgi/test_configuration.py::test_custom_root_value_function_is_called_with_context_value",
"tests/wsgi/test_configuration.py::test_custom_query_parser_is_used",
"tests/wsgi/test_configuration.py::test_custom_validation_rule_is_called_by_query_validation",
"tests/wsgi/test_configuration.py::test_custom_validation_rules_function_is_set_and_called_on_query_execution",
"tests/wsgi/test_configuration.py::test_custom_validation_rules_function_is_called_with_context_value",
"tests/wsgi/test_configuration.py::test_default_logger_is_used_to_log_error_if_custom_is_not_set",
"tests/wsgi/test_configuration.py::test_custom_logger_is_used_to_log_error",
"tests/wsgi/test_configuration.py::test_custom_logger_instance_is_used_to_log_error",
"tests/wsgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_error",
"tests/wsgi/test_configuration.py::test_error_formatter_is_called_with_debug_enabled_flag",
"tests/wsgi/test_configuration.py::test_error_formatter_is_called_with_debug_disabled_flag",
"tests/wsgi/test_configuration.py::test_extension_from_option_are_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_extensions_function_result_is_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_middlewares_are_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_middleware_function_result_is_passed_to_query_executor"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-25 18:53:14+00:00
|
bsd-3-clause
| 3,962 |
|
mirumee__ariadne-990
|
diff --git a/.pylintrc b/.pylintrc
index 02b186f..46abd67 100644
--- a/.pylintrc
+++ b/.pylintrc
@@ -3,7 +3,7 @@ ignore=snapshots
load-plugins=pylint.extensions.bad_builtin, pylint.extensions.mccabe
[MESSAGES CONTROL]
-disable=C0103, C0111, C0209, C0412, I0011, R0101, R0801, R0901, R0902, R0903, R0912, R0913, R0914, R0915, R1260, W0231, W0621, W0703
+disable=C0103, C0111, C0209, C0412, I0011, R0101, R0801, R0901, R0902, R0903, R0912, R0913, R0914, R0915, R1260, W0231, W0511, W0621, W0703
[SIMILARITIES]
ignore-imports=yes
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7bf3892..6dcf457 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,10 +10,11 @@
- Added support for `@tag` directive used by Apollo Federation.
- Updated `starlette` dependency in setup.py to `<1.0`.
- Moved project configuration from `setup.py` to `pyproject.toml`.
-- Added `execution_context_class` option to ASGI and WSGI `applications`.
+- Changed `root_value` option in ASGI and WSGI applications for callables to take operation and and variables in addition to context and parsed query.
+- Added `execution_context_class` option to ASGI and WSGI applications.
- Added `query_parser` option to ASGI and WSGI `GraphQL` applications that enables query parsing customization.
- Changed `middleware` option to work with callable or list of middlewares instead of `MiddlewareManager` instance.
-- Added `middleware_manager_class` option to ASGI and WSGI `applications`.
+- Added `middleware_manager_class` option to ASGI and WSGI applications.
- Added Python 3.11 support.
diff --git a/ariadne/graphql.py b/ariadne/graphql.py
index 834d2f0..fc1d493 100644
--- a/ariadne/graphql.py
+++ b/ariadne/graphql.py
@@ -13,6 +13,7 @@ from typing import (
cast,
Union,
)
+from warnings import warn
from graphql import (
DocumentNode,
@@ -46,6 +47,16 @@ from .types import (
from .validation.introspection_disabled import IntrospectionDisabledRule
+def root_value_two_args_deprecated(): # TODO: remove in 0.19
+ warn(
+ "'root_value(context, document)' has been deprecated and will raise a type "
+ "error in Ariadne 0.18, update definition to "
+ "'root_value(context, operation_name, variables, document)'.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+
async def graphql(
schema: GraphQLSchema,
data: Any,
@@ -99,7 +110,14 @@ async def graphql(
)
if callable(root_value):
- root_value = root_value(context_value, document)
+ try:
+ root_value = root_value( # type: ignore
+ context_value, operation_name, variables, document
+ )
+ except TypeError: # TODO: remove in 0.19
+ root_value_two_args_deprecated()
+ root_value = root_value(context_value, document) # type: ignore
+
if isawaitable(root_value):
root_value = await root_value
@@ -190,7 +208,14 @@ def graphql_sync(
)
if callable(root_value):
- root_value = root_value(context_value, document)
+ try:
+ root_value = root_value( # type: ignore
+ context_value, operation_name, variables, document
+ )
+ except TypeError: # TODO: remove in 0.19
+ root_value_two_args_deprecated()
+ root_value = root_value(context_value, document) # type: ignore
+
if isawaitable(root_value):
ensure_future(root_value).cancel()
raise RuntimeError(
@@ -280,7 +305,14 @@ async def subscribe(
)
if callable(root_value):
- root_value = root_value(context_value, document)
+ try:
+ root_value = root_value( # type: ignore
+ context_value, operation_name, variables, document
+ )
+ except TypeError: # TODO: remove in 0.19
+ root_value_two_args_deprecated()
+ root_value = root_value(context_value, document) # type: ignore
+
if isawaitable(root_value):
root_value = await root_value
diff --git a/ariadne/types.py b/ariadne/types.py
index 9368464..74046b9 100644
--- a/ariadne/types.py
+++ b/ariadne/types.py
@@ -40,7 +40,11 @@ Subscriber = Callable[..., AsyncGenerator]
ErrorFormatter = Callable[[GraphQLError, bool], dict]
ContextValue = Union[Any, Callable[[Any], Any]]
-RootValue = Union[Any, Callable[[Optional[Any], DocumentNode], Any]]
+RootValue = Union[
+ Any,
+ Callable[[Optional[Any], DocumentNode], Any], # TODO: remove in 0.19
+ Callable[[Optional[Any], Optional[str], Optional[dict], DocumentNode], Any],
+]
QueryParser = Callable[[ContextValue, Dict[str, Any]], DocumentNode]
|
mirumee/ariadne
|
bc1e00bc31ccab9e8312872075ffd05043e5a59e
|
diff --git a/tests/asgi/test_configuration.py b/tests/asgi/test_configuration.py
index 9f1ceba..f7c007d 100644
--- a/tests/asgi/test_configuration.py
+++ b/tests/asgi/test_configuration.py
@@ -111,6 +111,21 @@ def test_custom_root_value_function_is_called_by_query(schema):
get_root_value.assert_called_once()
+def test_custom_deprecated_root_value_function_raises_warning_by_query(
+ schema,
+):
+ def get_root_value(_context, _document):
+ return True
+
+ app = GraphQL(
+ schema, context_value={"test": "TEST-CONTEXT"}, root_value=get_root_value
+ )
+ client = TestClient(app)
+
+ with pytest.deprecated_call():
+ client.post("/", json={"query": "{ status }"})
+
+
def test_custom_root_value_function_is_called_by_subscription(schema):
get_root_value = Mock(return_value=True)
app = GraphQL(schema, root_value=get_root_value)
@@ -131,6 +146,29 @@ def test_custom_root_value_function_is_called_by_subscription(schema):
get_root_value.assert_called_once()
+def test_custom_deprecated_root_value_function_raises_warning_by_subscription(schema):
+ def get_root_value(_context, _document):
+ return True
+
+ app = GraphQL(schema, root_value=get_root_value)
+ client = TestClient(app)
+
+ with pytest.deprecated_call():
+ with client.websocket_connect("/", ["graphql-ws"]) as ws:
+ ws.send_json({"type": GraphQLWSHandler.GQL_CONNECTION_INIT})
+ ws.send_json(
+ {
+ "type": GraphQLWSHandler.GQL_START,
+ "id": "test1",
+ "payload": {"query": "subscription { ping }"},
+ }
+ )
+ response = ws.receive_json()
+ assert response["type"] == GraphQLWSHandler.GQL_CONNECTION_ACK
+ response = ws.receive_json()
+ assert response["type"] == GraphQLWSHandler.GQL_DATA
+
+
def test_custom_root_value_function_is_called_by_subscription_graphql_transport_ws(
schema,
):
@@ -156,6 +194,34 @@ def test_custom_root_value_function_is_called_by_subscription_graphql_transport_
get_root_value.assert_called_once()
+def test_custom_deprecated_root_value_function_raises_warning_by_subscription_graphql_transport_ws(
+ schema,
+):
+ def get_root_value(_context, _document):
+ return True
+
+ websocket_handler = GraphQLTransportWSHandler()
+ app = GraphQL(
+ schema, root_value=get_root_value, websocket_handler=websocket_handler
+ )
+ client = TestClient(app)
+
+ with pytest.deprecated_call():
+ with client.websocket_connect("/", ["graphql-transport-ws"]) as ws:
+ ws.send_json({"type": GraphQLTransportWSHandler.GQL_CONNECTION_INIT})
+ ws.send_json(
+ {
+ "type": GraphQLTransportWSHandler.GQL_SUBSCRIBE,
+ "id": "test1",
+ "payload": {"query": "subscription { ping }"},
+ }
+ )
+ response = ws.receive_json()
+ assert response["type"] == GraphQLTransportWSHandler.GQL_CONNECTION_ACK
+ response = ws.receive_json()
+ assert response["type"] == GraphQLTransportWSHandler.GQL_NEXT
+
+
def test_custom_root_value_function_is_called_with_context_value(schema):
get_root_value = Mock(return_value=True)
app = GraphQL(
@@ -163,7 +229,7 @@ def test_custom_root_value_function_is_called_with_context_value(schema):
)
client = TestClient(app)
client.post("/", json={"query": "{ status }"})
- get_root_value.assert_called_once_with({"test": "TEST-CONTEXT"}, ANY)
+ get_root_value.assert_called_once_with({"test": "TEST-CONTEXT"}, None, None, ANY)
def test_custom_query_parser_is_used_for_http_query(schema):
diff --git a/tests/wsgi/test_configuration.py b/tests/wsgi/test_configuration.py
index 47f8608..ed0a802 100644
--- a/tests/wsgi/test_configuration.py
+++ b/tests/wsgi/test_configuration.py
@@ -76,7 +76,21 @@ def test_custom_root_value_function_is_called_with_context_value(schema):
schema, context_value={"test": "TEST-CONTEXT"}, root_value=get_root_value
)
app.execute_query({}, {"query": "{ status }"})
- get_root_value.assert_called_once_with({"test": "TEST-CONTEXT"}, ANY)
+ get_root_value.assert_called_once_with({"test": "TEST-CONTEXT"}, None, None, ANY)
+
+
+def test_warning_is_raised_if_custom_root_value_function_has_deprecated_signature(
+ schema,
+):
+ def get_root_value(_context, _document):
+ return True
+
+ app = GraphQL(
+ schema, context_value={"test": "TEST-CONTEXT"}, root_value=get_root_value
+ )
+
+ with pytest.deprecated_call():
+ app.execute_query({}, {"query": "{ status }"})
def test_custom_query_parser_is_used(schema):
|
Pass operation name and variables to root value resolver
Split form #843
Callable root value resolver becomes really useful in scenarios like GraphQL proxies, but it should have easy access to operation name and variables dict for that.
Plan is to change root value callable to support those as extra arguments, effectively changing type to that:
```python
RootValue = Union[
Any,
Callable[[Optional[Any], DocumentNode], Any],
Callable[[Optional[Any], Optional[str], Optional[dict], DocumentNode], Any],
]
```
|
0.0
|
bc1e00bc31ccab9e8312872075ffd05043e5a59e
|
[
"tests/asgi/test_configuration.py::test_custom_deprecated_root_value_function_raises_warning_by_query",
"tests/asgi/test_configuration.py::test_custom_deprecated_root_value_function_raises_warning_by_subscription",
"tests/asgi/test_configuration.py::test_custom_deprecated_root_value_function_raises_warning_by_subscription_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_root_value_function_is_called_with_context_value",
"tests/wsgi/test_configuration.py::test_custom_root_value_function_is_called_with_context_value",
"tests/wsgi/test_configuration.py::test_warning_is_raised_if_custom_root_value_function_has_deprecated_signature"
] |
[
"tests/asgi/test_configuration.py::test_custom_context_value_is_passed_to_resolvers",
"tests/asgi/test_configuration.py::test_custom_context_value_function_is_set_and_called_by_app",
"tests/asgi/test_configuration.py::test_custom_context_value_function_result_is_passed_to_resolvers",
"tests/asgi/test_configuration.py::test_async_context_value_function_result_is_awaited_before_passing_to_resolvers",
"tests/asgi/test_configuration.py::test_custom_root_value_is_passed_to_query_resolvers",
"tests/asgi/test_configuration.py::test_custom_root_value_is_passed_to_subscription_resolvers",
"tests/asgi/test_configuration.py::test_custom_root_value_is_passed_to_subscription_resolvers_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_root_value_function_is_called_by_query",
"tests/asgi/test_configuration.py::test_custom_root_value_function_is_called_by_subscription",
"tests/asgi/test_configuration.py::test_custom_root_value_function_is_called_by_subscription_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_query_parser_is_used_for_http_query",
"tests/asgi/test_configuration.py::test_custom_validation_rule_is_called_by_query_validation",
"tests/asgi/test_configuration.py::test_custom_validation_rules_function_is_set_and_called_on_query_execution",
"tests/asgi/test_configuration.py::test_custom_validation_rules_function_is_called_with_context_value",
"tests/asgi/test_configuration.py::test_default_logger_is_used_to_log_error_if_custom_is_not_set",
"tests/asgi/test_configuration.py::test_custom_logger_instance_is_used_to_log_error",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_query_error",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_subscription_source_error",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_subscription_source_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_subscription_resolver_error",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_subscription_resolver_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_query_error",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_syntax_error",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_syntax_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_source_error",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_source_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_resolver_error",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_resolver_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_error_formatter_is_called_with_debug_enabled",
"tests/asgi/test_configuration.py::test_error_formatter_is_called_with_debug_disabled",
"tests/asgi/test_configuration.py::test_extension_from_option_are_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_extensions_function_result_is_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_async_extensions_function_result_is_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_middlewares_are_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_middleware_function_result_is_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_async_middleware_function_result_is_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_handle_connection_init_timeout_handler_executed_graphql_transport_ws",
"tests/wsgi/test_configuration.py::test_custom_context_value_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_is_set_and_called_by_app",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_is_called_with_request_value",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_result_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_root_value_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_root_value_function_is_set_and_called_by_app",
"tests/wsgi/test_configuration.py::test_custom_query_parser_is_used",
"tests/wsgi/test_configuration.py::test_custom_validation_rule_is_called_by_query_validation",
"tests/wsgi/test_configuration.py::test_custom_validation_rules_function_is_set_and_called_on_query_execution",
"tests/wsgi/test_configuration.py::test_custom_validation_rules_function_is_called_with_context_value",
"tests/wsgi/test_configuration.py::test_default_logger_is_used_to_log_error_if_custom_is_not_set",
"tests/wsgi/test_configuration.py::test_custom_logger_is_used_to_log_error",
"tests/wsgi/test_configuration.py::test_custom_logger_instance_is_used_to_log_error",
"tests/wsgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_error",
"tests/wsgi/test_configuration.py::test_error_formatter_is_called_with_debug_enabled_flag",
"tests/wsgi/test_configuration.py::test_error_formatter_is_called_with_debug_disabled_flag",
"tests/wsgi/test_configuration.py::test_extension_from_option_are_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_extensions_function_result_is_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_middlewares_are_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_middleware_function_result_is_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_wsgi_app_supports_sync_dataloader_with_custom_execution_context"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-09 15:35:10+00:00
|
bsd-3-clause
| 3,963 |
|
mirumee__ariadne-993
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57f4b2f..71e21a0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@
- Changed `logger` option to also support `Logger` and `LoggerAdapter` instance in addition to `str` with logger name.
- Added support for `@tag` directive used by Apollo Federation.
- Moved project configuration from `setup.py` to `pyproject.toml`.
+- Changed `context_value` option in ASGI and WSGI applications for callables to take query data as second argument.
- Changed `root_value` option in ASGI and WSGI applications for callables to take operation and and variables in addition to context and parsed query.
- Added `execution_context_class` option to ASGI and WSGI applications.
- Added `query_parser` option to ASGI and WSGI `GraphQL` applications that enables query parsing customization.
diff --git a/ariadne/asgi/handlers/base.py b/ariadne/asgi/handlers/base.py
index acb24c4..57a7bb3 100644
--- a/ariadne/asgi/handlers/base.py
+++ b/ariadne/asgi/handlers/base.py
@@ -70,9 +70,10 @@ class GraphQLHandler(ABC):
async def get_context_for_request(
self,
request: Any,
+ data: dict,
) -> Any:
if callable(self.context_value):
- context = self.context_value(request)
+ context = self.context_value(request, data) # type: ignore
if isawaitable(context):
context = await context
return context
diff --git a/ariadne/asgi/handlers/graphql_transport_ws.py b/ariadne/asgi/handlers/graphql_transport_ws.py
index 0ff3132..6148a8c 100644
--- a/ariadne/asgi/handlers/graphql_transport_ws.py
+++ b/ariadne/asgi/handlers/graphql_transport_ws.py
@@ -181,7 +181,7 @@ class GraphQLTransportWSHandler(GraphQLWebsocketHandler):
validate_data(data)
- context_value = await self.get_context_for_request(websocket)
+ context_value = await self.get_context_for_request(websocket, data)
try:
query_document = parse_query(context_value, self.query_parser, data)
diff --git a/ariadne/asgi/handlers/graphql_ws.py b/ariadne/asgi/handlers/graphql_ws.py
index 0d94ccc..67003e8 100644
--- a/ariadne/asgi/handlers/graphql_ws.py
+++ b/ariadne/asgi/handlers/graphql_ws.py
@@ -110,7 +110,7 @@ class GraphQLWSHandler(GraphQLWebsocketHandler):
operations: Dict[str, Operation],
) -> None:
validate_data(data)
- context_value = await self.get_context_for_request(websocket)
+ context_value = await self.get_context_for_request(websocket, data)
try:
query_document = parse_query(context_value, self.query_parser, data)
diff --git a/ariadne/asgi/handlers/http.py b/ariadne/asgi/handlers/http.py
index 4c533bb..6763349 100644
--- a/ariadne/asgi/handlers/http.py
+++ b/ariadne/asgi/handlers/http.py
@@ -91,7 +91,7 @@ class GraphQLHTTPHandler(GraphQLHttpHandlerBase):
query_document: Optional[DocumentNode] = None,
) -> GraphQLResult:
if context_value is None:
- context_value = await self.get_context_for_request(request)
+ context_value = await self.get_context_for_request(request, data)
extensions = await self.get_extensions_for_request(request, context_value)
middleware = await self.get_middleware_for_request(request, context_value)
diff --git a/ariadne/types.py b/ariadne/types.py
index 74046b9..eea6c0d 100644
--- a/ariadne/types.py
+++ b/ariadne/types.py
@@ -39,7 +39,11 @@ SubscriptionResult = Tuple[
Subscriber = Callable[..., AsyncGenerator]
ErrorFormatter = Callable[[GraphQLError, bool], dict]
-ContextValue = Union[Any, Callable[[Any], Any]]
+ContextValue = Union[
+ Any,
+ Callable[[Any], Any], # TODO: remove in 0.19
+ Callable[[Any, dict], Any],
+]
RootValue = Union[
Any,
Callable[[Optional[Any], DocumentNode], Any], # TODO: remove in 0.19
diff --git a/ariadne/wsgi.py b/ariadne/wsgi.py
index 82bc7c4..74921cd 100644
--- a/ariadne/wsgi.py
+++ b/ariadne/wsgi.py
@@ -206,7 +206,7 @@ class GraphQL:
return combine_multipart_data(operations, files_map, form.files)
def execute_query(self, environ: dict, data: dict) -> GraphQLResult:
- context_value = self.get_context_for_request(environ)
+ context_value = self.get_context_for_request(environ, data)
extensions = self.get_extensions_for_request(environ, context_value)
middleware = self.get_middleware_for_request(environ, context_value)
@@ -227,9 +227,11 @@ class GraphQL:
execution_context_class=self.execution_context_class,
)
- def get_context_for_request(self, environ: dict) -> Optional[ContextValue]:
+ def get_context_for_request(
+ self, environ: dict, data: dict
+ ) -> Optional[ContextValue]:
if callable(self.context_value):
- return self.context_value(environ)
+ return self.context_value(environ, data) # type: ignore
return self.context_value or {"request": environ}
def get_extensions_for_request(
|
mirumee/ariadne
|
408982696eab53c05acf5d9ee38fe03ac2df2fb0
|
diff --git a/tests/asgi/test_configuration.py b/tests/asgi/test_configuration.py
index f7c007d..81dbf5e 100644
--- a/tests/asgi/test_configuration.py
+++ b/tests/asgi/test_configuration.py
@@ -30,7 +30,7 @@ def test_custom_context_value_function_is_set_and_called_by_app(schema):
app = GraphQL(schema, context_value=get_context_value)
client = TestClient(app)
client.post("/", json={"query": "{ status }"})
- get_context_value.assert_called_once()
+ get_context_value.assert_called_once_with(ANY, {"query": "{ status }"})
def test_custom_context_value_function_result_is_passed_to_resolvers(schema):
diff --git a/tests/wsgi/test_configuration.py b/tests/wsgi/test_configuration.py
index ed0a802..75ab0bd 100644
--- a/tests/wsgi/test_configuration.py
+++ b/tests/wsgi/test_configuration.py
@@ -47,7 +47,7 @@ def test_custom_context_value_function_is_called_with_request_value(schema):
app = GraphQL(schema, context_value=get_context_value)
request = {"CONTENT_TYPE": DATA_TYPE_JSON}
app.execute_query(request, {"query": "{ status }"})
- get_context_value.assert_called_once_with(request)
+ get_context_value.assert_called_once_with(request, {"query": "{ status }"})
def test_custom_context_value_function_result_is_passed_to_resolvers(schema):
|
Pass in data to get_context_for_request
That way you can write something like:
```python
async def get_context_for_request(
self,
request: Any,
*, data: Dict[str, Any] = None
) -> Any:
if callable(self.context_value):
context = self.context_value(request)
if isawaitable(context):
context = await context
return context
data = data or {}
query: Optional[str] = data.get("query")
variables: Optional[Dict[str, Any]] = data.get("variables")
operation_name: Optional[str] = data.get("operationName")
return self.context_value or {
"request": request,
"variables": variables,
"operation_name": operation_name,
"query": query,
}
```
that way the tracing extension can access `operation_name`, `variables`, and `query` which is very helpful metadata context.
|
0.0
|
408982696eab53c05acf5d9ee38fe03ac2df2fb0
|
[
"tests/asgi/test_configuration.py::test_custom_context_value_function_is_set_and_called_by_app",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_is_called_with_request_value"
] |
[
"tests/asgi/test_configuration.py::test_custom_context_value_is_passed_to_resolvers",
"tests/asgi/test_configuration.py::test_custom_context_value_function_result_is_passed_to_resolvers",
"tests/asgi/test_configuration.py::test_async_context_value_function_result_is_awaited_before_passing_to_resolvers",
"tests/asgi/test_configuration.py::test_custom_root_value_is_passed_to_query_resolvers",
"tests/asgi/test_configuration.py::test_custom_root_value_is_passed_to_subscription_resolvers",
"tests/asgi/test_configuration.py::test_custom_root_value_is_passed_to_subscription_resolvers_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_root_value_function_is_called_by_query",
"tests/asgi/test_configuration.py::test_custom_deprecated_root_value_function_raises_warning_by_query",
"tests/asgi/test_configuration.py::test_custom_root_value_function_is_called_by_subscription",
"tests/asgi/test_configuration.py::test_custom_deprecated_root_value_function_raises_warning_by_subscription",
"tests/asgi/test_configuration.py::test_custom_root_value_function_is_called_by_subscription_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_deprecated_root_value_function_raises_warning_by_subscription_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_root_value_function_is_called_with_context_value",
"tests/asgi/test_configuration.py::test_custom_query_parser_is_used_for_http_query",
"tests/asgi/test_configuration.py::test_custom_validation_rule_is_called_by_query_validation",
"tests/asgi/test_configuration.py::test_custom_validation_rules_function_is_set_and_called_on_query_execution",
"tests/asgi/test_configuration.py::test_custom_validation_rules_function_is_called_with_context_value",
"tests/asgi/test_configuration.py::test_default_logger_is_used_to_log_error_if_custom_is_not_set",
"tests/asgi/test_configuration.py::test_custom_logger_instance_is_used_to_log_error",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_query_error",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_subscription_source_error",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_subscription_source_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_subscription_resolver_error",
"tests/asgi/test_configuration.py::test_custom_logger_is_used_to_log_subscription_resolver_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_query_error",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_syntax_error",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_syntax_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_source_error",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_source_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_resolver_error",
"tests/asgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_subscription_resolver_error_graphql_transport_ws",
"tests/asgi/test_configuration.py::test_error_formatter_is_called_with_debug_enabled",
"tests/asgi/test_configuration.py::test_error_formatter_is_called_with_debug_disabled",
"tests/asgi/test_configuration.py::test_extension_from_option_are_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_extensions_function_result_is_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_async_extensions_function_result_is_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_middlewares_are_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_middleware_function_result_is_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_async_middleware_function_result_is_passed_to_query_executor",
"tests/asgi/test_configuration.py::test_handle_connection_init_timeout_handler_executed_graphql_transport_ws",
"tests/wsgi/test_configuration.py::test_custom_context_value_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_is_set_and_called_by_app",
"tests/wsgi/test_configuration.py::test_custom_context_value_function_result_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_root_value_is_passed_to_resolvers",
"tests/wsgi/test_configuration.py::test_custom_root_value_function_is_set_and_called_by_app",
"tests/wsgi/test_configuration.py::test_custom_root_value_function_is_called_with_context_value",
"tests/wsgi/test_configuration.py::test_warning_is_raised_if_custom_root_value_function_has_deprecated_signature",
"tests/wsgi/test_configuration.py::test_custom_query_parser_is_used",
"tests/wsgi/test_configuration.py::test_custom_validation_rule_is_called_by_query_validation",
"tests/wsgi/test_configuration.py::test_custom_validation_rules_function_is_set_and_called_on_query_execution",
"tests/wsgi/test_configuration.py::test_custom_validation_rules_function_is_called_with_context_value",
"tests/wsgi/test_configuration.py::test_default_logger_is_used_to_log_error_if_custom_is_not_set",
"tests/wsgi/test_configuration.py::test_custom_logger_is_used_to_log_error",
"tests/wsgi/test_configuration.py::test_custom_logger_instance_is_used_to_log_error",
"tests/wsgi/test_configuration.py::test_custom_error_formatter_is_used_to_format_error",
"tests/wsgi/test_configuration.py::test_error_formatter_is_called_with_debug_enabled_flag",
"tests/wsgi/test_configuration.py::test_error_formatter_is_called_with_debug_disabled_flag",
"tests/wsgi/test_configuration.py::test_extension_from_option_are_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_extensions_function_result_is_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_middlewares_are_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_middleware_function_result_is_passed_to_query_executor",
"tests/wsgi/test_configuration.py::test_wsgi_app_supports_sync_dataloader_with_custom_execution_context"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-13 18:12:21+00:00
|
bsd-3-clause
| 3,964 |
|
mirumee__google-i18n-address-62
|
diff --git a/i18naddress/__init__.py b/i18naddress/__init__.py
index 4ea2bd5..c53c8fc 100644
--- a/i18naddress/__init__.py
+++ b/i18naddress/__init__.py
@@ -28,7 +28,14 @@ def load_validation_data(country_code="all"):
if not VALID_COUNTRY_CODE.match(country_code):
raise ValueError("%r is not a valid country code" % (country_code,))
country_code = country_code.lower()
- path = VALIDATION_DATA_PATH % (country_code,)
+ try:
+ # VALIDATION_DATA_PATH may have '%' symbols
+ # for backwards compatability if VALIDATION_DATA_PATH is imported
+ # by consumers of this package.
+ path = VALIDATION_DATA_PATH % (country_code,)
+ except TypeError:
+ path = os.path.join(VALIDATION_DATA_DIR, "%s.json" % country_code)
+
if not os.path.exists(path):
raise ValueError("%r is not a valid country code" % (country_code,))
with io.open(path, encoding="utf-8") as data:
|
mirumee/google-i18n-address
|
aaa90ee859a5ff445b9cb39a67e12db047db0027
|
diff --git a/tests/test_i18naddress.py b/tests/test_i18naddress.py
index 1179bbf..eceaf08 100644
--- a/tests/test_i18naddress.py
+++ b/tests/test_i18naddress.py
@@ -1,5 +1,6 @@
# coding: utf-8
from __future__ import unicode_literals
+from unittest.mock import patch
import pytest
@@ -158,3 +159,9 @@ def test_locality_types(country, levels):
assert validation_data.country_area_type == levels[0]
assert validation_data.city_type == levels[1]
assert validation_data.city_area_type == levels[2]
+
+@patch('i18naddress.VALIDATION_DATA_PATH', '/home/bug%2Fexample/%s.json')
+def test_validation_path_with_percent_symbol():
+ data = load_validation_data('US')
+ state = data['US/NV']
+ assert state['name'] == 'Nevada'
|
`load_validation_data` throws TypeErrors if site-packages path includes `%` characters
https://github.com/mirumee/google-i18n-address/blob/aaa90ee859a5ff445b9cb39a67e12db047db0027/i18naddress/__init__.py#L31
The above line throws TypeError exceptions if `VALIDATION_DATA_PATH` contains any `%` characters.
```
10:38:05 proj/common/validators.py:28: in validate_postal_code_with_country_code
10:38:05 rules = i18naddress.get_validation_rules({"country_code": country_code})
10:38:05 python-test-env/jira%2FTACO-1947/lib/python3.6/site-packages/i18naddress/__init__.py:206: in get_validation_rules
10:38:05 country_data, database = _load_country_data(country_code)
10:38:05 python-test-env/jira%2FTACO-1947/lib/python3.6/site-packages/i18naddress/__init__.py:193: in _load_country_data
10:38:05 database = load_validation_data("zz")
10:38:05 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
10:38:05
10:38:05 country_code = 'zz'
10:38:05
10:38:05 def load_validation_data(country_code="all"):
10:38:05 if not VALID_COUNTRY_CODE.match(country_code):
10:38:05 raise ValueError("%r is not a valid country code" % (country_code,))
10:38:05 country_code = country_code.lower()
10:38:05 > path = VALIDATION_DATA_PATH % (country_code,)
10:38:05 E TypeError: must be real number, not str
10:38:05
10:38:05 python-test-env/jira%2FTACO-1947/lib/python3.6/site-packages/i18naddress/__init__.py:31: TypeError
```
A common example of this would be a Jenkins pipeline that uses branch name to create the workspace directory. A branch named `bug/exampe123` would result in
```
VALIDATION_DATA_PATH='/home/jenkins/workspace/bug%2Fexample123/lib/python3.6/site-packages/i18naddress/data/%s.json'
```
|
0.0
|
aaa90ee859a5ff445b9cb39a67e12db047db0027
|
[
"tests/test_i18naddress.py::test_validation_path_with_percent_symbol"
] |
[
"tests/test_i18naddress.py::test_invalid_country_code",
"tests/test_i18naddress.py::test_dictionary_access",
"tests/test_i18naddress.py::test_validation_rules_canada",
"tests/test_i18naddress.py::test_validation_india",
"tests/test_i18naddress.py::test_validation_rules_switzerland",
"tests/test_i18naddress.py::test_field_order_poland",
"tests/test_i18naddress.py::test_field_order_china",
"tests/test_i18naddress.py::test_locality_types[CN-levels0]",
"tests/test_i18naddress.py::test_locality_types[JP-levels1]",
"tests/test_i18naddress.py::test_locality_types[KR-levels2]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-08-05 16:57:23+00:00
|
bsd-3-clause
| 3,965 |
|
mirumee__prices-26
|
diff --git a/prices/price.py b/prices/price.py
index ffc15bb..549dfab 100644
--- a/prices/price.py
+++ b/prices/price.py
@@ -14,6 +14,10 @@ class Price(object):
if not isinstance(net, Amount) or not isinstance(gross, Amount):
raise TypeError('Price requires two amounts, got %r, %r' % (
net, gross))
+ if net.currency != gross.currency:
+ raise ValueError(
+ 'Amounts given in different currencies: %r and %r' % (
+ net.currency, gross.currency))
self.net = net
self.gross = gross
diff --git a/setup.py b/setup.py
index 7b0a652..02f7aac 100755
--- a/setup.py
+++ b/setup.py
@@ -18,7 +18,7 @@ setup(
author_email='[email protected]',
description='Python price handling for humans',
license='BSD',
- version='1.0.0-beta',
+ version='1.0.1-beta',
url='https://github.com/mirumee/prices',
packages=['prices'],
install_requires=['babel'],
|
mirumee/prices
|
e56c162aa254f17ab3fa50b718d74e491a90b913
|
diff --git a/tests/test_price.py b/tests/test_price.py
index 9f2f214..2a7465c 100644
--- a/tests/test_price.py
+++ b/tests/test_price.py
@@ -10,6 +10,11 @@ def test_construction():
Price(1, 1)
+def test_construction_different_currencies():
+ with pytest.raises(ValueError):
+ Price(net=Amount(1, 'USD'), gross=Amount(2, 'EUR'))
+
+
def test_addition():
price1 = Price(Amount(10, 'USD'), Amount(15, 'USD'))
price2 = Price(Amount(20, 'USD'), Amount(30, 'USD'))
|
Price can be created with net and gross with different currencies
Right now we allow to create Price with net Amount and gross Amount with different currencies.
`Price(net=Amount('25', 'USD'), gross=Amount('30', 'EUR'))`
This should not be allowed and should rise an exception.
|
0.0
|
e56c162aa254f17ab3fa50b718d74e491a90b913
|
[
"tests/test_price.py::test_construction_different_currencies"
] |
[
"tests/test_price.py::test_construction",
"tests/test_price.py::test_addition",
"tests/test_price.py::test_subtraction",
"tests/test_price.py::test_multiplication",
"tests/test_price.py::test_division",
"tests/test_price.py::test_comparison",
"tests/test_price.py::test_quantize",
"tests/test_price.py::test_currency",
"tests/test_price.py::test_tax",
"tests/test_price.py::test_repr",
"tests/test_price.py::test_sum"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-12-15 10:37:39+00:00
|
bsd-3-clause
| 3,966 |
|
miso-belica__sumy-166
|
diff --git a/sumy/summarizers/sum_basic.py b/sumy/summarizers/sum_basic.py
index 9e8f9ce..c54cf67 100644
--- a/sumy/summarizers/sum_basic.py
+++ b/sumy/summarizers/sum_basic.py
@@ -8,10 +8,9 @@ from ._summarizer import AbstractSummarizer
class SumBasicSummarizer(AbstractSummarizer):
"""
- SumBasic: a frequency-based summarization system that adjusts word frequencies as
+ SumBasic: a frequency-based summarization system that adjusts word frequencies as
sentences are extracted.
Source: http://www.cis.upenn.edu/~nenkova/papers/ipm.pdf
-
"""
_stop_words = frozenset()
@@ -28,12 +27,11 @@ class SumBasicSummarizer(AbstractSummarizer):
ratings = self._compute_ratings(sentences)
return self._get_best_sentences(document.sentences, sentences_count, ratings)
- @staticmethod
- def _get_all_words_in_doc(sentences):
- return [w for s in sentences for w in s.words]
+ def _get_all_words_in_doc(self, sentences):
+ return self._stem_words([w for s in sentences for w in s.words])
def _get_content_words_in_sentence(self, sentence):
- normalized_words = self._normalize_words(sentence.words)
+ normalized_words = self._normalize_words(sentence.words)
normalized_content_words = self._filter_out_stop_words(normalized_words)
stemmed_normalized_content_words = self._stem_words(normalized_content_words)
return stemmed_normalized_content_words
@@ -77,7 +75,7 @@ class SumBasicSummarizer(AbstractSummarizer):
word_freq_sum = sum([word_freq_in_doc[w] for w in content_words_in_sentence])
word_freq_avg = word_freq_sum / content_words_count
return word_freq_avg
- else:
+ else:
return 0
@staticmethod
@@ -100,13 +98,13 @@ class SumBasicSummarizer(AbstractSummarizer):
def _compute_ratings(self, sentences):
word_freq = self._compute_tf(sentences)
ratings = {}
-
+
# make it a list so that it can be modified
sentences_list = list(sentences)
# get all content words once for efficiency
sentences_as_words = [self._get_content_words_in_sentence(s) for s in sentences]
-
+
# Removes one sentence per iteration by adding to summary
while len(sentences_list) > 0:
best_sentence_index = self._find_index_of_best_sentence(word_freq, sentences_as_words)
|
miso-belica/sumy
|
87fc584b3b984732ba63d902e0701dd883749899
|
diff --git a/tests/test_summarizers/test_sum_basic.py b/tests/test_summarizers/test_sum_basic.py
index 4d70612..befc0c7 100644
--- a/tests/test_summarizers/test_sum_basic.py
+++ b/tests/test_summarizers/test_sum_basic.py
@@ -30,7 +30,6 @@ def test_empty_document():
def test_single_sentence():
-
s = Sentence("I am one slightly longer sentence.", Tokenizer("english"))
document = build_document([s])
summarizer = _build_summarizer(EMPTY_STOP_WORDS)
@@ -39,6 +38,15 @@ def test_single_sentence():
assert len(returned) == 1
+def test_stemmer_does_not_cause_crash():
+ """https://github.com/miso-belica/sumy/issues/165"""
+ document = build_document([Sentence("Was ist das längste deutsche Wort?", Tokenizer("german"))])
+ summarizer = _build_summarizer(EMPTY_STOP_WORDS, Stemmer("german"))
+
+ returned = summarizer(document, 10)
+ assert len(returned) == 1
+
+
def test_normalize_words():
summarizer = _build_summarizer(EMPTY_STOP_WORDS)
sentence = "This iS A test 2 CHECk normalization."
|
`KeyError` in `SumBasicSummarizer`
Hey, first of all, thanks for the great library!
I just encountered a bug with the `SumBasicSummarizer`, where it seems that the method looks up the document frequency of a stemmed word. However, the actual `word_freq_in_doc` dictionary only stores the frequencies for **unstemmed** words.
In particular, I believe that the culprit is the different normalization of content words between [`_get_content_words_in_sentence()`](https://github.com/miso-belica/sumy/blob/main/sumy/summarizers/sum_basic.py#L35-L39) versus the normalization in [`_get_all_content_words_in_doc()`](https://github.com/miso-belica/sumy/blob/main/sumy/summarizers/sum_basic.py#L57-L61). In particular, the former method performs stemming, whereas the latter does not.
I would have proposed a PR myself, but I don't know which is the "more correct" fix (IMO, consistent stemming should be the way to go?).
FWIW, I used this with German texts, although capitalization etc. seems to be no issue here.
|
0.0
|
87fc584b3b984732ba63d902e0701dd883749899
|
[
"tests/test_summarizers/test_sum_basic.py::test_stemmer_does_not_cause_crash"
] |
[
"tests/test_summarizers/test_sum_basic.py::test_empty_document",
"tests/test_summarizers/test_sum_basic.py::test_single_sentence",
"tests/test_summarizers/test_sum_basic.py::test_normalize_words",
"tests/test_summarizers/test_sum_basic.py::test_stemmer",
"tests/test_summarizers/test_sum_basic.py::test_filter_out_stop_words",
"tests/test_summarizers/test_sum_basic.py::test_compute_word_freq",
"tests/test_summarizers/test_sum_basic.py::test_get_all_content_words_in_doc",
"tests/test_summarizers/test_sum_basic.py::test_compute_tf",
"tests/test_summarizers/test_sum_basic.py::test_compute_average_probability_of_words",
"tests/test_summarizers/test_sum_basic.py::test_compute_ratings"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-09 22:26:18+00:00
|
apache-2.0
| 3,967 |
|
missionpinball__mpf-1564
|
diff --git a/mpf/config_spec.yaml b/mpf/config_spec.yaml
index 4f90ba675..dce39ea73 100644
--- a/mpf/config_spec.yaml
+++ b/mpf/config_spec.yaml
@@ -835,6 +835,7 @@ logic_blocks_common:
start_enabled: single|bool|None
events_when_complete: list|event_posted|None
events_when_hit: list|event_posted|None
+ logic_block_timeout: single|ms|0
accruals:
__valid_in__: machine, mode
__type__: device
diff --git a/mpf/devices/logic_blocks.py b/mpf/devices/logic_blocks.py
index 54c88591b..5a9cf2747 100644
--- a/mpf/devices/logic_blocks.py
+++ b/mpf/devices/logic_blocks.py
@@ -32,11 +32,12 @@ class LogicBlock(SystemWideDevice, ModeDevice):
"""Parent class for each of the logic block classes."""
- __slots__ = ["_state", "_start_enabled", "player_state_variable"]
+ __slots__ = ["delay", "_state", "_start_enabled", "player_state_variable"]
def __init__(self, machine: MachineController, name: str) -> None:
"""Initialize logic block."""
super().__init__(machine, name)
+ self.delay = DelayManager(self.machine)
self._state = None # type: Optional[LogicBlockState]
self._start_enabled = None # type: Optional[bool]
@@ -189,6 +190,7 @@ class LogicBlock(SystemWideDevice, ModeDevice):
self.debug_log("Enabling")
self.enabled = True
self.post_update_event()
+ self._logic_block_timer_start()
def _post_hit_events(self, **kwargs):
self.post_update_event()
@@ -221,6 +223,7 @@ class LogicBlock(SystemWideDevice, ModeDevice):
self.debug_log("Disabling")
self.enabled = False
self.post_update_event()
+ self.delay.remove("timeout")
@event_handler(4)
def event_reset(self, **kwargs):
@@ -238,6 +241,26 @@ class LogicBlock(SystemWideDevice, ModeDevice):
self.value = self.get_start_value()
self.debug_log("Resetting")
self.post_update_event()
+ self._logic_block_timer_start()
+
+ def _logic_block_timer_start(self):
+ if self.config['logic_block_timeout']:
+ self.debug_log("Setting up a logic block timer for %sms",
+ self.config['logic_block_timeout'])
+
+ self.delay.reset(name="timeout",
+ ms=self.config['logic_block_timeout'],
+ callback=self._logic_block_timeout)
+
+ def _logic_block_timeout(self):
+ """Reset the progress towards completion of this logic block when timer expires.
+
+ Automatically called when one of the logic_block_timer_complete
+ events is called.
+ """
+ self.info_log("Logic Block timeouted")
+ self.machine.events.post("{}_timeout".format(self.name))
+ self.reset()
@event_handler(5)
def event_restart(self, **kwargs):
@@ -268,6 +291,7 @@ class LogicBlock(SystemWideDevice, ModeDevice):
# otherwise mark as completed
self.completed = True
+ self.delay.remove("timeout")
self.debug_log("Complete")
if self.config['events_when_complete']:
@@ -313,7 +337,6 @@ class Counter(LogicBlock):
def __init__(self, machine: MachineController, name: str) -> None:
"""Initialise counter."""
super().__init__(machine, name)
- self.delay = DelayManager(self.machine)
self.ignore_hits = False
self.hit_value = -1
|
missionpinball/mpf
|
5903fba37c6ab4fbfcfc3e0e9523d0e8dc80cb22
|
diff --git a/mpf/tests/machine_files/logic_blocks/config/config.yaml b/mpf/tests/machine_files/logic_blocks/config/config.yaml
index 6870cdfc8..cd75e1c12 100644
--- a/mpf/tests/machine_files/logic_blocks/config/config.yaml
+++ b/mpf/tests/machine_files/logic_blocks/config/config.yaml
@@ -59,6 +59,19 @@ accruals:
enable_events: accrual10_enable
disable_events: accrual10_disable
reset_events: accrual10_reset
+ accrual7:
+ events:
+ - accrual7_step1
+ - accrual7_step2
+ - accrual7_step3
+ events_when_complete: accrual7_complete
+ events_when_hit: accrual7_hit
+ reset_on_complete: True
+ disable_on_complete: False
+ enable_events: accrual7_enable
+ disable_events: accrual7_disable
+ reset_events: accrual7_reset
+ logic_block_timeout: 50
counters:
counter1:
count_events: counter1_count
@@ -91,6 +104,16 @@ counters:
reset_events: counter4_reset
counter5:
count_events: counter5_count
+ counter9:
+ count_events: counter9_count
+ starting_count: 5
+ count_complete_value: 0
+ direction: down
+ enable_events: counter9_enable
+ disable_events: counter9_disable
+ restart_events: counter9_restart
+ reset_events: counter9_reset
+ logic_block_timeout: 50
sequences:
sequence1:
events:
@@ -101,6 +124,16 @@ sequences:
enable_events: sequence1_enable
disable_events: sequence1_disable
reset_events: sequence1_reset
+ sequence2:
+ events:
+ - sequence2_step1a, sequence2_step1b
+ - sequence2_step2a, sequence2_step2b
+ - sequence2_step3a, sequence2_step3b
+ events_when_complete: sequence2_complete
+ enable_events: sequence2_enable
+ disable_events: sequence2_disable
+ reset_events: sequence2_reset
+ logic_block_timeout: 50
# logic blocks in mode1
modes:
diff --git a/mpf/tests/test_LogicBlocks.py b/mpf/tests/test_LogicBlocks.py
index ac86c4b43..29490a6dd 100644
--- a/mpf/tests/test_LogicBlocks.py
+++ b/mpf/tests/test_LogicBlocks.py
@@ -758,3 +758,105 @@ class TestLogicBlocks(MpfFakeGameTestCase):
self.post_event("counter5_count")
self.assertEqual(3, self.machine.counters["counter5"].value)
+
+ def test_counter_delay_timeout(self):
+ self.start_game()
+ self.mock_event("logicblock_counter9_complete")
+ self.mock_event("logicblock_counter9_hit")
+
+ self.post_event("counter9_enable")
+ for i in range(4):
+ self.post_event("counter9_count")
+ self.advance_time_and_run(.01)
+ self.assertEqual(0, self._events["logicblock_counter9_complete"])
+
+ # post final event to complete
+ self.post_event("counter9_count")
+ self.assertEqual(1, self._events["logicblock_counter9_complete"])
+ self.assertEqual(5, self._events["logicblock_counter9_hit"])
+
+ #restart (reset and enable)
+ self.post_event("counter9_restart")
+
+ # 10 more hits with delay causing timeout
+ for i in range(10):
+ self.post_event("counter9_count")
+ self.advance_time_and_run(1)
+ self.assertEqual(1, self._events["logicblock_counter9_complete"])
+ self.assertEqual(15, self._events["logicblock_counter9_hit"])
+
+ def test_sequence_delay_timeout(self):
+ self.start_game()
+ self.mock_event("sequence2_complete")
+ self.mock_event("logicblock_sequence2_hit")
+
+ self.post_event("sequence2_enable")
+
+ # no timer reset
+ self.post_event("sequence2_step1a")
+ self.post_event("sequence2_step2a")
+ self.post_event("sequence2_step3a")
+ self.assertEqual(1, self._events["sequence2_complete"])
+ self.assertEqual(3, self._events["logicblock_sequence2_hit"])
+
+ # enable and reset
+ self.post_event("sequence2_enable")
+ self.post_event("sequence2_reset")
+
+ # timer expired
+ self.post_event("sequence2_step1a")
+ self.assertEqual(4, self._events["logicblock_sequence2_hit"])
+ self.advance_time_and_run(1)
+ self.post_event("sequence2_step2a")
+ self.post_event("sequence2_step3a")
+ self.assertEqual(1, self._events["sequence2_complete"])
+ self.assertEqual(4, self._events["logicblock_sequence2_hit"])
+
+ #time expired and restart
+ self.post_event("sequence2_step1a")
+ self.advance_time_and_run(.1)
+ self.post_event("sequence2_step1a")
+ self.post_event("sequence2_step2a")
+ self.advance_time_and_run(.01)
+ self.post_event("sequence2_step3a")
+ self.assertEqual(2, self._events["sequence2_complete"])
+ self.assertEqual(8, self._events["logicblock_sequence2_hit"])
+
+ def test_accruals_delay_timeout(self):
+ self.start_game()
+ self.mock_event("accrual7_complete")
+ self.mock_event("accrual7_hit")
+
+ # enable accrual
+ self.post_event("accrual7_enable")
+
+ # no timer reset
+ self.post_event("accrual7_step1")
+ self.post_event("accrual7_step2")
+ self.post_event("accrual7_step3")
+ self.assertEqual(1, self._events["accrual7_complete"])
+ self.assertEqual(3, self._events["accrual7_hit"])
+
+ # time advance after each step but under timeout
+ self.post_event("accrual7_step1")
+ self.advance_time_and_run(.01)
+ self.post_event("accrual7_step2")
+ self.advance_time_and_run(.01)
+ self.post_event("accrual7_step3")
+ self.assertEqual(2, self._events["accrual7_complete"])
+ self.assertEqual(6, self._events["accrual7_hit"])
+
+ # timer advance after each step over timeout
+ self.post_event("accrual7_step1")
+ self.advance_time_and_run(1)
+ self.post_event("accrual7_step2")
+ self.advance_time_and_run(1)
+ self.post_event("accrual7_step3")
+ self.assertEqual(2, self._events["accrual7_complete"])
+ self.assertEqual(9, self._events["accrual7_hit"])
+
+ #final two steps without additional time passed
+ self.post_event("accrual7_step1")
+ self.post_event("accrual7_step2")
+ self.assertEqual(3, self._events["accrual7_complete"])
+ self.assertEqual(11, self._events["accrual7_hit"])
\ No newline at end of file
|
Add timeouts to logic blocks
Add a timeout to logic blocks such as counters, sequences and sequels. It should reset the block if it expires. This should only cover this very basic usecase and everything advanced can use an external timer.
|
0.0
|
5903fba37c6ab4fbfcfc3e0e9523d0e8dc80cb22
|
[
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_accrual_random_advance",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_accruals_delay_timeout",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_accruals_simple",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_count_without_end",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_counter_control_events",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_counter_delay_timeout",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_counter_hit_window",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_counter_in_mode",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_counter_persist",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_counter_simple_down",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_counter_template",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_counter_with_lights",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_logic_block_outside_game",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_mode_selection_with_counters",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_no_reset_and_no_disable_on_complete",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_no_reset_on_complete",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_player_change",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_reset_and_no_disable_on_complete",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_sequence_delay_timeout",
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_sequence_simple"
] |
[
"mpf/tests/test_LogicBlocks.py::TestLogicBlocks::test_subscription_on_counter_values"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-21 16:56:51+00:00
|
mit
| 3,968 |
|
mit-ll-responsible-ai__hydra-zen-367
|
diff --git a/docs/source/changes.rst b/docs/source/changes.rst
index ac757753..c928b5b1 100644
--- a/docs/source/changes.rst
+++ b/docs/source/changes.rst
@@ -134,6 +134,7 @@ New Features
- Adds `hyda_zen.store`, which is a pre-initialized instance of :class:`~hydra_zen.ZenStore` (see :pull:`331`)
- The option `hydra_convert='object'` is now supported by all of hydra-zen's config-creation functions. So that an instantiated structured config can be converted to an instance of its backing dataclass. This feature was added by `Hydra 1.3.0 <https://github.com/facebookresearch/hydra/issues/1719>`_.
- Adds auto-config support for `torch.optim.optimizer.required` so that the common pattern `builds(<torch_optimizer_type>, populate_full_signature=True, zen_partial=True)` works and exposes `lr` as a required configurable parameter. Thanks to @addisonklinke for requesting this in :issue:`257`.
+- :ref:`builds([...], zen_wrapper=...) <zen-wrapper>` can now accept a partial'd function as a wrapper.
Improvements
------------
diff --git a/src/hydra_zen/structured_configs/_implementations.py b/src/hydra_zen/structured_configs/_implementations.py
index cc7bffe2..5645210b 100644
--- a/src/hydra_zen/structured_configs/_implementations.py
+++ b/src/hydra_zen/structured_configs/_implementations.py
@@ -1501,6 +1501,9 @@ def builds(
continue
# We are intentionally keeping each condition branched
# so that test-coverage will be checked for each one
+ if isinstance(wrapper, functools.partial):
+ wrapper = ZEN_VALUE_CONVERSION[functools.partial](wrapper)
+
if is_builds(wrapper):
# If Hydra's locate function starts supporting importing literals
# – or if we decide to ship our own locate function –
|
mit-ll-responsible-ai/hydra-zen
|
9807b1ba603c6fa74d9756dabf755457007e0048
|
diff --git a/tests/test_zen_processing/test_zen_wrappers.py b/tests/test_zen_processing/test_zen_wrappers.py
index 45028f83..088ba092 100644
--- a/tests/test_zen_processing/test_zen_wrappers.py
+++ b/tests/test_zen_processing/test_zen_wrappers.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: MIT
import string
import warnings
+from functools import partial
from typing import Any, Callable, Dict, List, TypeVar, Union
import hypothesis.strategies as st
@@ -299,3 +300,19 @@ def test_bad_relative_interp_warns(wrappers, expected_match):
def test_interp_doesnt_warn(wrappers):
with warnings.catch_warnings():
builds(dict, zen_wrappers=wrappers, zen_meta=dict(s=1))
+
+
+def pmy_wrapper(func, repeat):
+ def w(*a, **k):
+ return [func(*a, **k)] * repeat
+
+ return w
+
+
+def ptarget():
+ return "moo"
+
+
+def test_partial_zen_wrapper():
+ out = instantiate(builds(ptarget, zen_wrappers=partial(pmy_wrapper, repeat=3)))
+ assert out == ["moo"] * 3
|
`zen_wrapper` should support partial'd wrappers
This should work:
```python
builds(something, zen_wrappers=partial(my_wrapper, param=100))
```
Currently, one would have to write:
```python
builds(something, zen_wrappers=builds(my_wrapper, param=100, zen_partial=True))
```
we just need to check if a wrapper is an instance of `partial` and auto-apply `hydra_zen.just` if so.
|
0.0
|
9807b1ba603c6fa74d9756dabf755457007e0048
|
[
"tests/test_zen_processing/test_zen_wrappers.py::test_partial_zen_wrapper"
] |
[
"tests/test_zen_processing/test_zen_wrappers.py::test_zen_wrappers_expected_behavior",
"tests/test_zen_processing/test_zen_wrappers.py::test_wrapper_for_hydrated_dataclass",
"tests/test_zen_processing/test_zen_wrappers.py::test_zen_wrappers_validation_during_builds[1]",
"tests/test_zen_processing/test_zen_wrappers.py::test_zen_wrappers_validation_during_builds[bad_wrapper1]",
"tests/test_zen_processing/test_zen_wrappers.py::test_zen_wrappers_validation_during_builds[bad_wrapper2]",
"tests/test_zen_processing/test_zen_wrappers.py::test_zen_wrappers_validation_during_instantiation[NotAWrapper]",
"tests/test_zen_processing/test_zen_wrappers.py::test_zen_wrappers_validation_during_instantiation[bad_wrapper1]",
"tests/test_zen_processing/test_zen_wrappers.py::test_zen_wrappers_validation_during_instantiation[bad_wrapper2]",
"tests/test_zen_processing/test_zen_wrappers.py::test_zen_wrappers_validation_during_instantiation[bad_wrapper3]",
"tests/test_zen_processing/test_zen_wrappers.py::test_unresolved_interpolated_value_gets_caught[${unresolved}]",
"tests/test_zen_processing/test_zen_wrappers.py::test_unresolved_interpolated_value_gets_caught[bad_wrapper1]",
"tests/test_zen_processing/test_zen_wrappers.py::test_wrapper_via_builds_with_recusive_False",
"tests/test_zen_processing/test_zen_wrappers.py::test_bad_relative_interp_warns[${..s}-to",
"tests/test_zen_processing/test_zen_wrappers.py::test_bad_relative_interp_warns[${...s}-to",
"tests/test_zen_processing/test_zen_wrappers.py::test_bad_relative_interp_warns[wrappers2-to",
"tests/test_zen_processing/test_zen_wrappers.py::test_bad_relative_interp_warns[wrappers3-to",
"tests/test_zen_processing/test_zen_wrappers.py::test_bad_relative_interp_warns[wrappers4-to",
"tests/test_zen_processing/test_zen_wrappers.py::test_interp_doesnt_warn[${s}]",
"tests/test_zen_processing/test_zen_wrappers.py::test_interp_doesnt_warn[${.s}]",
"tests/test_zen_processing/test_zen_wrappers.py::test_interp_doesnt_warn[wrappers2]",
"tests/test_zen_processing/test_zen_wrappers.py::test_interp_doesnt_warn[wrappers3]",
"tests/test_zen_processing/test_zen_wrappers.py::test_interp_doesnt_warn[wrappers4]"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-30 22:51:31+00:00
|
mit
| 3,969 |
|
mit-ll-responsible-ai__hydra-zen-401
|
diff --git a/src/hydra_zen/wrapper/_implementations.py b/src/hydra_zen/wrapper/_implementations.py
index 55261530..af7a4559 100644
--- a/src/hydra_zen/wrapper/_implementations.py
+++ b/src/hydra_zen/wrapper/_implementations.py
@@ -30,6 +30,7 @@ from typing import (
)
import hydra
+from hydra.conf import HydraConf
from hydra.core.config_store import ConfigStore
from hydra.utils import instantiate
from omegaconf import DictConfig, ListConfig, OmegaConf
@@ -796,6 +797,10 @@ def default_to_config(
"""
if is_dataclass(target):
if isinstance(target, type):
+ if issubclass(target, HydraConf):
+ # don't auto-config HydraConf
+ return target
+
if not kw and get_obj_path(target).startswith("types."):
# handles dataclasses returned by make_config()
return target
@@ -909,6 +914,28 @@ class ZenStore:
deferred_hydra_store=True,
)
+ Notes
+ -----
+ Special support is provided for overriding Hydra's configuration; the name and
+ group of the store entry is inferred to be 'config' and 'hydra', respectively,
+ when an instance/subclass of `HydraConf` is being stored. E.g., specifying
+
+ .. code-block:: python
+
+ from hydra.conf import HydraConf, JobConf
+ from hydra_zen import store
+
+ store(HydraConf(job=JobConf(chdir=True)))
+
+ is equivalent to writing the following manually
+
+ .. code-block:: python
+
+ store(HydraConf(job=JobConf(chdir=True)), name="config", group="hydra", provider="hydra_zen")
+
+ Additionally, overwriting the store entry for `HydraConf` will not raise an error
+ even if `ZenStore(overwrite_ok=False)` is specified.
+
Examples
--------
>>> from hydra_zen import to_yaml, store, ZenStore
@@ -1005,6 +1032,19 @@ class ZenStore:
... def func(a: int, b: int):
... return a - b
+ Each application of `@store` utilizes the store's auto-config capability
+ to create and store a config inline. I.e. the above snippet is equivalent to
+
+ >>> from hydra_zen import builds
+ >>>
+ >>> store(builds(func, a=1, b=22), name="func1")
+ >>> store(builds(func, a=-10,
+ ... populate_full_signature=True
+ ... ),
+ ... name="func2",
+ ... )
+
+
>>> func(10, 3) # the decorated function is left unchanged
7
>>> pyaml(store[None, "func1"])
@@ -1287,6 +1327,20 @@ class ZenStore:
package = kw.get("package", self._defaults["package"])
provider = kw.get("provider", self._defaults["provider"])
+ if (
+ isinstance(__target, HydraConf)
+ or isinstance(__target, type)
+ and issubclass(__target, HydraConf)
+ ):
+ # User is re-configuring Hydra's config; we provide "smart" defaults
+ # for the entry's name, group, and package
+ if "name" not in kw and "group" not in kw: # pragma: no branch
+ # only apply when neither name nor group are specified
+ name = "config"
+ group = "hydra"
+ if "provider" not in kw: # pragma: no branch
+ provider = "hydra_zen"
+
_name: NodeName = name(__target) if callable(name) else name
if not isinstance(_name, str):
raise TypeError(f"`name` must be a string, got {_name}")
@@ -1535,19 +1589,30 @@ class ZenStore:
>>> store2.add_to_hydra_store(overwrite_ok=True) # successfully overwrites entry
"""
-
+ _store = ConfigStore.instance().store
while self._queue:
entry = _resolve_node(self._queue.popleft(), copy=False)
if (
- overwrite_ok is False
- or (overwrite_ok is None and not self._overwrite_ok)
- ) and self._exists_in_hydra_store(name=entry["name"], group=entry["group"]):
+ (
+ overwrite_ok is False
+ or (overwrite_ok is None and not self._overwrite_ok)
+ )
+ and self._exists_in_hydra_store(
+ name=entry["name"], group=entry["group"]
+ )
+ # It is okay if we are overwriting Hydra's default store
+ and not (
+ (entry["name"], entry["group"]) == ("config", "hydra")
+ and ConfigStore.instance().repo["hydra"]["config.yaml"].provider
+ == "hydra"
+ )
+ ):
raise ValueError(
f"(name={entry['name']} group={entry['group']}): "
f"Hydra config store entry already exists. Specify "
f"`overwrite_ok=True` to enable replacing config store entries"
)
- ConfigStore.instance().store(**entry)
+ _store(**entry)
def _exists_in_hydra_store(
self,
|
mit-ll-responsible-ai/hydra-zen
|
8a6d5bbb344dcf1610f87942c93a65b725e0f7ec
|
diff --git a/tests/example_app/change_hydra_config.py b/tests/example_app/change_hydra_config.py
new file mode 100644
index 00000000..627ed03a
--- /dev/null
+++ b/tests/example_app/change_hydra_config.py
@@ -0,0 +1,25 @@
+# Copyright (c) 2023 Massachusetts Institute of Technology
+# SPDX-License-Identifier: MIT
+
+from datetime import datetime
+
+from hydra.conf import HydraConf, JobConf
+
+from hydra_zen import store, zen
+
+store(HydraConf(job=JobConf(chdir=True)))
+
+
+@store
+def task():
+ # Used to test that configuring Hydra to change working dir to time-stamped
+ # output dir works as-expected
+ from pathlib import Path
+
+ path = Path.cwd()
+ assert path.parent.name == datetime.today().strftime("%Y-%m-%d")
+
+
+if __name__ == "__main__":
+ store.add_to_hydra_store()
+ zen(task).hydra_main(config_name="task", config_path=None)
diff --git a/tests/test_signature_parsing.py b/tests/test_signature_parsing.py
index 8478e5b1..b46a9b1a 100644
--- a/tests/test_signature_parsing.py
+++ b/tests/test_signature_parsing.py
@@ -325,9 +325,9 @@ def expects_int(x: int) -> int:
@pytest.mark.parametrize(
"builds_as_default",
[
- builds(returns_int), # type
- builds(returns_int)(), # instance
- ],
+ builds(returns_int),
+ builds(returns_int)(),
+ ], # type # instance
)
@pytest.mark.parametrize("hydra_recursive", [True, None])
def test_setting_default_with_builds_widens_type(builds_as_default, hydra_recursive):
diff --git a/tests/test_store.py b/tests/test_store.py
index 62088f9a..699788a4 100644
--- a/tests/test_store.py
+++ b/tests/test_store.py
@@ -1,6 +1,8 @@
# Copyright (c) 2023 Massachusetts Institute of Technology
# SPDX-License-Identifier: MIT
+import os
import re
+import sys
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass
@@ -9,6 +11,7 @@ from typing import Any, Callable, Hashable, Optional
import hypothesis.strategies as st
import pytest
+from hydra.conf import HydraConf
from hydra.core.config_store import ConfigStore
from hypothesis import assume, given, note, settings
from omegaconf import DictConfig, ListConfig
@@ -21,7 +24,7 @@ from hydra_zen import (
make_config,
store as default_store,
)
-from hydra_zen._compatibility import HYDRA_SUPPORTS_LIST_INSTANTIATION
+from hydra_zen._compatibility import HYDRA_SUPPORTS_LIST_INSTANTIATION, HYDRA_VERSION
from tests.custom_strategies import new_stores, store_entries
cs = ConfigStore().instance()
@@ -724,3 +727,65 @@ def test_entry_access_cannot_mutate_store(store: ZenStore, getter):
entry["name"] = 2222
new_entries = tuple(d.copy() for d in store)
assert all(e in new_entries for e in entries)
+
+
+class CustomHydraConf(HydraConf):
+ ...
+
+
[email protected]("conf", [CustomHydraConf, HydraConf()])
[email protected]("deferred", [True, False])
[email protected]("clean_store")
+def test_auto_support_for_HydraConf(conf: HydraConf, deferred: bool):
+ with clean_store():
+ st1 = ZenStore(deferred_hydra_store=deferred)
+ st2 = ZenStore(deferred_hydra_store=True)
+ st1(conf)
+ st1.add_to_hydra_store()
+ assert st1["hydra", "config"] is conf
+
+ with pytest.raises(
+ ValueError,
+ match=re.escape(r"(name=config group=hydra):"),
+ ):
+ # Attempting to overwrite HydraConf within the same
+ # store should fail.
+ st1(conf)
+
+ st2(conf)
+ with pytest.raises(ValueError):
+ st2.add_to_hydra_store()
+
+
[email protected](
+ sys.platform.startswith("win") and bool(os.environ.get("CI")),
+ reason="Things are weird on GitHub Actions and Windows",
+)
[email protected](
+ HYDRA_VERSION < (1, 2, 0),
+ reason="HydraConf(job=Job(chdir=...)) introduced in Hydra 1.2.0",
+)
[email protected](
+ "inp",
+ [
+ None,
+ pytest.param(
+ "hydra.job.chdir=False",
+ marks=pytest.mark.xfail(
+ reason="Hydra should not change directory in this case"
+ ),
+ ),
+ ],
+)
[email protected]("clean_store")
[email protected]("cleandir")
+def test_configure_hydra_chdir(inp: str):
+ import subprocess
+ from pathlib import Path
+
+ path = (Path(__file__).parent / "example_app" / "change_hydra_config.py").absolute()
+
+ cli = ["python", path]
+ if inp:
+ cli.append(inp)
+ subprocess.run(cli).check_returncode()
|
Specialized support for `HydraConf` in `ZenStore`?
Inspired by #394 , it might be nice for `store`/`ZenStore` to have specialized support for instances/subclasses of `HydraConf` so that
```python
store(HydraConf(job=JobConf(chdir=True)))
```
is equivalent to the long-form
```python
store(HydraConf(job=JobConf(chdir=True)), name="config", group="hydra", provider="hydra_zen")
```
i.e. we auto-populate the name/group/provider to be the obvious entries if the user doesn't specify it.
Furthermore, we can special case `store.add_to_hydra_store()` to automatically overwrite the default Hydra entry (but only if it is the entry provided by Hydra itself) since this is the obvious desired behavior if the user is storing their own `HydraConf`.
This would almost certainly be the only special case we would want to specify for `store`. There are some tradeoffs here between convenience and explicitness, and perhaps this leans towards making things a bit too magical for users. It is worth discussing the pros and cons.
|
0.0
|
8a6d5bbb344dcf1610f87942c93a65b725e0f7ec
|
[
"tests/test_signature_parsing.py::test_user_specified_value_overrides_default[False]",
"tests/test_signature_parsing.py::test_user_specified_value_overrides_default[True]",
"tests/test_signature_parsing.py::test_builds_signature_shuffling_takes_least_path",
"tests/test_signature_parsing.py::test_builds_with_full_sig_mirrors_target_sig[None-False]",
"tests/test_signature_parsing.py::test_builds_with_full_sig_mirrors_target_sig[None-True]",
"tests/test_signature_parsing.py::test_builds_with_full_sig_mirrors_target_sig[False-False]",
"tests/test_signature_parsing.py::test_builds_with_full_sig_mirrors_target_sig[False-True]",
"tests/test_signature_parsing.py::test_builds_with_full_sig_mirrors_target_sig[True-False]",
"tests/test_signature_parsing.py::test_builds_with_full_sig_mirrors_target_sig[True-True]",
"tests/test_signature_parsing.py::test_builds_partial_with_full_sig_excludes_non_specified_params[a_func]",
"tests/test_signature_parsing.py::test_builds_partial_with_full_sig_excludes_non_specified_params[AClass]",
"tests/test_signature_parsing.py::test_builds_partial_with_full_sig_excludes_non_specified_params[a_class_method]",
"tests/test_signature_parsing.py::test_builds_partial_with_full_sig_excludes_non_specified_params[AMetaClass]",
"tests/test_signature_parsing.py::test_sig_with_unresolved_fwd_ref[f_with_fwd_ref]",
"tests/test_signature_parsing.py::test_sig_with_unresolved_fwd_ref[A_w_fwd_ref]",
"tests/test_signature_parsing.py::test_setting_default_with_builds_widens_type[True-Builds_returns_int]",
"tests/test_signature_parsing.py::test_setting_default_with_builds_widens_type[True-builds_as_default1]",
"tests/test_signature_parsing.py::test_setting_default_with_builds_widens_type[None-Builds_returns_int]",
"tests/test_signature_parsing.py::test_setting_default_with_builds_widens_type[None-builds_as_default1]",
"tests/test_signature_parsing.py::test_builds_doesnt_widen_dataclass_type_annotation[<lambda>0-1]",
"tests/test_signature_parsing.py::test_builds_doesnt_widen_dataclass_type_annotation[<lambda>0-bad_value1]",
"tests/test_signature_parsing.py::test_builds_doesnt_widen_dataclass_type_annotation[<lambda>1-1]",
"tests/test_signature_parsing.py::test_builds_doesnt_widen_dataclass_type_annotation[<lambda>1-bad_value1]",
"tests/test_signature_parsing.py::test_dataclass_type_annotation_with_subclass_default[<lambda>0]",
"tests/test_signature_parsing.py::test_dataclass_type_annotation_with_subclass_default[<lambda>1]",
"tests/test_signature_parsing.py::test_builds_widens_non_dataclass_type_with_target",
"tests/test_signature_parsing.py::test_type_widening_with_internal_conversion_to_Builds",
"tests/test_signature_parsing.py::test_type_widening_for_interpolated_field_is_needed",
"tests/test_signature_parsing.py::test_type_widening_for_interpolated_field",
"tests/test_signature_parsing.py::test_type_widening_for_interpolated_field_regression_example",
"tests/test_signature_parsing.py::test_pop_full_sig_is_always_identical_to_manually_specifying_sig_args",
"tests/test_signature_parsing.py::test_populate_annotated_enum_regression",
"tests/test_signature_parsing.py::test_parse_sig_with_new_vs_init[A]",
"tests/test_signature_parsing.py::test_parse_sig_with_new_vs_init[B]",
"tests/test_signature_parsing.py::test_parse_sig_with_new_vs_init[C]",
"tests/test_signature_parsing.py::test_parse_sig_with_new_vs_init[D]",
"tests/test_signature_parsing.py::test_parse_sig_with_new_vs_init[E]",
"tests/test_signature_parsing.py::test_Counter",
"tests/test_signature_parsing.py::test_inheritance_populates_init_field",
"tests/test_signature_parsing.py::test_builds_of_inherited_classmethod[B265]",
"tests/test_signature_parsing.py::test_builds_of_inherited_classmethod[C265]",
"tests/test_store.py::test_kw_overrides[inline]",
"tests/test_store.py::test_kw_overrides[decorated]",
"tests/test_store.py::test_kw_overrides[partiald_inline]",
"tests/test_store.py::test_kw_overrides[partiald_decorated]",
"tests/test_store.py::test_kw_overrides[kw_overrides]",
"tests/test_store.py::test_name_overrides[inline]",
"tests/test_store.py::test_name_overrides[decorated]",
"tests/test_store.py::test_name_overrides[partiald_inline]",
"tests/test_store.py::test_name_overrides[partiald_decorated]",
"tests/test_store.py::test_name_overrides[kw_overrides]",
"tests/test_store.py::test_group_overrides[inline]",
"tests/test_store.py::test_group_overrides[decorated]",
"tests/test_store.py::test_group_overrides[partiald_inline]",
"tests/test_store.py::test_group_overrides[partiald_decorated]",
"tests/test_store.py::test_group_overrides[kw_overrides]",
"tests/test_store.py::test_package_overrides[inline]",
"tests/test_store.py::test_package_overrides[decorated]",
"tests/test_store.py::test_package_overrides[partiald_inline]",
"tests/test_store.py::test_package_overrides[partiald_decorated]",
"tests/test_store.py::test_package_overrides[kw_overrides]",
"tests/test_store.py::test_to_config_overrides[inline]",
"tests/test_store.py::test_to_config_overrides[decorated]",
"tests/test_store.py::test_to_config_overrides[partiald_inline]",
"tests/test_store.py::test_to_config_overrides[partiald_decorated]",
"tests/test_store.py::test_to_config_overrides[kw_overrides]",
"tests/test_store.py::test_provider_overrides[inline]",
"tests/test_store.py::test_provider_overrides[decorated]",
"tests/test_store.py::test_provider_overrides[partiald_inline]",
"tests/test_store.py::test_provider_overrides[partiald_decorated]",
"tests/test_store.py::test_provider_overrides[kw_overrides]",
"tests/test_store.py::test_store_nested_groups[True]",
"tests/test_store.py::test_store_nested_groups[False]",
"tests/test_store.py::test_store_param_validation[name-1]",
"tests/test_store.py::test_store_param_validation[name-True]",
"tests/test_store.py::test_store_param_validation[name-bad_val2]",
"tests/test_store.py::test_store_param_validation[group-1]",
"tests/test_store.py::test_store_param_validation[group-True]",
"tests/test_store.py::test_store_param_validation[group-bad_val2]",
"tests/test_store.py::test_store_param_validation[package-1]",
"tests/test_store.py::test_store_param_validation[package-True]",
"tests/test_store.py::test_store_param_validation[package-bad_val2]",
"tests/test_store.py::test_validate_get_name",
"tests/test_store.py::test_raise_on_redundant_store[None-None-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-None-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-None-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-None-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-c-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-c-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-c-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-c-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-d-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-d-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-d-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-d-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-e/f-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-e/f-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-e/f-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-e/f-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-e/f/g-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-e/f/g-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[None-e/f/g-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[None-e/f/g-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-None-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-None-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-None-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-None-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-c-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-c-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-c-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-c-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-d-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-d-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-d-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-d-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-e/f-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-e/f-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-e/f-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-e/f-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-e/f/g-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-e/f/g-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[c-e/f/g-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[c-e/f/g-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-None-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-None-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-None-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-None-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-c-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-c-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-c-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-c-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-d-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-d-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-d-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-d-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-e/f-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-e/f-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-e/f-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-e/f-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-e/f/g-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-e/f/g-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[d-e/f/g-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[d-e/f/g-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-None-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-None-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-None-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-None-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-c-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-c-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-c-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-c-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-d-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-d-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-d-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-d-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-e/f-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-e/f-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-e/f-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-e/f-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-e/f/g-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-e/f/g-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-e/f/g-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f-e/f/g-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-None-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-None-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-None-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-None-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-c-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-c-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-c-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-c-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-d-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-d-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-d-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-d-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-e/f-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-e/f-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-e/f-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-e/f-b-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-e/f/g-a-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-e/f/g-a-b]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-e/f/g-b-a]",
"tests/test_store.py::test_raise_on_redundant_store[e/f/g-e/f/g-b-b]",
"tests/test_store.py::test_overwrite_ok[True-True-None-a]",
"tests/test_store.py::test_overwrite_ok[True-True-None-b]",
"tests/test_store.py::test_overwrite_ok[True-True-c-a]",
"tests/test_store.py::test_overwrite_ok[True-True-c-b]",
"tests/test_store.py::test_overwrite_ok[True-True-d-a]",
"tests/test_store.py::test_overwrite_ok[True-True-d-b]",
"tests/test_store.py::test_overwrite_ok[True-True-e/f-a]",
"tests/test_store.py::test_overwrite_ok[True-True-e/f-b]",
"tests/test_store.py::test_overwrite_ok[True-True-e/f/g-a]",
"tests/test_store.py::test_overwrite_ok[True-True-e/f/g-b]",
"tests/test_store.py::test_overwrite_ok[True-False-None-a]",
"tests/test_store.py::test_overwrite_ok[True-False-None-b]",
"tests/test_store.py::test_overwrite_ok[True-False-c-a]",
"tests/test_store.py::test_overwrite_ok[True-False-c-b]",
"tests/test_store.py::test_overwrite_ok[True-False-d-a]",
"tests/test_store.py::test_overwrite_ok[True-False-d-b]",
"tests/test_store.py::test_overwrite_ok[True-False-e/f-a]",
"tests/test_store.py::test_overwrite_ok[True-False-e/f-b]",
"tests/test_store.py::test_overwrite_ok[True-False-e/f/g-a]",
"tests/test_store.py::test_overwrite_ok[True-False-e/f/g-b]",
"tests/test_store.py::test_overwrite_ok[False-True-None-a]",
"tests/test_store.py::test_overwrite_ok[False-True-None-b]",
"tests/test_store.py::test_overwrite_ok[False-True-c-a]",
"tests/test_store.py::test_overwrite_ok[False-True-c-b]",
"tests/test_store.py::test_overwrite_ok[False-True-d-a]",
"tests/test_store.py::test_overwrite_ok[False-True-d-b]",
"tests/test_store.py::test_overwrite_ok[False-True-e/f-a]",
"tests/test_store.py::test_overwrite_ok[False-True-e/f-b]",
"tests/test_store.py::test_overwrite_ok[False-True-e/f/g-a]",
"tests/test_store.py::test_overwrite_ok[False-True-e/f/g-b]",
"tests/test_store.py::test_overwrite_ok[False-False-None-a]",
"tests/test_store.py::test_overwrite_ok[False-False-None-b]",
"tests/test_store.py::test_overwrite_ok[False-False-c-a]",
"tests/test_store.py::test_overwrite_ok[False-False-c-b]",
"tests/test_store.py::test_overwrite_ok[False-False-d-a]",
"tests/test_store.py::test_overwrite_ok[False-False-d-b]",
"tests/test_store.py::test_overwrite_ok[False-False-e/f-a]",
"tests/test_store.py::test_overwrite_ok[False-False-e/f-b]",
"tests/test_store.py::test_overwrite_ok[False-False-e/f/g-a]",
"tests/test_store.py::test_overwrite_ok[False-False-e/f/g-b]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[target0]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[target1]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[target2]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[target3]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[Config]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[target5]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[Builds_dict]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[DC]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[target8]",
"tests/test_store.py::test_default_to_config_produces_instantiable_configs[target9]",
"tests/test_store.py::test_self_partialing_reflects_mutable_state",
"tests/test_store.py::test_stores_have_independent_mutable_state",
"tests/test_store.py::test_deferred_to_config[None-a]",
"tests/test_store.py::test_deferred_to_config[None-b]",
"tests/test_store.py::test_deferred_to_config[c-a]",
"tests/test_store.py::test_deferred_to_config[c-b]",
"tests/test_store.py::test_deferred_to_config[d-a]",
"tests/test_store.py::test_deferred_to_config[d-b]",
"tests/test_store.py::test_deferred_to_config[e/f-a]",
"tests/test_store.py::test_deferred_to_config[e/f-b]",
"tests/test_store.py::test_deferred_to_config[e/f/g-a]",
"tests/test_store.py::test_deferred_to_config[e/f/g-b]",
"tests/test_store.py::test_self_partialing_preserves_subclass",
"tests/test_store.py::test_default_to_config_validates_dataclass_instance_with_kw",
"tests/test_store.py::test_validate_init[deferred_to_config]",
"tests/test_store.py::test_validate_init[deferred_hydra_store]",
"tests/test_store.py::test_validate_init[overwrite_ok]",
"tests/test_store.py::test_contains_manual",
"tests/test_store.py::test_contains_consistent_with_getitem",
"tests/test_store.py::test_iter",
"tests/test_store.py::test_bool",
"tests/test_store.py::test_repr",
"tests/test_store.py::test_repeated_add_to_hydra_store_ok",
"tests/test_store.py::test_store_protects_overwriting_entries_in_hydra_store",
"tests/test_store.py::test_getitem",
"tests/test_store.py::test_eq",
"tests/test_store.py::test_get_entry",
"tests/test_store.py::test_entry_access_cannot_mutate_store[<lambda>0]",
"tests/test_store.py::test_entry_access_cannot_mutate_store[<lambda>1]",
"tests/test_store.py::test_auto_support_for_HydraConf[True-CustomHydraConf]",
"tests/test_store.py::test_auto_support_for_HydraConf[True-conf1]",
"tests/test_store.py::test_auto_support_for_HydraConf[False-CustomHydraConf]",
"tests/test_store.py::test_auto_support_for_HydraConf[False-conf1]",
"tests/test_store.py::test_configure_hydra_chdir[None]"
] |
[] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-01-23 22:21:01+00:00
|
mit
| 3,970 |
|
mit-ll-responsible-ai__hydra-zen-459
|
diff --git a/docs/source/changes.rst b/docs/source/changes.rst
index b78326f0..bc98b949 100644
--- a/docs/source/changes.rst
+++ b/docs/source/changes.rst
@@ -8,28 +8,36 @@ Changelog
This is a record of all past hydra-zen releases and what went into them, in reverse
chronological order. All previous releases should still be available on pip.
---------------------------
-Documentation - 2023-03-11
---------------------------
-
-The following parts of the documentation underwent significant revisions:
-
-- `The landing page <https://github.com/mit-ll-responsible-ai/hydra-zen>`_ now has a "hydra-zen at at glance" subsection.
-- The docs for `~hydra_zen.ZenStore` were revamped.
-
.. _v0.11.0:
---------------------
0.11.0rc - 2023-04-09
---------------------
-This release drops support for hydra-core 1.1 and for omegaconf 2.1; this enables hydra-zen to remove a lot of complex compatibility logic and to improve the behavior
-of :func:`~hydra_zen.zen`.
+.. note:: This is documentation for an unreleased version of hydra-zen. You can try out this pre-release version using `pip install --pre hydra-zen`
+
+This release drops support for hydra-core 1.1 and for omegaconf 2.1; this enabled the
+removal of a lot of complex compatibility logic from hydra-zen's source code, and to
+improve the behavior of :func:`~hydra_zen.zen`.
+
+Bug Fixes
+---------
+- Configs produced by `~hydra_zen.just` will no longer cause a `ReadonlyConfigError` during Hydra's config-composition process. See :pull:`459`
Compatibility-Breaking Changes
------------------------------
- The auto-instantiation behavior of :class:`~hydra_zen.wrapper.Zen` and :func:`~hydra_zen.zen` have been updated so that nested dataclasses (nested within lists, dicts, and other dataclasses) will no longer be returned as omegaconf configs (see :pull:`448`).
- hydra-core 1.2.0 and omegaconf 2.2.1 are now the minimum supported versions.
+- :func:`~hydra_zen.just` not longer returns a frozen dataclass (see :pull:`459`).
+
+--------------------------
+Documentation - 2023-03-11
+--------------------------
+
+The following parts of the documentation underwent significant revisions:
+
+- `The landing page <https://github.com/mit-ll-responsible-ai/hydra-zen>`_ now has a "hydra-zen at at glance" subsection.
+- The docs for `~hydra_zen.ZenStore` were revamped.
.. _v0.10.0:
diff --git a/src/hydra_zen/structured_configs/_implementations.py b/src/hydra_zen/structured_configs/_implementations.py
index c4fa41bc..01c86425 100644
--- a/src/hydra_zen/structured_configs/_implementations.py
+++ b/src/hydra_zen/structured_configs/_implementations.py
@@ -485,7 +485,7 @@ def hydrated_dataclass(
return wrapper
-@dataclass(frozen=True)
+@dataclass(unsafe_hash=True)
class Just:
"""Just[T] is a config that returns T when instantiated."""
|
mit-ll-responsible-ai/hydra-zen
|
450e1cf0beefeb2d8b2605a55e1048fb6cab2d42
|
diff --git a/tests/test_launch/test_merge_compat.py b/tests/test_launch/test_merge_compat.py
new file mode 100644
index 00000000..1c3737f4
--- /dev/null
+++ b/tests/test_launch/test_merge_compat.py
@@ -0,0 +1,52 @@
+# Copyright (c) 2023 Massachusetts Institute of Technology
+# SPDX-License-Identifier: MIT
+
+import pytest
+from omegaconf import DictConfig
+
+from hydra_zen import ZenStore, builds, launch, make_config, to_yaml, zen
+
+
+def relu():
+ ...
+
+
+def selu():
+ ...
+
+
+class Model:
+ def __init__(self, activation_fn=relu):
+ ...
+
+
+def app(zen_cfg: DictConfig, model: Model) -> None:
+ print(to_yaml(zen_cfg, resolve=True))
+
+
[email protected]("cleandir")
[email protected]("clean_store")
+def test_merge_prevented_by_frozen_regression():
+ # https://github.com/mit-ll-responsible-ai/hydra-zen/issues/449
+
+ store = ZenStore()
+ Config = builds(
+ app,
+ populate_full_signature=True,
+ hydra_defaults=[
+ "_self_",
+ {"model": "Model"},
+ {"experiment": "selu"},
+ ],
+ )
+
+ experiment_store = store(group="experiment", package="_global_")
+ experiment_store(
+ make_config(
+ hydra_defaults=["_self_"], model=dict(activation_fn=selu), bases=(Config,)
+ ),
+ name="selu",
+ )
+ store(Model, group="model")
+ store.add_to_hydra_store()
+ launch(Config, zen(app), version_base="1.2")
|
Don't make any configs frozen by default
Apparently this causes config merge issues: https://github.com/mit-ll-responsible-ai/hydra-zen/discussions/438
|
0.0
|
450e1cf0beefeb2d8b2605a55e1048fb6cab2d42
|
[
"tests/test_launch/test_merge_compat.py::test_merge_prevented_by_frozen_regression"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-18 17:24:41+00:00
|
mit
| 3,971 |
|
mit-ll-responsible-ai__hydra-zen-460
|
diff --git a/docs/source/changes.rst b/docs/source/changes.rst
index 56ef9293..ece432cc 100644
--- a/docs/source/changes.rst
+++ b/docs/source/changes.rst
@@ -56,6 +56,7 @@ Improvements
------------
- :func:`~hydra_zen.builds` now has a transitive property that enables iterative build patterns. See :pull:`455`
- :func:`~hydra_zen.zen`'s instantiation phase has been improved so that dataclass objects and stdlib containers are returned instead of omegaconf objects. See :pull:`#448`.
+- :func:`~hydra_zen.zen` can now be passed `resolve_pre_call=False` to defer the resolution of interpolated fields until after `pre_call` functions are called. See :pull:`460`.
Bug Fixes
---------
diff --git a/src/hydra_zen/wrapper/_implementations.py b/src/hydra_zen/wrapper/_implementations.py
index 6fcc9144..3301979e 100644
--- a/src/hydra_zen/wrapper/_implementations.py
+++ b/src/hydra_zen/wrapper/_implementations.py
@@ -1,6 +1,6 @@
# Copyright (c) 2023 Massachusetts Institute of Technology
# SPDX-License-Identifier: MIT
-# pyright: strict
+# pyright: strict, reportUnnecessaryTypeIgnoreComment = true, reportUnnecessaryIsInstance = false
import warnings
from collections import defaultdict, deque
@@ -136,6 +136,7 @@ class Zen(Generic[P, R]):
exclude: Optional[Union[str, Iterable[str]]] = None,
pre_call: PreCall = None,
unpack_kwargs: bool = False,
+ resolve_pre_call: bool = True,
) -> None:
"""
Parameters
@@ -173,9 +174,14 @@ class Zen(Generic[P, R]):
"signatures."
)
- if not isinstance(unpack_kwargs, bool): # type: ignore
+ if not isinstance(unpack_kwargs, bool):
raise TypeError(f"`unpack_kwargs` must be type `bool` got {unpack_kwargs}")
+ if not isinstance(resolve_pre_call, bool): # pragma: no cover
+ raise TypeError(
+ f"`resolve_pre_call` must be type `bool` got {resolve_pre_call}"
+ )
+ self._resolve = resolve_pre_call
self._unpack_kwargs: bool = unpack_kwargs and any(
p.kind is p.VAR_KEYWORD for p in self.parameters.values()
)
@@ -222,8 +228,8 @@ class Zen(Generic[P, R]):
pre_call if not isinstance(pre_call, Iterable) else _flat_call(pre_call)
)
- @staticmethod
def _normalize_cfg(
+ self,
cfg: Union[
DataClass_,
Type[DataClass_],
@@ -340,8 +346,10 @@ class Zen(Generic[P, R]):
The result of `func(<args extracted from cfg>)`
"""
cfg = self._normalize_cfg(__cfg)
- # resolves all interpolated values in-place
- OmegaConf.resolve(cfg)
+
+ if self._resolve:
+ # resolves all interpolated values in-place
+ OmegaConf.resolve(cfg)
if self.pre_call is not None:
self.pre_call(cfg)
@@ -461,6 +469,7 @@ def zen(
unpack_kwargs: bool = ...,
pre_call: PreCall = ...,
ZenWrapper: Type[Zen[P, R]] = Zen,
+ resolve_pre_call: bool = ...,
exclude: Optional[Union[str, Iterable[str]]] = None,
) -> Zen[P, R]:
...
@@ -472,6 +481,7 @@ def zen(
*,
unpack_kwargs: bool = ...,
pre_call: PreCall = ...,
+ resolve_pre_call: bool = ...,
ZenWrapper: Type[Zen[Any, Any]] = ...,
exclude: Optional[Union[str, Iterable[str]]] = None,
) -> Callable[[Callable[P, R]], Zen[P, R]]:
@@ -484,6 +494,7 @@ def zen(
unpack_kwargs: bool = False,
pre_call: PreCall = None,
exclude: Optional[Union[str, Iterable[str]]] = None,
+ resolve_pre_call: bool = True,
ZenWrapper: Type[Zen[P, R]] = Zen,
) -> Union[Zen[P, R], Callable[[Callable[P, R]], Zen[P, R]]]:
r"""zen(func, /, pre_call, ZenWrapper)
@@ -521,12 +532,16 @@ def zen(
This is useful, e.g., for seeding a RNG prior to the instantiation phase
that is triggered when calling the wrapped function.
- exclude: Optional[str | Iterable[str]]
+ exclude : Optional[str | Iterable[str]]
Specifies one or more parameter names in the function's signature
that will not be extracted from input configs by the zen-wrapped function.
A single string of comma-separated names can be specified.
+ resolve_pre_call : bool, (default=True)
+ If True, the config passed to the zen-wrapped function has its interpolated
+ fields resolved to being passed to any pre-call functions.
+
ZenWrapper : Type[hydra_zen.wrapper.Zen], optional (default=Zen)
If specified, a subclass of `Zen` that customizes the behavior of the wrapper.
@@ -722,12 +737,20 @@ def zen(
"""
if __func is not None:
return ZenWrapper(
- __func, pre_call=pre_call, exclude=exclude, unpack_kwargs=unpack_kwargs
+ __func,
+ pre_call=pre_call,
+ exclude=exclude,
+ unpack_kwargs=unpack_kwargs,
+ resolve_pre_call=resolve_pre_call,
)
def wrap(f: Callable[P, R]) -> Zen[P, R]:
return ZenWrapper(
- f, pre_call=pre_call, exclude=exclude, unpack_kwargs=unpack_kwargs
+ f,
+ pre_call=pre_call,
+ exclude=exclude,
+ unpack_kwargs=unpack_kwargs,
+ resolve_pre_call=resolve_pre_call,
)
return wrap
@@ -1278,15 +1301,15 @@ class ZenStore:
with `store(node=Config)` instead of actually storing the node with
`store(Config)`.
"""
- if not isinstance(deferred_to_config, bool): # type: ignore
+ if not isinstance(deferred_to_config, bool):
raise TypeError(
f"deferred_to_config must be a bool, got {deferred_to_config}"
)
- if not isinstance(overwrite_ok, bool): # type: ignore
+ if not isinstance(overwrite_ok, bool):
raise TypeError(f"overwrite_ok must be a bool, got {overwrite_ok}")
- if not isinstance(deferred_hydra_store, bool): # type: ignore
+ if not isinstance(deferred_hydra_store, bool):
raise TypeError(
f"deferred_hydra_store must be a bool, got {deferred_hydra_store}"
)
|
mit-ll-responsible-ai/hydra-zen
|
303225c0db70e614b85b17f3189a8a85c833324a
|
diff --git a/tests/test_zen.py b/tests/test_zen.py
index 8fffa0b3..b0b32c10 100644
--- a/tests/test_zen.py
+++ b/tests/test_zen.py
@@ -217,6 +217,27 @@ def test_zen_resolves_default_factories():
assert zen_identity(Cfg()) == [1, 2, 3]
+def test_no_resolve():
+ def not_resolved(x):
+ assert x == dict(x=1, y="${x}")
+
+ def is_resolved(x):
+ assert x == dict(x=1, y=1)
+
+ Cfg = make_config(x=1, y="${x}")
+ out = zen(lambda **kw: kw, unpack_kwargs=True, pre_call=is_resolved)(Cfg)
+ assert out == dict(x=1, y=1)
+
+ Cfg2 = make_config(x=1, y="${x}")
+ out2 = zen(
+ lambda **kw: kw,
+ unpack_kwargs=True,
+ resolve_pre_call=False,
+ pre_call=not_resolved,
+ )(Cfg2)
+ assert out2 == dict(x=1, y=1)
+
+
def test_zen_works_on_partiald_funcs():
from functools import partial
|
Move `OmegaConf.resolve(cfg)` after `pre_call`
Hello,
I am using the `@zen` decorator in my project, and using its `pre_call` arg to modify my config. I am trying to modify the unresolved config, but `pre_call` gets the config after `OmegaConf.resolve(cfg)` has been run.
https://github.com/mit-ll-responsible-ai/hydra-zen/blob/796d8ac7c87c5ad245eb739cd27b81cf62eb19ca/src/hydra_zen/wrapper/_implementations.py#L336
Can `OmegaConf.resolve(cfg)` please be moved to be after `self.pre_call(cfg)` to allow for more flexibility?
|
0.0
|
303225c0db70e614b85b17f3189a8a85c833324a
|
[
"tests/test_zen.py::test_no_resolve",
"tests/test_zen.py::test_zen_validate_bad_config"
] |
[
"tests/test_zen.py::test_zen_basic_usecase",
"tests/test_zen.py::test_zen_repr",
"tests/test_zen.py::test_zen_excluded_param[None-expected0]",
"tests/test_zen.py::test_zen_excluded_param[y-expected1]",
"tests/test_zen.py::test_zen_excluded_param[y,-expected2]",
"tests/test_zen.py::test_zen_excluded_param[exclude3-expected3]",
"tests/test_zen.py::test_zen_excluded_param[x,y-expected4]",
"tests/test_zen.py::test_zen_excluded_param[exclude5-expected5]",
"tests/test_zen.py::test_repr_doesnt_crash[target0]",
"tests/test_zen.py::test_repr_doesnt_crash[target1]",
"tests/test_zen.py::test_repr_doesnt_crash[target2]",
"tests/test_zen.py::test_repr_doesnt_crash[target3]",
"tests/test_zen.py::test_repr_doesnt_crash[target4]",
"tests/test_zen.py::test_repr_doesnt_crash[target5]",
"tests/test_zen.py::test_zen_wrapper_trick[None]",
"tests/test_zen.py::test_zen_wrapper_trick[<lambda>]",
"tests/test_zen.py::test_zen_pre_call_precedes_instantiation",
"tests/test_zen.py::test_interpolations_are_resolved",
"tests/test_zen.py::test_supported_config_types[cfg0]",
"tests/test_zen.py::test_supported_config_types[cfg1]",
"tests/test_zen.py::test_supported_config_types[Config]",
"tests/test_zen.py::test_supported_config_types[x:",
"tests/test_zen.py::test_zen_resolves_default_factories",
"tests/test_zen.py::test_zen_works_on_partiald_funcs",
"tests/test_zen.py::test_zen_cfg_passthrough",
"tests/test_zen.py::test_custom_zen_wrapper",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config0-function]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config0-function_with_args]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config0-function_with_kwargs]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config0-function_with_args_kwargs]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config0-f]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config1-function]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config1-function_with_args]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config1-function_with_kwargs]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config1-function_with_args_kwargs]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config1-f]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config2-function]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config2-function_with_args]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config2-function_with_kwargs]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config2-function_with_args_kwargs]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config2-f]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config3-function]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config3-function_with_args]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config3-function_with_kwargs]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config3-function_with_args_kwargs]",
"tests/test_zen.py::test_zen_validation_cfg_missing_parameter[Config3-f]",
"tests/test_zen.py::test_validate_unpack_kwargs",
"tests/test_zen.py::test_zen_validation_excluded_param",
"tests/test_zen.py::test_zen_validation_cfg_has_bad_pos_args",
"tests/test_zen.py::test_zen_validate_no_sig[not_inspectable0]",
"tests/test_zen.py::test_zen_validate_no_sig[False]",
"tests/test_zen.py::test_pre_call_validates_wrong_num_args[<lambda>0]",
"tests/test_zen.py::test_pre_call_validates_wrong_num_args[<lambda>1]",
"tests/test_zen.py::test_pre_call_validates_wrong_num_args[<lambda>2]",
"tests/test_zen.py::test_pre_call_validates_bad_param_name",
"tests/test_zen.py::test_zen_call[function]",
"tests/test_zen.py::test_zen_call[function_with_args]",
"tests/test_zen.py::test_zen_call[function_with_kwargs]",
"tests/test_zen.py::test_zen_call[function_with_args_kwargs]",
"tests/test_zen.py::test_zen_call[f]",
"tests/test_zen.py::test_zen_function_respects_with_defaults",
"tests/test_zen.py::test_instantiation_only_occurs_as_needed[<lambda>0]",
"tests/test_zen.py::test_instantiation_only_occurs_as_needed[<lambda>1]",
"tests/test_zen.py::test_instantiation_only_occurs_as_needed[<lambda>2]",
"tests/test_zen.py::test_instantiation_only_occurs_as_needed[<lambda>3]",
"tests/test_zen.py::test_zen_works_with_non_builds",
"tests/test_zen.py::test_multiple_pre_calls",
"tests/test_zen.py::test_hydra_main",
"tests/test_zen.py::test_hydra_main_config_path[dir1-cfg1]",
"tests/test_zen.py::test_hydra_main_config_path[dir1-cfg2]",
"tests/test_zen.py::test_hydra_main_config_path[dir2-cfg1]",
"tests/test_zen.py::test_hydra_main_config_path[dir2-cfg2]",
"tests/test_zen.py::test_hydra_main_config_path[None-None]",
"tests/test_zen.py::test_unpack_kw_basic_behavior[zen_func0]",
"tests/test_zen.py::test_unpack_kw_basic_behavior[zen_func1]",
"tests/test_zen.py::test_unpack_kw_non_redundant",
"tests/test_zen.py::test_pickle_compatible"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-21 18:49:27+00:00
|
mit
| 3,972 |
|
mit-ll-responsible-ai__hydra-zen-600
|
diff --git a/src/hydra_zen/structured_configs/_implementations.py b/src/hydra_zen/structured_configs/_implementations.py
index ebda2b9f..32fbe3eb 100644
--- a/src/hydra_zen/structured_configs/_implementations.py
+++ b/src/hydra_zen/structured_configs/_implementations.py
@@ -50,6 +50,7 @@ from typing_extensions import (
ParamSpec,
ParamSpecArgs,
ParamSpecKwargs,
+ Protocol,
TypeAlias,
Unpack,
_AnnotatedAlias,
@@ -141,9 +142,15 @@ _JUST_CONVERT_SETTINGS = AllConvert(dataclass=True, flat_target=False)
# default zen_convert settings for `builds` and `hydrated_dataclass`
_BUILDS_CONVERT_SETTINGS = AllConvert(dataclass=True, flat_target=True)
+
# stores type -> value-conversion-fn
# for types with specialized support from hydra-zen
-ZEN_VALUE_CONVERSION: Dict[type, Callable[[Any], Any]] = {}
+class _ConversionFn(Protocol):
+ def __call__(self, __x: Any, CBuildsFn: "Type[BuildsFn[Any]]") -> Any:
+ ...
+
+
+ZEN_VALUE_CONVERSION: Dict[type, _ConversionFn] = {}
# signature param-types
_POSITIONAL_ONLY: Final = inspect.Parameter.POSITIONAL_ONLY
@@ -1089,7 +1096,7 @@ class BuildsFn(Generic[T]):
type_ = type(resolved_value)
conversion_fn = ZEN_VALUE_CONVERSION[type_]
- resolved_value = conversion_fn(resolved_value)
+ resolved_value = conversion_fn(resolved_value, CBuildsFn=cls)
type_of_value = type(resolved_value)
if type_of_value in HYDRA_SUPPORTED_PRIMITIVES or (
@@ -2135,7 +2142,9 @@ class BuildsFn(Generic[T]):
# We are intentionally keeping each condition branched
# so that test-coverage will be checked for each one
if isinstance(wrapper, functools.partial):
- wrapper = ZEN_VALUE_CONVERSION[functools.partial](wrapper)
+ wrapper = ZEN_VALUE_CONVERSION[functools.partial](
+ wrapper, CBuildsFn=cls
+ )
if is_builds(wrapper):
# If Hydra's locate function starts supporting importing literals
@@ -3347,12 +3356,20 @@ class ConfigComplex:
real: Any
imag: Any
_target_: str = field(default=BuildsFn._get_obj_path(complex), init=False)
+ CBuildsFn: InitVar[Type[BuildsFn[Any]]]
+
+ def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None:
+ del CBuildsFn
@dataclass(unsafe_hash=True)
class ConfigPath:
_args_: Tuple[str]
_target_: str = field(default=BuildsFn._get_obj_path(Path), init=False)
+ CBuildsFn: InitVar[Type[BuildsFn[Any]]]
+
+ def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None: # pragma: no cover
+ del CBuildsFn
@overload
@@ -3489,8 +3506,13 @@ def mutable_value(
return BuildsFunction._mutable_value(x, zen_convert=zen_convert)
-def convert_complex(value: complex) -> Builds[Type[complex]]:
- return cast(Builds[Type[complex]], ConfigComplex(real=value.real, imag=value.imag))
+def convert_complex(
+ value: complex, CBuildsFn: Type[BuildsFn[Any]]
+) -> Builds[Type[complex]]:
+ return cast(
+ Builds[Type[complex]],
+ ConfigComplex(real=value.real, imag=value.imag, CBuildsFn=CBuildsFn),
+ )
ZEN_VALUE_CONVERSION[complex] = convert_complex
@@ -3498,27 +3520,32 @@ ZEN_VALUE_CONVERSION[complex] = convert_complex
if Path in ZEN_SUPPORTED_PRIMITIVES: # pragma: no cover
- def convert_path(value: Path) -> Builds[Type[Path]]:
- return cast(Builds[Type[Path]], ConfigPath(_args_=(str(value),)))
+ def convert_path(value: Path, CBuildsFn: Type[BuildsFn[Any]]) -> Builds[Type[Path]]:
+ return cast(
+ Builds[Type[Path]], ConfigPath(_args_=(str(value),), CBuildsFn=CBuildsFn)
+ )
ZEN_VALUE_CONVERSION[Path] = convert_path
ZEN_VALUE_CONVERSION[PosixPath] = convert_path
ZEN_VALUE_CONVERSION[WindowsPath] = convert_path
-def _unpack_partial(value: Partial[_T]) -> PartialBuilds[Type[_T]]:
+def _unpack_partial(
+ value: Partial[_T], CBuildsFn: InitVar[Type[BuildsFn[Any]]]
+) -> PartialBuilds[Type[_T]]:
target = cast(Type[_T], value.func)
- return builds(target, *value.args, **value.keywords, zen_partial=True)()
+ return CBuildsFn.builds(target, *value.args, **value.keywords, zen_partial=True)()
@dataclass(unsafe_hash=True)
class ConfigFromTuple:
_args_: Tuple[Any, ...]
_target_: str
+ CBuildsFn: InitVar[Type[BuildsFn[Any]]]
- def __post_init__(self):
+ def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None:
self._args_ = (
- BuildsFn._make_hydra_compatible(
+ CBuildsFn._make_hydra_compatible(
tuple(self._args_),
convert_dataclass=True,
allow_zen_conversion=True,
@@ -3531,10 +3558,11 @@ class ConfigFromTuple:
class ConfigFromDict:
_args_: Any
_target_: str
+ CBuildsFn: InitVar[Type[BuildsFn[Any]]]
- def __post_init__(self):
+ def __post_init__(self, CBuildsFn: Type[BuildsFn[Any]]) -> None:
self._args_ = (
- BuildsFn._make_hydra_compatible(
+ CBuildsFn._make_hydra_compatible(
dict(self._args_),
convert_dataclass=True,
allow_zen_conversion=True,
@@ -3550,8 +3578,12 @@ class ConfigRange:
step: InitVar[int]
_target_: str = field(default=BuildsFn._get_obj_path(range), init=False)
_args_: Tuple[int, ...] = field(default=(), init=False, repr=False)
+ CBuildsFn: InitVar[Type[BuildsFn[Any]]]
- def __post_init__(self, start, stop, step):
+ def __post_init__(
+ self, start: int, stop: int, step: int, CBuildsFn: Type[BuildsFn[Any]]
+ ) -> None:
+ del CBuildsFn
self._args_ = (start, stop, step)
@@ -3573,8 +3605,11 @@ if bytes in ZEN_SUPPORTED_PRIMITIVES: # pragma: no cover
ZEN_VALUE_CONVERSION[bytearray] = partial(
ConfigFromTuple, _target_=BuildsFn._get_obj_path(bytearray)
)
-ZEN_VALUE_CONVERSION[range] = lambda value: ConfigRange(
- value.start, value.stop, value.step
+ZEN_VALUE_CONVERSION[range] = lambda value, CBuildsFn: ConfigRange(
+ value.start,
+ value.stop,
+ value.step,
+ CBuildsFn=CBuildsFn,
)
ZEN_VALUE_CONVERSION[Counter] = partial(
ConfigFromDict, _target_=BuildsFn._get_obj_path(Counter)
|
mit-ll-responsible-ai/hydra-zen
|
7b93b419091ce5303f9563d4fb3eca316fc46af9
|
diff --git a/tests/test_BuildsFn.py b/tests/test_BuildsFn.py
index c418dcbb..ef09ba7e 100644
--- a/tests/test_BuildsFn.py
+++ b/tests/test_BuildsFn.py
@@ -1,6 +1,6 @@
# Copyright (c) 2023 Massachusetts Institute of Technology
# SPDX-License-Identifier: MIT
-
+from collections import deque
from functools import partial
from inspect import signature
from typing import Any, List, Union
@@ -17,6 +17,7 @@ from hydra_zen import (
just,
make_config,
make_custom_builds_fn,
+ to_yaml,
)
from hydra_zen.errors import HydraZenUnsupportedPrimitiveError
from hydra_zen.typing import DataclassOptions, SupportedPrimitive
@@ -31,6 +32,9 @@ class A:
def __eq__(self, __value: object) -> bool:
return isinstance(__value, type(self)) and __value.x == self.x
+ def __hash__(self) -> int:
+ return hash(self.x) + hash(self.__class__.__name__)
+
@staticmethod
def static():
return 11
@@ -171,3 +175,19 @@ def test_default_to_config():
)
store(A, x=A(x=2), name="blah")
assert instantiate(store[None, "blah"]) == A(x=A(x=2))
+
+
[email protected](
+ "obj",
+ [
+ deque([A(x=1), A(x=2)]),
+ partial(foo, x=A(x=1)),
+ ],
+)
+def test_zen_conversion_uses_custom_builds(obj):
+ Conf = MyBuildsFn.just(obj)
+ to_yaml(Conf)
+ if not isinstance(obj, partial):
+ assert instantiate(Conf) == obj
+ else:
+ assert instantiate(Conf)() == obj()
|
Cusont `BuildsFn` autoconfig support doesn't work for hydra-zen extended types
E.g. set, deque, counter have their elements converted by `DefaultBuilds`.
|
0.0
|
7b93b419091ce5303f9563d4fb3eca316fc46af9
|
[
"tests/test_BuildsFn.py::test_zen_conversion_uses_custom_builds[obj0]",
"tests/test_BuildsFn.py::test_zen_conversion_uses_custom_builds[obj1]"
] |
[
"tests/test_BuildsFn.py::test_call",
"tests/test_BuildsFn.py::test_just",
"tests/test_BuildsFn.py::test_make_custom_builds",
"tests/test_BuildsFn.py::test_sanitized_type_override",
"tests/test_BuildsFn.py::test_make_config",
"tests/test_BuildsFn.py::test_zen_field",
"tests/test_BuildsFn.py::test_default_to_config"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-25 15:57:03+00:00
|
mit
| 3,973 |
|
mitodl__release-script-307
|
diff --git a/finish_release.py b/finish_release.py
index 749dd6d..c5fdef6 100644
--- a/finish_release.py
+++ b/finish_release.py
@@ -10,7 +10,11 @@ from async_subprocess import (
)
from exception import VersionMismatchException
from github import get_org_and_repo
-from lib import get_default_branch
+from lib import (
+ get_default_branch,
+ get_pr_ref,
+ get_release_pr,
+)
from release import (
init_working_dir,
validate_dependencies,
@@ -116,7 +120,7 @@ def update_go_mod(*, path, version, repo_url):
return False
-async def update_go_mod_and_commit(*, github_access_token, new_version, repo_info, go_mod_repo_url):
+async def update_go_mod_and_commit(*, github_access_token, new_version, repo_info, go_mod_repo_url, pull_request):
"""
Create a new PR with an updated go.mod file
@@ -125,6 +129,7 @@ async def update_go_mod_and_commit(*, github_access_token, new_version, repo_inf
new_version (str): The new version of the finished release
repo_info (RepoInfo): The repository info for the finished release
go_mod_repo_url (str): The repository info for the project with the go.mod file to update
+ pull_request (ReleasePR): The release PR
"""
# go_mod is starter, finished repo is theme
# theme was just merged, so we want to checkout and update starter's go.mod to point to the new version for theme
@@ -143,8 +148,9 @@ async def update_go_mod_and_commit(*, github_access_token, new_version, repo_inf
["git", "add", "go.mod"],
cwd=go_mod_repo_path,
)
+ pr_ref = get_pr_ref(pull_request.url)
await check_call(
- ["git", "commit", "-m", f"Update go.mod to reference {name}@{new_version}"],
+ ["git", "commit", "-m", f"Update go.mod to reference {name}@{new_version} from ({pr_ref})"],
cwd=go_mod_repo_path,
)
await check_call(["git", "push"], cwd=go_mod_repo_path)
@@ -164,6 +170,12 @@ async def finish_release(*, github_access_token, repo_info, version, timezone, g
await validate_dependencies()
async with init_working_dir(github_access_token, repo_info.repo_url) as working_dir:
+ org, repo = get_org_and_repo(repo_info.repo_url)
+ pr = await get_release_pr(
+ github_access_token=github_access_token,
+ org=org,
+ repo=repo,
+ )
await check_release_tag(version, root=working_dir)
await set_release_date(version, timezone, root=working_dir)
await merge_release_candidate(root=working_dir)
@@ -176,4 +188,5 @@ async def finish_release(*, github_access_token, repo_info, version, timezone, g
new_version=version,
repo_info=repo_info,
go_mod_repo_url=go_mod_repo_url,
+ pull_request=pr,
)
diff --git a/lib.py b/lib.py
index 272b105..66a60f7 100644
--- a/lib.py
+++ b/lib.py
@@ -427,3 +427,20 @@ def remove_path_from_url(url):
# The docs recommend _replace: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse
updated = parsed._replace(path="", query="", fragment="")
return urlunparse(updated)
+
+
+def get_pr_ref(url):
+ """
+ Convert a HTML link to a github pull request to a shorter piece of text that will still act as a link for github
+
+ Args:
+ url (str): A pull request URL, for example: https://github.com/mitodl/micromasters/pull/2993
+
+ Returns:
+ str: The shorter reference for a pull request. For example: mitodl/micromasters#2993
+ """
+ match = re.match(r".+://github.com/(?P<org>[^/]+)/(?P<repo>[^/]+)/pull/(?P<number>\d+)", url)
+ if not match:
+ raise Exception(f"Unable to parse pull request URL: {url}")
+ org, repo, number = match.group("org"), match.group("repo"), match.group("number")
+ return f"{org}/{repo}#{number}"
|
mitodl/release-script
|
b40b187f5f5470b79b5db25034187689e63ddc29
|
diff --git a/finish_release_test.py b/finish_release_test.py
index 44e54dd..dc6be07 100644
--- a/finish_release_test.py
+++ b/finish_release_test.py
@@ -7,7 +7,10 @@ from pathlib import Path
import pytest
from exception import VersionMismatchException
-from lib import check_call
+from lib import (
+ check_call,
+ ReleasePR,
+)
from release import create_release_notes
from release_test import make_empty_commit
from finish_release import (
@@ -94,6 +97,8 @@ async def test_finish_release(mocker, timezone, test_repo_directory, has_go_mod,
merge_release_mock = mocker.async_patch('finish_release.merge_release')
set_version_date_mock = mocker.async_patch('finish_release.set_release_date')
update_go_mod_and_commit_mock = mocker.async_patch('finish_release.update_go_mod_and_commit')
+ release_pr = ReleasePR('version', 'https://github.com/org/repo/pull/123456', 'body')
+ mocker.async_patch('finish_release.get_release_pr', return_value=release_pr)
go_mod_repo_url = "https://github.com/example-test/repo-with-go-mod.git"
await finish_release(
@@ -116,6 +121,7 @@ async def test_finish_release(mocker, timezone, test_repo_directory, has_go_mod,
new_version=version,
repo_info=test_repo,
go_mod_repo_url=go_mod_repo_url,
+ pull_request=release_pr,
)
else:
assert update_go_mod_and_commit_mock.called is False
@@ -209,6 +215,7 @@ async def test_update_go_mod_and_commit(
new_version=version,
repo_info=library_test_repo,
go_mod_repo_url=go_mod_repo_url,
+ pull_request=ReleasePR('version', 'https://github.com/org/repo/pull/123456', 'body')
)
update_go_mod_mock.assert_called_once_with(
@@ -220,7 +227,7 @@ async def test_update_go_mod_and_commit(
init_working_dir_mock.assert_called_once_with(token, go_mod_repo_url)
if changed:
check_call_mock.assert_any_call(["git", "add", "go.mod"], cwd=Path(go_mod_repo_path))
- message = f"Update go.mod to reference {library_test_repo.name}@{version}"
+ message = f"Update go.mod to reference {library_test_repo.name}@{version} from (org/repo#123456)"
check_call_mock.assert_any_call(["git", "commit", "-m", message], cwd=Path(go_mod_repo_path))
check_call_mock.assert_any_call(["git", "push"], cwd=Path(go_mod_repo_path))
else:
diff --git a/lib_test.py b/lib_test.py
index bed7a11..1be2743 100644
--- a/lib_test.py
+++ b/lib_test.py
@@ -13,6 +13,7 @@ from constants import (
from github import github_auth_headers
from lib import (
get_default_branch,
+ get_pr_ref,
get_release_pr,
get_unchecked_authors,
load_repos_info,
@@ -361,3 +362,8 @@ async def test_get_default_branch(test_repo_directory):
get_default_branch should get master or main, depending on the default branch in the repository
"""
assert await get_default_branch(test_repo_directory) == "master"
+
+
+def test_get_pr_ref():
+ """get_pr_ref should convert a github pull request URL to a shorter reference"""
+ assert get_pr_ref("https://github.com/mitodl/micromasters/pull/2993") == "mitodl/micromasters#2993"
|
Add more context to go.mod commit message
The messages on ocw-course-hugo-starter look like `Update go.mod to reference [email protected]`. We should also add something brief on the changes in ocw-course-hugo-theme, or maybe just link to that PR in the message if that's something github can do
|
0.0
|
b40b187f5f5470b79b5db25034187689e63ddc29
|
[
"finish_release_test.py::test_check_release_tag",
"finish_release_test.py::test_merge_release_candidate",
"finish_release_test.py::test_merge_release",
"finish_release_test.py::test_tag_release",
"finish_release_test.py::test_finish_release[True]",
"finish_release_test.py::test_finish_release[False]",
"finish_release_test.py::test_set_release_date_no_file",
"finish_release_test.py::test_update_go_mod[True]",
"finish_release_test.py::test_update_go_mod[False]",
"finish_release_test.py::test_update_go_mod_and_commit[True]",
"finish_release_test.py::test_update_go_mod_and_commit[False]",
"lib_test.py::test_parse_checkmarks",
"lib_test.py::test_get_release_pr",
"lib_test.py::test_get_release_pr_no_pulls",
"lib_test.py::test_too_many_releases",
"lib_test.py::test_no_release_wrong_repo",
"lib_test.py::test_get_unchecked_authors",
"lib_test.py::test_next_workday_at_10",
"lib_test.py::test_reformatted_full_name",
"lib_test.py::test_match_users",
"lib_test.py::test_url_with_access_token",
"lib_test.py::test_load_repos_info",
"lib_test.py::test_next_versions",
"lib_test.py::test_async_wrapper",
"lib_test.py::test_async_patch",
"lib_test.py::test_remove_path_from_url[https://www.example.com-https://www.example.com]",
"lib_test.py::test_remove_path_from_url[http://mit.edu/a/path-http://mit.edu]",
"lib_test.py::test_remove_path_from_url[http://example.com:5678/?query=params#included-http://example.com:5678]",
"lib_test.py::test_parse_text_matching_options",
"lib_test.py::test_parse_text_matching_options_error",
"lib_test.py::test_get_default_branch",
"lib_test.py::test_get_pr_ref"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-02-16 18:30:53+00:00
|
bsd-3-clause
| 3,974 |
|
miurahr__aqtinstall-364
|
diff --git a/aqt/archives.py b/aqt/archives.py
index 480f5bf..64730c9 100644
--- a/aqt/archives.py
+++ b/aqt/archives.py
@@ -98,19 +98,16 @@ class QtArchives:
else:
for m in modules if modules is not None else []:
self.mod_list.append(
- "qt.qt{0}.{0}{1}{2}.{3}.{4}".format(
+ "qt.qt{0}.{1}.{2}.{3}".format(
self.version.major,
- self.version.minor,
- self.version.patch,
+ self._version_str(),
m,
arch,
)
)
self.mod_list.append(
- "qt.{0}{1}{2}.{3}.{4}".format(
- self.version.major,
- self.version.minor,
- self.version.patch,
+ "qt.{0}.{1}.{2}".format(
+ self._version_str(),
m,
arch,
)
@@ -120,6 +117,11 @@ class QtArchives:
if not all_archives:
self.archives = list(filter(lambda a: a.name in subarchives, self.archives))
+ def _version_str(self) -> str:
+ return ("{0.major}{0.minor}" if self.version == Version("5.9.0") else "{0.major}{0.minor}{0.patch}").format(
+ self.version
+ )
+
def _get_archives(self):
# Get packages index
if self.arch == "wasm_32":
@@ -128,29 +130,25 @@ class QtArchives:
arch_ext = "{}".format(self.arch[7:])
else:
arch_ext = ""
- archive_path = "{0}{1}{2}/qt{3}_{3}{4}{5}{6}/".format(
+ archive_path = "{0}{1}/{2}/qt{3}_{4}{5}/".format(
self.os_name,
- "_x86/" if self.os_name == "windows" else "_x64/",
+ "_x86" if self.os_name == "windows" else "_x64",
self.target,
self.version.major,
- self.version.minor,
- self.version.patch,
+ self._version_str(),
arch_ext,
)
update_xml_url = "{0}{1}Updates.xml".format(self.base, archive_path)
archive_url = "{0}{1}".format(self.base, archive_path)
target_packages = []
target_packages.append(
- "qt.qt{0}.{0}{1}{2}.{3}".format(
+ "qt.qt{0}.{1}.{2}".format(
self.version.major,
- self.version.minor,
- self.version.patch,
+ self._version_str(),
self.arch,
)
)
- target_packages.append(
- "qt.{0}{1}{2}.{3}".format(self.version.major, self.version.minor, self.version.patch, self.arch)
- )
+ target_packages.append("qt.{0}.{1}".format(self._version_str(), self.arch))
target_packages.extend(self.mod_list)
self._download_update_xml(update_xml_url)
self._parse_update_xml(archive_url, target_packages)
diff --git a/aqt/updater.py b/aqt/updater.py
index e8ee446..ca75402 100644
--- a/aqt/updater.py
+++ b/aqt/updater.py
@@ -258,6 +258,7 @@ class Updater:
arch = target.arch
version = Version(target.version)
os_name = target.os_name
+ version_dir = "5.9" if version == Version("5.9.0") else target.version
if arch is None:
arch_dir = ""
elif arch.startswith("win64_mingw"):
@@ -276,9 +277,9 @@ class Updater:
else:
arch_dir = arch
try:
- prefix = pathlib.Path(base_dir) / target.version / arch_dir
+ prefix = pathlib.Path(base_dir) / version_dir / arch_dir
updater = Updater(prefix, logger)
- updater.set_license(base_dir, target.version, arch_dir)
+ updater.set_license(base_dir, version_dir, arch_dir)
if target.arch not in [
"ios",
"android",
@@ -288,7 +289,7 @@ class Updater:
"android_x86",
"android_armv7",
]: # desktop version
- updater.make_qtconf(base_dir, target.version, arch_dir)
+ updater.make_qtconf(base_dir, version_dir, arch_dir)
updater.patch_qmake()
if target.os_name == "linux":
updater.patch_pkgconfig("/home/qt/work/install", target.os_name)
@@ -297,14 +298,14 @@ class Updater:
updater.patch_pkgconfig("/Users/qt/work/install", target.os_name)
updater.patch_libtool("/Users/qt/work/install/lib", target.os_name)
elif target.os_name == "windows":
- updater.make_qtenv2(base_dir, target.version, arch_dir)
- if Version(target.version) < Version("5.14.0"):
+ updater.make_qtenv2(base_dir, version_dir, arch_dir)
+ if version < Version("5.14.0"):
updater.patch_qtcore(target)
- elif Version(target.version) in SimpleSpec(">=5.0,<6.0"):
+ elif version in SimpleSpec(">=5.0,<6.0"):
updater.patch_qmake()
else: # qt6 non-desktop
- updater.patch_qmake_script(base_dir, target.version, target.os_name)
- updater.patch_target_qt_conf(base_dir, target.version, arch_dir, target.os_name)
+ updater.patch_qmake_script(base_dir, version_dir, target.os_name)
+ updater.patch_target_qt_conf(base_dir, version_dir, arch_dir, target.os_name)
except IOError as e:
raise e
diff --git a/ci/generate_azure_pipelines_matrices.py b/ci/generate_azure_pipelines_matrices.py
index fd07338..4651e18 100644
--- a/ci/generate_azure_pipelines_matrices.py
+++ b/ci/generate_azure_pipelines_matrices.py
@@ -44,6 +44,14 @@ class BuildJob:
self.spec = spec
self.output_dir = output_dir
+ def qt_bindir(self, *, sep='/') -> str:
+ out_dir = f"$(Build.BinariesDirectory){sep}Qt" if not self.output_dir else self.output_dir
+ version_dir = "5.9" if self.qt_version == "5.9.0" else self.qt_version
+ return f"{out_dir}{sep}{version_dir}{sep}{self.archdir}{sep}bin"
+
+ def win_qt_bindir(self) -> str:
+ return self.qt_bindir(sep='\\')
+
class PlatformBuildJobs:
def __init__(self, platform, build_jobs):
@@ -130,6 +138,16 @@ windows_build_jobs.extend(
module="qtcharts qtnetworkauth",
mirror=random.choice(MIRRORS),
),
+ BuildJob(
+ "install-qt",
+ "5.9.0",
+ "windows",
+ "desktop",
+ "win64_msvc2017_64",
+ "msvc2017_64",
+ module="qtcharts qtnetworkauth",
+ mirror=random.choice(MIRRORS),
+ ),
]
)
@@ -281,24 +299,8 @@ for platform_build_job in all_platform_build_jobs:
("HAS_EXTENSIONS", build_job.list_options.get("HAS_EXTENSIONS", "False")),
("USE_EXTENSION", build_job.list_options.get("USE_EXTENSION", "None")),
("OUTPUT_DIR", build_job.output_dir if build_job.output_dir else ""),
- (
- "QT_BINDIR",
- "{0}/{1.qt_version}/{1.archdir}/bin".format(
- "$(Build.BinariesDirectory)/Qt"
- if not build_job.output_dir
- else build_job.output_dir,
- build_job,
- ),
- ),
- (
- "WIN_QT_BINDIR",
- "{0}\\{1.qt_version}\\{1.archdir}\\bin".format(
- "$(Build.BinariesDirectory)\\Qt"
- if not build_job.output_dir
- else build_job.output_dir,
- build_job,
- ),
- ),
+ ("QT_BINDIR", build_job.qt_bindir()),
+ ("WIN_QT_BINDIR", build_job.win_qt_bindir()),
]
)
|
miurahr/aqtinstall
|
dd0b42bd72a49c5f361ccff582662411912392a9
|
diff --git a/tests/test_install.py b/tests/test_install.py
index 44f9032..5e2fa9b 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -86,7 +86,7 @@ def make_mock_geturl_download_archive(
def mock_getUrl(url: str, *args) -> str:
if url.endswith(updates_url):
- qt_major_nodot = f"qt{qt_version[0]}.{qt_version.replace('.', '')}"
+ qt_major_nodot = "59" if qt_version == "5.9.0" else f"qt{qt_version[0]}.{qt_version.replace('.', '')}"
_xml = textwrap.dedent(
f"""\
<Updates>
@@ -122,7 +122,8 @@ def make_mock_geturl_download_archive(
full_path.parent.mkdir(parents=True)
full_path.write_text(file[UNPATCHED_CONTENT], "utf_8")
- archive.writeall(path=temp_path, arcname=qt_version)
+ archive_name = "5.9" if qt_version == "5.9.0" else qt_version
+ archive.writeall(path=temp_path, arcname=archive_name)
return mock_getUrl, mock_download_archive
@@ -178,6 +179,66 @@ def disable_sockets_and_multiprocessing(monkeypatch):
r"Time elapsed: .* second"
),
),
+ (
+ "install 5.9.0 windows desktop win32_mingw53".split(),
+ "windows",
+ "desktop",
+ "5.9.0",
+ "win32_mingw53",
+ "mingw53_32",
+ "windows_x86/desktop/qt5_59/Updates.xml",
+ (
+ {
+ FILENAME: "mkspecs/qconfig.pri",
+ UNPATCHED_CONTENT: "... blah blah blah ...\n"
+ "QT_EDITION = Not OpenSource\n"
+ "QT_LICHECK = Not Empty\n"
+ "... blah blah blah ...\n",
+ PATCHED_CONTENT: "... blah blah blah ...\n"
+ "QT_EDITION = OpenSource\n"
+ "QT_LICHECK =\n"
+ "... blah blah blah ...\n",
+ },
+ ),
+ re.compile(
+ r"^aqtinstall\(aqt\) v.* on Python 3.*\n"
+ r"Warning: The command 'install' is deprecated and marked for removal in a future version of aqt.\n"
+ r"In the future, please use the command 'install-qt' instead.\n"
+ r"Downloading qtbase...\n"
+ r"Finished installation of qtbase-windows-win32_mingw53.7z in .*\n"
+ r"Finished installation\n"
+ r"Time elapsed: .* second"
+ ),
+ ),
+ (
+ "install-qt windows desktop 5.9.0 win32_mingw53".split(),
+ "windows",
+ "desktop",
+ "5.9.0",
+ "win32_mingw53",
+ "mingw53_32",
+ "windows_x86/desktop/qt5_59/Updates.xml",
+ (
+ {
+ FILENAME: "mkspecs/qconfig.pri",
+ UNPATCHED_CONTENT: "... blah blah blah ...\n"
+ "QT_EDITION = Not OpenSource\n"
+ "QT_LICHECK = Not Empty\n"
+ "... blah blah blah ...\n",
+ PATCHED_CONTENT: "... blah blah blah ...\n"
+ "QT_EDITION = OpenSource\n"
+ "QT_LICHECK =\n"
+ "... blah blah blah ...\n",
+ },
+ ),
+ re.compile(
+ r"^aqtinstall\(aqt\) v.* on Python 3.*\n"
+ r"Downloading qtbase...\n"
+ r"Finished installation of qtbase-windows-win32_mingw53.7z in .*\n"
+ r"Finished installation\n"
+ r"Time elapsed: .* second"
+ ),
+ ),
(
"install-qt windows desktop 5.14.0 win32_mingw73".split(),
"windows",
@@ -289,6 +350,8 @@ def test_install(
assert expect_out.match(err)
installed_path = Path(output_dir) / version / arch_dir
+ if version == "5.9.0":
+ installed_path = Path(output_dir) / "5.9" / arch_dir
assert installed_path.is_dir()
for patched_file in files:
file_path = installed_path / patched_file[FILENAME]
|
Qt 5.9 installation was broken at some point
`aqt install 5.9 linux desktop` returns "Invalid version string: '5.9'"
Qt 5.9 has a weird package name but it is hosted: https://download.qt.io/online/qtsdkrepository/linux_x64/desktop/qt5_59/
This worked in 1.1.3 but is broken in 1.2.x, as I discovered when trying to update the version.
https://github.com/jurplel/install-qt-action/runs/3303265869
|
0.0
|
dd0b42bd72a49c5f361ccff582662411912392a9
|
[
"tests/test_install.py::test_install[cmd1-windows-desktop-5.9.0-win32_mingw53-mingw53_32-windows_x86/desktop/qt5_59/Updates.xml-files1-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.9.0-win32_mingw53-mingw53_32-windows_x86/desktop/qt5_59/Updates.xml-files2-^aqtinstall\\\\(aqt\\\\)"
] |
[
"tests/test_install.py::test_install[cmd0-windows-desktop-5.14.0-win32_mingw73-mingw73_32-windows_x86/desktop/qt5_5140/Updates.xml-files0-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.14.0-win32_mingw73-mingw73_32-windows_x86/desktop/qt5_5140/Updates.xml-files3-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd4-windows-android-6.1.0-android_armv7-android_armv7-windows_x86/android/qt6_610_armv7/Updates.xml-files4-^aqtinstall\\\\(aqt\\\\)"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-08-11 18:42:49+00:00
|
mit
| 3,975 |
|
miurahr__aqtinstall-414
|
diff --git a/aqt/archives.py b/aqt/archives.py
index 3c06d8c..2874747 100644
--- a/aqt/archives.py
+++ b/aqt/archives.py
@@ -371,6 +371,7 @@ class ToolArchives(QtArchives):
self.tool_name = tool_name
self.os_name = os_name
self.logger = getLogger("aqt.archives")
+ self.is_require_version_match = version_str is not None
super(ToolArchives, self).__init__(
os_name=os_name,
target=target,
@@ -421,6 +422,9 @@ class ToolArchives(QtArchives):
name = packageupdate.find("Name").text
named_version = packageupdate.find("Version").text
+ if self.is_require_version_match and named_version != self.version:
+ message = f"The package '{self.arch}' has the version '{named_version}', not the requested '{self.version}'."
+ raise NoPackageFound(message, suggested_action=self.help_msg())
package_desc = packageupdate.find("Description").text
downloadable_archives = packageupdate.find("DownloadableArchives").text
if not downloadable_archives:
diff --git a/aqt/installer.py b/aqt/installer.py
index 1500705..2059c0e 100644
--- a/aqt/installer.py
+++ b/aqt/installer.py
@@ -66,7 +66,7 @@ class Cli:
def __init__(self):
parser = argparse.ArgumentParser(
prog="aqt",
- description="Another unofficial Qt Installer.\n" "aqt helps you install Qt SDK, tools, examples and others\n",
+ description="Another unofficial Qt Installer.\naqt helps you install Qt SDK, tools, examples and others\n",
formatter_class=argparse.RawTextHelpFormatter,
add_help=True,
)
@@ -84,11 +84,7 @@ class Cli:
"commands {install|tool|src|examples|doc} are deprecated and marked for removal\n",
help="Please refer to each help message by using '--help' with each subcommand",
)
- self._make_install_parsers(subparsers)
- self._make_list_qt_parser(subparsers)
- self._make_list_tool_parser(subparsers)
- self._make_legacy_parsers(subparsers)
- self._make_common_parsers(subparsers)
+ self._make_all_parsers(subparsers)
parser.set_defaults(func=self.show_help)
self.parser = parser
@@ -388,7 +384,7 @@ class Cli:
self._warn_on_deprecated_command("tool", "install-tool")
tool_name = args.tool_name # such as tools_openssl_x64
os_name = args.host # windows, linux and mac
- target = args.target # desktop, android and ios
+ target = "desktop" if args.is_legacy else args.target # desktop, android and ios
output_dir = args.outputdir
if output_dir is None:
base_dir = os.getcwd()
@@ -398,7 +394,8 @@ class Cli:
if EXT7Z and sevenzip is None:
# override when py7zr is not exist
sevenzip = self._set_sevenzip(Settings.zipcmd)
- version = "0.0.1" # just store a dummy version
+ version = getattr(args, "version", "0.0.1") # for legacy aqt tool
+ Cli._validate_version_str(version)
keep = args.keep
if args.base is not None:
base = args.base
@@ -408,7 +405,7 @@ class Cli:
timeout = (args.timeout, args.timeout)
else:
timeout = (Settings.connection_timeout, Settings.response_timeout)
- if args.arch is None:
+ if args.tool_variant is None:
archive_id = ArchiveId("tools", os_name, target, "")
meta = MetadataFactory(archive_id, is_latest_version=True, tool_name=tool_name)
try:
@@ -418,7 +415,7 @@ class Cli:
raise ArchiveListError(msg, suggested_action=suggested_follow_up(meta)) from e
else:
- archs = [args.arch]
+ archs = [args.tool_variant]
for arch in archs:
if not self._check_tools_arg_combination(os_name, tool_name, arch):
@@ -541,71 +538,67 @@ class Cli:
def _set_install_tool_parser(self, install_tool_parser, *, is_legacy: bool):
install_tool_parser.set_defaults(func=self.run_install_tool, is_legacy=is_legacy)
install_tool_parser.add_argument("host", choices=["linux", "mac", "windows"], help="host os name")
- install_tool_parser.add_argument(
- "target",
- default=None,
- choices=["desktop", "winrt", "android", "ios"],
- help="Target SDK.",
- )
+ if not is_legacy:
+ install_tool_parser.add_argument(
+ "target",
+ default=None,
+ choices=["desktop", "winrt", "android", "ios"],
+ help="Target SDK.",
+ )
install_tool_parser.add_argument("tool_name", help="Name of tool such as tools_ifw, tools_mingw")
+ if is_legacy:
+ install_tool_parser.add_argument("version", help="Version of tool variant")
+
+ tool_variant_opts = {} if is_legacy else {"nargs": "?", "default": None}
install_tool_parser.add_argument(
- "arch",
- nargs="?",
- default=None,
- help="Name of full tool name such as qt.tools.ifw.31. "
+ "tool_variant",
+ **tool_variant_opts,
+ help="Name of tool variant, such as qt.tools.ifw.41. "
"Please use 'aqt list-tool' to list acceptable values for this parameter.",
)
self._set_common_options(install_tool_parser)
- def _make_legacy_parsers(self, subparsers: argparse._SubParsersAction):
- deprecated_msg = "This command is deprecated and marked for removal in a future version of aqt."
- install_parser = subparsers.add_parser(
- "install",
- description=deprecated_msg,
- formatter_class=argparse.RawTextHelpFormatter,
- )
- self._set_install_qt_parser(install_parser, is_legacy=True)
- tool_parser = subparsers.add_parser("tool")
- self._set_install_tool_parser(tool_parser, is_legacy=True)
- #
- for cmd, f in (
- ("doc", self.run_install_doc),
- ("example", self.run_install_example),
- ("src", self.run_install_src),
- ):
- p = subparsers.add_parser(cmd, description=deprecated_msg)
- p.set_defaults(func=f, is_legacy=True)
- self._set_common_arguments(p, is_legacy=True)
- self._set_common_options(p)
- self._set_module_options(p)
-
def _warn_on_deprecated_command(self, old_name: str, new_name: str):
self.logger.warning(
f"Warning: The command '{old_name}' is deprecated and marked for removal in a future version of aqt.\n"
f"In the future, please use the command '{new_name}' instead."
)
- def _make_install_parsers(self, subparsers: argparse._SubParsersAction):
- install_qt_parser = subparsers.add_parser("install-qt", formatter_class=argparse.RawTextHelpFormatter)
- self._set_install_qt_parser(install_qt_parser, is_legacy=False)
- tool_parser = subparsers.add_parser("install-tool")
- self._set_install_tool_parser(tool_parser, is_legacy=False)
- #
- for cmd, f in (
- ("install-doc", self.run_install_doc),
- ("install-example", self.run_install_example),
- ):
- p = subparsers.add_parser(cmd)
- p.set_defaults(func=f, is_legacy=False)
- self._set_common_arguments(p, is_legacy=False)
- self._set_common_options(p)
- self._set_module_options(p)
- src_parser = subparsers.add_parser("install-src")
- src_parser.set_defaults(func=self.run_install_src, is_legacy=False)
- self._set_common_arguments(src_parser, is_legacy=False)
- self._set_common_options(src_parser)
- self._set_module_options(src_parser)
- src_parser.add_argument("--kde", action="store_true", help="patching with KDE patch kit.")
+ def _make_all_parsers(self, subparsers: argparse._SubParsersAction):
+ deprecated_msg = "This command is deprecated and marked for removal in a future version of aqt."
+
+ def make_parser_it(cmd: str, desc: str, is_legacy: bool, set_parser_cmd, formatter_class):
+ description = f"{desc} {deprecated_msg}" if is_legacy else desc
+ kwargs = {"formatter_class": formatter_class} if formatter_class else {}
+ p = subparsers.add_parser(cmd, description=description, **kwargs)
+ set_parser_cmd(p, is_legacy=is_legacy)
+
+ def make_parser_sde(cmd: str, desc: str, is_legacy: bool, action, is_add_kde: bool):
+ description = f"{desc} {deprecated_msg}" if is_legacy else desc
+ parser = subparsers.add_parser(cmd, description=description)
+ parser.set_defaults(func=action, is_legacy=is_legacy)
+ self._set_common_arguments(parser, is_legacy=is_legacy)
+ self._set_common_options(parser)
+ self._set_module_options(parser)
+ if is_add_kde:
+ parser.add_argument("--kde", action="store_true", help="patching with KDE patch kit.")
+
+ make_parser_it("install-qt", "Install Qt.", False, self._set_install_qt_parser, argparse.RawTextHelpFormatter)
+ make_parser_it("install-tool", "Install tools.", False, self._set_install_tool_parser, None)
+ make_parser_sde("install-doc", "Install documentation.", False, self.run_install_doc, False)
+ make_parser_sde("install-example", "Install examples.", False, self.run_install_example, False)
+ make_parser_sde("install-src", "Install source.", False, self.run_install_src, True)
+
+ self._make_list_qt_parser(subparsers)
+ self._make_list_tool_parser(subparsers)
+
+ make_parser_it("install", "Install Qt.", True, self._set_install_qt_parser, argparse.RawTextHelpFormatter)
+ make_parser_it("tool", "Install tools.", True, self._set_install_tool_parser, None)
+ make_parser_sde("doc", "Install documentation.", True, self.run_install_doc, False)
+ make_parser_sde("examples", "Install examples.", True, self.run_install_example, False)
+ make_parser_sde("src", "Install source.", True, self.run_install_src, True)
+
+ self._make_common_parsers(subparsers)
def _make_list_qt_parser(self, subparsers: argparse._SubParsersAction):
"""Creates a subparser that works with the MetadataFactory, and adds it to the `subparsers` parameter"""
|
miurahr/aqtinstall
|
372113fe9df9dbe0ec0d943fe64b08a06daec554
|
diff --git a/tests/test_archives.py b/tests/test_archives.py
index 66020e0..af52a9f 100644
--- a/tests/test_archives.py
+++ b/tests/test_archives.py
@@ -232,6 +232,38 @@ def test_tools_variants(monkeypatch, tool_name, tool_variant_name, is_expect_fai
assert len(expected_7z_files) == 0, f"Failed to produce QtPackages for {expected_7z_files}"
+def to_xml(package_updates: Iterable[Dict]) -> str:
+ def wrap(tag: str, content: str, is_multiline: bool = True):
+ newline = "\n" if is_multiline else ""
+ return f"<{tag}>{newline}{content}{newline}</{tag}>"
+
+ return wrap(
+ "Updates",
+ "\n".join(
+ [
+ wrap("PackageUpdate", "\n".join([wrap(key, value, False) for key, value in pu.items()]))
+ for pu in package_updates
+ ]
+ ),
+ )
+
+
[email protected](
+ "tool_name, variant_name, version, actual_version",
+ (("tools_qtcreator", "qt.tools.qtcreator", "1.2.3", "3.2.1"),),
+)
+def test_tool_archive_wrong_version(monkeypatch, tool_name, variant_name, version, actual_version):
+ def _mock(self, *args):
+ self.update_xml_text = to_xml([dict(Name=variant_name, Version=actual_version)])
+
+ monkeypatch.setattr(QtArchives, "_download_update_xml", _mock)
+
+ host, target, base = "mac", "desktop", "https://example.com"
+ with pytest.raises(NoPackageFound) as e:
+ ToolArchives(host, target, tool_name, base, version_str=version, arch=variant_name)
+ assert e.type == NoPackageFound
+
+
# Test the helper class
def test_module_to_package():
qt_base_names = ["qt.999.clang", "qt9.999.clang", "qt9.999.addon.clang"]
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 4d90566..09427ca 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -14,7 +14,7 @@ def expected_help():
return (
"usage: aqt [-h] [-c CONFIG]\n"
" {install-qt,install-tool,install-doc,install-example,install-src,list-qt,list-tool,"
- "install,tool,doc,example,src,help,version}\n"
+ "install,tool,doc,examples,src,help,version}\n"
" ...\n"
"\n"
"Another unofficial Qt Installer.\n"
@@ -33,7 +33,7 @@ def expected_help():
" commands {install|tool|src|examples|doc} are deprecated and marked for removal\n"
"\n"
" {install-qt,install-tool,install-doc,install-example,install-src,list-qt,list-tool,"
- "install,tool,doc,example,src,help,version}\n"
+ "install,tool,doc,examples,src,help,version}\n"
" Please refer to each help message by using '--help' with each subcommand\n"
)
@@ -218,6 +218,74 @@ def test_cli_input_errors(capsys, expected_help, cmd, expect_msg, should_show_he
assert err.rstrip().endswith(expect_msg)
+# These commands use the new syntax with the legacy commands
[email protected](
+ "cmd",
+ (
+ "install linux desktop 5.10.0",
+ "install linux desktop 5.10.0 gcc_64",
+ "src linux desktop 5.10.0",
+ "doc linux desktop 5.10.0",
+ "example linux desktop 5.10.0",
+ "tool windows desktop tools_ifw",
+ ),
+)
+def test_cli_legacy_commands_with_wrong_syntax(cmd):
+ cli = Cli()
+ cli._setup_settings()
+ with pytest.raises(SystemExit) as e:
+ cli.run(cmd.split())
+ assert e.type == SystemExit
+
+
[email protected](
+ "cmd",
+ (
+ "tool windows desktop tools_ifw qt.tools.ifw.31", # New syntax
+ "tool windows desktop tools_ifw 1.2.3",
+ ),
+)
+def test_cli_legacy_tool_new_syntax(monkeypatch, capsys, cmd):
+ # These incorrect commands cannot be filtered out directly by argparse because
+ # they have the correct number of arguments.
+ command = cmd.split()
+
+ expected = (
+ "Warning: The command 'tool' is deprecated and marked for removal in a future version of aqt.\n"
+ "In the future, please use the command 'install-tool' instead.\n"
+ "Invalid version: 'tools_ifw'! Please use the form '5.X.Y'.\n"
+ )
+
+ cli = Cli()
+ cli._setup_settings()
+ assert 1 == cli.run(command)
+ out, err = capsys.readouterr()
+ actual = err[err.index("\n") + 1 :]
+ assert actual == expected
+
+
+# These commands come directly from examples in the legacy documentation
[email protected](
+ "cmd",
+ (
+ "install 5.10.0 linux desktop", # default arch
+ "install 5.10.2 linux android android_armv7",
+ "src 5.15.2 windows desktop --archives qtbase --kde",
+ "doc 5.15.2 windows desktop -m qtcharts qtnetworkauth",
+ "examples 5.15.2 windows desktop -m qtcharts qtnetworkauth",
+ "tool linux tools_ifw 4.0 qt.tools.ifw.40",
+ ),
+)
+def test_cli_legacy_commands_with_correct_syntax(monkeypatch, cmd):
+ # Pretend to install correctly when any command is run
+ for func in ("run_install_qt", "run_install_src", "run_install_doc", "run_install_example", "run_install_tool"):
+ monkeypatch.setattr(Cli, func, lambda *args, **kwargs: 0)
+
+ cli = Cli()
+ cli._setup_settings()
+ assert 0 == cli.run(cmd.split())
+
+
def test_cli_unexpected_error(monkeypatch, capsys):
def _mocked_run(*args):
raise RuntimeError("Some unexpected error")
|
Keeping v1 commands available in v2 may confuse users
## Overview
In [Legacy subcommands § Command Line Options — aqtinstall 2.0.0 documentation](https://aqtinstall.readthedocs.io/en/v2.0.0/cli.html#legacy-subcommands), we wrote:
> The subcommands `install`, `tool`, `src`, `doc`, and `examples` have been deprecated in favor of the newer `install-*` commands, but they remain in aqt in case you still need to use them.
After reading the above paragraph, I will think *"Fine, 'aqt tool' is still there. Those guys are keeping two series of commands in v2. I don't have to update my script after upgrading aqtinstall"*. However, the reality is that after switching to v2, the old script will **NOT** work without modification, at least for the "tool" command.
## Test
A working example for installing QIFW by aqtinstall 1.2.5:
```console
$ aqt tool linux tools_ifw 4.1.1 qt.tools.ifw.41
Specified target combination is not valid: linux tools_ifw qt.tools.ifw.41
...
Time elapsed: 8.37262754 second
```
The same script does not work in 2.0.0:
```console
$ aqt tool linux tools_ifw 4.1.1 qt.tools.ifw.41
usage: aqt tool ...
...
aqt tool: error: argument target: invalid choice: 'tools_ifw' (choose from 'desktop', 'winrt', 'android', 'ios')
Error: Process completed with exit code 2.
```
Rewrite the script according to the documentation of "[install-tool](https://aqtinstall.readthedocs.io/en/v2.0.0/cli.html#install-tool-command)" but keep the *legacy* "tool" command. It works in 2.0.0:
```diff
- aqt tool linux tools_ifw 4.1.1 qt.tools.ifw.41
+ aqt tool linux desktop tools_ifw
```
```console
$ aqt tool linux desktop tools_ifw
aqtinstall(aqt) v2.0.0 on Python 3.8.10 [CPython GCC 9.4.0]
Warning: The command 'tool' is deprecated and marked for removal in a future version of aqt.
In the future, please use the command 'install-tool' instead.
...
Time elapsed: 11.00345962 second
```
Add the "tool variant name":
```diff
- aqt tool linux desktop tools_ifw
+ aqt tool linux desktop tools_ifw qt.tools.ifw.41
```
```console
$ aqt tool linux desktop tools_ifw qt.tools.ifw.41
aqtinstall(aqt) v2.0.0 on Python 3.8.10 [CPython GCC 9.4.0]
Warning: The command 'tool' is deprecated and marked for removal in a future version of aqt.
In the future, please use the command 'install-tool' instead.
...
Time elapsed: 9.82558412 second
```
*Use the command 'install-tool' instead*:
```diff
- aqt tool linux desktop tools_ifw qt.tools.ifw.41
+ aqt install-tool linux desktop tools_ifw qt.tools.ifw.41
```
```console
$ aqt install-tool linux desktop tools_ifw qt.tools.ifw.41
aqtinstall(aqt) v2.0.0 on Python 3.8.10 [CPython GCC 9.4.0]
...
Time elapsed: 11.23552921 second
```
## Conclusion
As you can see, in aqtinstall v2, "tool" is not a legacy subcommand but **another name** of "install-tool". Those old interfaces have been changed, so keeping them available in v2 may confuse users.
I really know that the API changes can be (or should be) made in a new major release, but we didn't keep the availability and compatibility for those legacy commands, and what's worse is that we didn't document it correctly and clearly.
## Ignorable possible solutions
Here are some expensive ways to solve this problem:
- Remove those legacy commands in the next major version and release this new version as soon as possible. Yes, aqtinstall v3.
- Or, make those legacy commands usable again in the next minor version of v2. In other words, keep two series (v1 and v2) of commands in aqtinstall ^v2.1.
|
0.0
|
372113fe9df9dbe0ec0d943fe64b08a06daec554
|
[
"tests/test_archives.py::test_tool_archive_wrong_version[tools_qtcreator-qt.tools.qtcreator-1.2.3-3.2.1]",
"tests/test_cli.py::test_cli_help",
"tests/test_cli.py::test_cli_input_errors[install-qt",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[tool",
"tests/test_cli.py::test_cli_legacy_tool_new_syntax[tool",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[src",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[examples",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[tool"
] |
[
"tests/test_archives.py::test_parse_update_xml[windows-5.15.0-win64_msvc2019_64-windows-5150-update.xml]",
"tests/test_archives.py::test_parse_update_xml[windows-5.15.0-win64_mingw81-windows-5150-update.xml]",
"tests/test_archives.py::test_parse_update_xml[windows-5.14.0-win64_mingw73-windows-5140-update.xml]",
"tests/test_archives.py::test_qtarchive_parse_corrupt_xmlfile[QtArchives-init_args0]",
"tests/test_archives.py::test_qtarchive_parse_corrupt_xmlfile[ToolArchives-init_args1]",
"tests/test_archives.py::test_qt_archives_modules[win32_mingw73-requested_module_names0-False]",
"tests/test_archives.py::test_qt_archives_modules[win32_mingw73-requested_module_names1-False]",
"tests/test_archives.py::test_qt_archives_modules[win32_msvc2017-requested_module_names2-False]",
"tests/test_archives.py::test_qt_archives_modules[win64_mingw73-requested_module_names3-False]",
"tests/test_archives.py::test_qt_archives_modules[win64_msvc2015_64-requested_module_names4-False]",
"tests/test_archives.py::test_qt_archives_modules[win64_msvc2017_64-requested_module_names5-False]",
"tests/test_archives.py::test_qt_archives_modules[win64_msvc2017_64-requested_module_names6-False]",
"tests/test_archives.py::test_qt_archives_modules[win32_mingw73-requested_module_names7-True]",
"tests/test_archives.py::test_qt_archives_modules[win64_mingw73-requested_module_names8-True]",
"tests/test_archives.py::test_qt_archives_modules[win64_msvc2015_64-requested_module_names9-True]",
"tests/test_archives.py::test_tools_variants[tools_qtcreator-qt.tools.qtcreator-False]",
"tests/test_archives.py::test_tools_variants[tools_qtcreator-qt.tools.qtcreatordbg-False]",
"tests/test_archives.py::test_tools_variants[tools_qtcreator-qt.tools.qtcreatordev-False]",
"tests/test_archives.py::test_tools_variants[tools_qtcreator-qt.tools.qtifw-True]",
"tests/test_archives.py::test_module_to_package",
"tests/test_cli.py::test_cli_check_module",
"tests/test_cli.py::test_cli_check_combination",
"tests/test_cli.py::test_cli_check_version",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-6.1-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5.12-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5.13-expected_version2-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5-expected_version3-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-<5.14.5-expected_version4-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-mingw32-6.0-expected_version5-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-winrt-mingw32-6-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-winrt-mingw32-bad",
"tests/test_cli.py::test_cli_determine_qt_version[windows-android-android_x86-6-expected_version8-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-android_x86-6-expected_version9-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-android_fake-6-expected_version10-False]",
"tests/test_cli.py::test_cli_invalid_version[5.15]",
"tests/test_cli.py::test_cli_invalid_version[five-dot-fifteen]",
"tests/test_cli.py::test_cli_invalid_version[5]",
"tests/test_cli.py::test_cli_invalid_version[5.5.5.5]",
"tests/test_cli.py::test_cli_check_mirror",
"tests/test_cli.py::test_set_arch[None-windows-desktop-6.2.0-None]",
"tests/test_cli.py::test_set_arch[-windows-desktop-6.2.0-None]",
"tests/test_cli.py::test_set_arch[None-linux-desktop-6.2.0-gcc_64]",
"tests/test_cli.py::test_set_arch[None-mac-desktop-6.2.0-clang_64]",
"tests/test_cli.py::test_set_arch[None-mac-ios-6.2.0-ios]",
"tests/test_cli.py::test_set_arch[None-mac-android-6.2.0-android]",
"tests/test_cli.py::test_set_arch[None-mac-android-5.12.0-None]",
"tests/test_cli.py::test_cli_input_errors[install-src",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[install",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[src",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[doc",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[example",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[install",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[doc",
"tests/test_cli.py::test_cli_unexpected_error",
"tests/test_cli.py::test_cli_set_7zip"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-09-30 16:47:45+00:00
|
mit
| 3,976 |
|
miurahr__aqtinstall-443
|
diff --git a/aqt/archives.py b/aqt/archives.py
index 0792044..bfc7bfb 100644
--- a/aqt/archives.py
+++ b/aqt/archives.py
@@ -373,11 +373,11 @@ class ToolArchives(QtArchives):
self.tool_name = tool_name
self.os_name = os_name
self.logger = getLogger("aqt.archives")
- self.is_require_version_match = version_str is not None
+ self.tool_version_str: Optional[str] = version_str
super(ToolArchives, self).__init__(
os_name=os_name,
target=target,
- version_str=version_str or "0.0.1", # dummy value
+ version_str="0.0.1", # dummy value
arch=arch,
base=base,
timeout=timeout,
@@ -424,7 +424,7 @@ class ToolArchives(QtArchives):
name = packageupdate.find("Name").text
named_version = packageupdate.find("Version").text
- if self.is_require_version_match and named_version != self.version:
+ if self.tool_version_str and named_version != self.tool_version_str:
message = f"The package '{self.arch}' has the version '{named_version}', not the requested '{self.version}'."
raise NoPackageFound(message, suggested_action=self.help_msg())
package_desc = packageupdate.find("Description").text
diff --git a/aqt/installer.py b/aqt/installer.py
index 9beddca..cc42402 100644
--- a/aqt/installer.py
+++ b/aqt/installer.py
@@ -402,8 +402,9 @@ class Cli:
if EXT7Z and sevenzip is None:
# override when py7zr is not exist
sevenzip = self._set_sevenzip(Settings.zipcmd)
- version = getattr(args, "version", "0.0.1") # for legacy aqt tool
- Cli._validate_version_str(version)
+ version = getattr(args, "version", None)
+ if version is not None:
+ Cli._validate_version_str(version, allow_minus=True)
keep = args.keep
if args.base is not None:
base = args.base
@@ -807,10 +808,23 @@ class Cli:
Settings.load_settings()
@staticmethod
- def _validate_version_str(version_str: str, *, allow_latest: bool = False, allow_empty: bool = False):
+ def _validate_version_str(
+ version_str: str, *, allow_latest: bool = False, allow_empty: bool = False, allow_minus: bool = False
+ ) -> None:
+ """
+ Raise CliInputError if the version is not an acceptable Version.
+
+ :param version_str: The version string to check.
+ :param allow_latest: If true, the string "latest" is acceptable.
+ :param allow_empty: If true, the empty string is acceptable.
+ :param allow_minus: If true, everything after the first '-' in the version will be ignored.
+ This allows acceptance of versions like "1.2.3-0-202101020304"
+ """
if (allow_latest and version_str == "latest") or (allow_empty and not version_str):
return
try:
+ if "-" in version_str and allow_minus:
+ version_str = version_str[: version_str.find("-")]
Version(version_str)
except ValueError as e:
raise CliInputError(f"Invalid version: '{version_str}'! Please use the form '5.X.Y'.") from e
diff --git a/ci/generate_azure_pipelines_matrices.py b/ci/generate_azure_pipelines_matrices.py
index 8000029..79778a5 100644
--- a/ci/generate_azure_pipelines_matrices.py
+++ b/ci/generate_azure_pipelines_matrices.py
@@ -5,6 +5,7 @@ import collections
import json
import random
from itertools import product
+from typing import Dict, Optional
MIRRORS = [
"https://ftp.jaist.ac.jp/pub/qtproject",
@@ -29,6 +30,7 @@ class BuildJob:
output_dir=None,
list_options=None,
spec=None,
+ tool_options: Optional[Dict[str, str]] = None,
):
self.command = command
self.qt_version = qt_version
@@ -40,6 +42,7 @@ class BuildJob:
self.mirror = mirror
self.subarchives = subarchives
self.list_options = list_options if list_options else {}
+ self.tool_options: Dict[str, str] = tool_options if tool_options else {}
# `steps.yml` assumes that qt_version is the highest version that satisfies spec
self.spec = spec
self.output_dir = output_dir
@@ -276,6 +279,33 @@ linux_build_jobs.extend(
]
)
+qt_creator_bin_path = "./Tools/QtCreator/bin/"
+qt_creator_mac_bin_path = "./Qt Creator.app/Contents/MacOS/"
+qt_ifw_bin_path = "./Tools/QtInstallerFramework/4.1/bin/"
+tool_options = {
+ "TOOL1_ARGS": "tools_qtcreator qt.tools.qtcreator",
+ "LIST_TOOL1_CMD": f"ls {qt_creator_bin_path}",
+ "TEST_TOOL1_CMD": f"{qt_creator_bin_path}qbs --version",
+ "TOOL2_ARGS": "tools_ifw",
+ "TEST_TOOL2_CMD": f"{qt_ifw_bin_path}archivegen --version",
+ "LIST_TOOL2_CMD": f"ls {qt_ifw_bin_path}",
+}
+# Mac Qt Creator is a .app, or "Package Bundle", so the path is changed:
+tool_options_mac = {
+ **tool_options,
+ "TEST_TOOL1_CMD": f'"{qt_creator_mac_bin_path}qbs" --version',
+ "LIST_TOOL1_CMD": f'ls "{qt_creator_mac_bin_path}"',
+}
+windows_build_jobs.append(
+ BuildJob("install-tool", "", "windows", "desktop", "", "", tool_options=tool_options)
+)
+linux_build_jobs.append(
+ BuildJob("install-tool", "", "linux", "desktop", "", "", tool_options=tool_options)
+)
+mac_build_jobs.append(
+ BuildJob("install-tool", "", "mac", "desktop", "", "", tool_options=tool_options_mac)
+)
+
matrices = {}
for platform_build_job in all_platform_build_jobs:
@@ -313,6 +343,12 @@ for platform_build_job in all_platform_build_jobs:
("OUTPUT_DIR", build_job.output_dir if build_job.output_dir else ""),
("QT_BINDIR", build_job.qt_bindir()),
("WIN_QT_BINDIR", build_job.win_qt_bindir()),
+ ("TOOL1_ARGS", build_job.tool_options.get("TOOL1_ARGS", "")),
+ ("LIST_TOOL1_CMD", build_job.tool_options.get("LIST_TOOL1_CMD", "")),
+ ("TEST_TOOL1_CMD", build_job.tool_options.get("TEST_TOOL1_CMD", "")),
+ ("TOOL2_ARGS", build_job.tool_options.get("TOOL2_ARGS", "")),
+ ("LIST_TOOL2_CMD", build_job.tool_options.get("LIST_TOOL2_CMD", "")),
+ ("TEST_TOOL2_CMD", build_job.tool_options.get("TEST_TOOL2_CMD", "")),
]
)
diff --git a/ci/steps.yml b/ci/steps.yml
index ba6fcdb..0550716 100644
--- a/ci/steps.yml
+++ b/ci/steps.yml
@@ -7,6 +7,13 @@ steps:
pip install -e .
displayName: install package
+ # Install linux dependencies
+ - bash: |
+ sudo apt-get update
+ sudo apt-get install -y libgl1-mesa-dev libxkbcommon-x11-0
+ condition: and(eq(variables['TARGET'], 'desktop'), eq(variables['Agent.OS'], 'Linux'))
+ displayName: install test dependency for Linux
+
# Run Aqt
##----------------------------------------------------
## we insert sleep in random 1sec < duration < 60sec to reduce
@@ -108,6 +115,22 @@ steps:
if [[ "$(SUBCOMMAND)" == "install-doc" ]]; then
python -m aqt $(SUBCOMMAND) $(HOST) $(TARGET) $(QT_VERSION) --archives $(SUBARCHIVES)
fi
+ if [[ "$(SUBCOMMAND)" == "install-tool" ]]; then
+ opt=""
+ if [[ "$(OUTPUT_DIR)" != "" ]]; then
+ opt+=" --outputdir $(OUTPUT_DIR)"
+ sudo mkdir -p "$(OUTPUT_DIR)"
+ sudo chown $(whoami) "$(OUTPUT_DIR)"
+ fi
+ python -m aqt $(SUBCOMMAND) $(HOST) $(TARGET) $(TOOL1_ARGS) $opt
+ $(LIST_TOOL1_CMD)
+ echo "Testing $(TOOL1_ARGS) with '$(TEST_TOOL1_CMD)'"
+ $(TEST_TOOL1_CMD)
+ python -m aqt $(SUBCOMMAND) $(HOST) $(TARGET) $(TOOL2_ARGS) $opt
+ $(LIST_TOOL2_CMD)
+ echo "Testing $(TOOL2_ARGS) with '$(TEST_TOOL2_CMD)'"
+ $(TEST_TOOL2_CMD)
+ fi
workingDirectory: $(Build.BinariesDirectory)
env:
AQT_CONFIG: $(Build.SourcesDirectory)/ci/settings.ini
@@ -132,15 +155,9 @@ steps:
export PATH=$(QT_BINDIR):$PATH
qmake $(Build.BinariesDirectory)/tests/accelbubble
make
- condition: and(eq(variables['TARGET'], 'android'), or(eq(variables['Agent.OS'], 'Linux'), eq(variables['Agent.OS'], 'Darwin')), ne(variables['SUBCOMMAND'], 'list'))
+ condition: and(eq(variables['TARGET'], 'android'), or(eq(variables['Agent.OS'], 'Linux'), eq(variables['Agent.OS'], 'Darwin')), ne(variables['SUBCOMMAND'], 'list'), ne(variables['SUBCOMMAND'], 'install-tool'))
displayName: Build accelbubble example application to test for android
- - script: |
- sudo apt-get update
- sudo apt-get install -y libgl1-mesa-dev
- condition: and(eq(variables['TARGET'], 'desktop'), eq(variables['Agent.OS'], 'Linux'), eq(variables['SUBCOMMAND'], 'install-qt'))
- displayName: install test dependency for Linux
-
##----------------------------------------------------
# determine Windows build system
- powershell: |
@@ -169,7 +186,7 @@ steps:
}
cd $(WIN_QT_BINDIR)
unzip $(Build.SourcesDirectory)\ci\jom_1_1_3.zip
- condition: eq( variables['Agent.OS'], 'Windows_NT')
+ condition: and(eq( variables['Agent.OS'], 'Windows_NT'), eq(variables['SUBCOMMAND'], 'install-qt'))
displayName: Detect toolchain for Windows and update PATH
# When no modules
@@ -195,9 +212,19 @@ steps:
} elseif ( $env:TOOLCHAIN -eq 'MINGW' ) {
if ( $env:ARCH -eq 'win64_mingw81' ) {
python -m aqt install-tool --outputdir $(Build.BinariesDirectory)/Qt $(HOST) desktop tools_mingw qt.tools.win64_mingw810
+ if ($?) {
+ Write-Host 'Successfully installed tools_mingw'
+ } else {
+ throw 'Failed to install tools_mingw'
+ }
[Environment]::SetEnvironmentVariable("Path", ";$(Build.BinariesDirectory)\Qt\Tools\mingw810_64\bin" + $env:Path, "Machine")
} else {
python -m aqt install-tool --outputdir $(Build.BinariesDirectory)/Qt $(HOST) desktop tools_mingw qt.tools.win32_mingw810
+ if ($?) {
+ Write-Host 'Successfully installed tools_mingw'
+ } else {
+ throw 'Failed to install tools_mingw'
+ }
[Environment]::SetEnvironmentVariable("Path", ";$(Build.BinariesDirectory)\Qt\Tools\mingw810_32\bin" + $env:Path, "Machine")
}
$env:Path = "$(Build.BinariesDirectory)\Qt\Tools\$(ARCHDIR)\bin;$(WIN_QT_BINDIR);" + $env:Path
@@ -208,7 +235,7 @@ steps:
qmake $(Build.BinariesDirectory)\tests\helloworld
mingw32-make
}
- condition: and(eq( variables['Agent.OS'], 'Windows_NT'), eq(variables['MODULE'], ''))
+ condition: and(eq( variables['Agent.OS'], 'Windows_NT'), eq(variables['MODULE'], ''), eq(variables['SUBCOMMAND'], 'install-qt'))
displayName: build test with qmake w/o extra module
- powershell: |
Import-VisualStudioVars -VisualStudioVersion $(VSVER) -Architecture $(ARCHITECTURE)
|
miurahr/aqtinstall
|
4235e78327187eba52dbefa5a4952c97b04318b2
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 64c2d73..3b1d533 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -150,6 +150,28 @@ def test_cli_invalid_version(capsys, invalid_version):
assert matcher.match(err)
[email protected](
+ "version, allow_latest, allow_empty, allow_minus, expect_ok",
+ (
+ ("1.2.3", False, False, False, True),
+ ("1.2.", False, False, False, False),
+ ("latest", True, False, False, True),
+ ("latest", False, False, False, False),
+ ("", False, True, False, True),
+ ("", False, False, False, False),
+ ("1.2.3-0-123", False, False, True, True),
+ ("1.2.3-0-123", False, False, False, False),
+ ),
+)
+def test_cli_validate_version(version: str, allow_latest: bool, allow_empty: bool, allow_minus: bool, expect_ok: bool):
+ if expect_ok:
+ Cli._validate_version_str(version, allow_latest=allow_latest, allow_empty=allow_empty, allow_minus=allow_minus)
+ else:
+ with pytest.raises(CliInputError) as err:
+ Cli._validate_version_str(version, allow_latest=allow_latest, allow_empty=allow_empty, allow_minus=allow_minus)
+ assert err.type == CliInputError
+
+
def test_cli_check_mirror():
cli = Cli()
cli._setup_settings()
diff --git a/tests/test_install.py b/tests/test_install.py
index 0fbe6c1..6284914 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -91,13 +91,14 @@ class MockArchive:
version: str = ""
arch_dir: str = ""
should_install: bool = True
+ date: datetime = datetime.now()
def xml_package_update(self) -> str:
return textwrap.dedent(
f"""\
<PackageUpdate>
<Name>{self.update_xml_name}</Name>
- <Version>{self.version}-0-{datetime.now().strftime("%Y%m%d%H%M")}</Version>
+ <Version>{self.version}-0-{self.date.strftime("%Y%m%d%H%M")}</Version>
<Description>none</Description>
<DownloadableArchives>{self.filename_7z}</DownloadableArchives>
</PackageUpdate>"""
@@ -253,9 +254,65 @@ def plain_qtbase_archive(update_xml_name: str, arch: str, should_install: bool =
)
+def tool_archive(host: str, tool_name: str, variant: str, date: datetime = datetime.now()) -> MockArchive:
+ return MockArchive(
+ filename_7z=f"{tool_name}-{host}-{variant}.7z",
+ update_xml_name=variant,
+ contents=(
+ PatchedFile(
+ filename=f"bin/{tool_name}-{variant}.exe",
+ unpatched_content="Some executable binary file",
+ patched_content=None, # it doesn't get patched
+ ),
+ ),
+ should_install=True,
+ date=date,
+ )
+
+
@pytest.mark.parametrize(
"cmd, host, target, version, arch, arch_dir, updates_url, archives, expect_out",
(
+ (
+ "install-tool linux desktop tools_qtcreator qt.tools.qtcreator".split(),
+ "linux",
+ "desktop",
+ "1.2.3-0-197001020304",
+ "",
+ "",
+ "linux_x64/desktop/tools_qtcreator/Updates.xml",
+ [
+ tool_archive("linux", "tools_qtcreator", "qt.tools.qtcreator"),
+ ],
+ re.compile(
+ r"^aqtinstall\(aqt\) v.* on Python 3.*\n"
+ r"Downloading qt.tools.qtcreator...\n"
+ r"Finished installation of tools_qtcreator-linux-qt.tools.qtcreator.7z in .*\n"
+ r"Finished installation\n"
+ r"Time elapsed: .* second"
+ ),
+ ),
+ (
+ "tool linux tools_qtcreator 1.2.3-0-197001020304 qt.tools.qtcreator".split(),
+ "linux",
+ "desktop",
+ "1.2.3",
+ "",
+ "",
+ "linux_x64/desktop/tools_qtcreator/Updates.xml",
+ [
+ tool_archive("linux", "tools_qtcreator", "qt.tools.qtcreator", datetime(1970, 1, 2, 3, 4, 5, 6)),
+ ],
+ re.compile(
+ r"^aqtinstall\(aqt\) v.* on Python 3.*\n"
+ r"Warning: The command 'tool' is deprecated and marked for removal in a future version of aqt.\n"
+ r"In the future, please use the command 'install-tool' instead.\n"
+ r"Downloading qt.tools.qtcreator...\n"
+ r"Finished installation of tools_qtcreator-linux-qt.tools.qtcreator.7z in .*\n"
+ r"Finished installation\n"
+ r"Time elapsed: .* second"
+ ),
+ ),
(
"install 5.14.0 windows desktop win32_mingw73".split(),
"windows",
|
Cannot install qtcreator tool (any version)
I have been trying for several hours different variations of commands to install the qtcreator ide. These are the results:
### Simple install
```sh
$ aqt install-tool linux desktop tools_qtcreator
```
Error: The package 'qt.tools.qtcreator' has the version '5.0.2-0-202109300244', not the requested '0.0.1'.
### Specify the variant
```sh
$ aqt install-tool linux desktop tools_qtcreator qt.tools.qtcreator
```
Error: The package 'qt.tools.qtcreator' has the version '5.0.2-0-202109300244', not the requested '0.0.1'.
### Using the version number
```
$ aqt install-tool linux desktop 5.2
```
Error: Specified target combination is not valid: linux 5.2 tools_qtcreator
Failed to locate XML data for the tool '5.2'.
What is the right way to do this?
|
0.0
|
4235e78327187eba52dbefa5a4952c97b04318b2
|
[
"tests/test_cli.py::test_cli_validate_version[1.2.3-False-False-False-True]",
"tests/test_cli.py::test_cli_validate_version[1.2.-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[latest-True-False-False-True]",
"tests/test_cli.py::test_cli_validate_version[latest-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[-False-True-False-True]",
"tests/test_cli.py::test_cli_validate_version[-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[1.2.3-0-123-False-False-True-True]",
"tests/test_cli.py::test_cli_validate_version[1.2.3-0-123-False-False-False-False]",
"tests/test_install.py::test_install[cmd0-linux-desktop-1.2.3-0-197001020304---linux_x64/desktop/tools_qtcreator/Updates.xml-archives0-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd1-linux-desktop-1.2.3---linux_x64/desktop/tools_qtcreator/Updates.xml-archives1-^aqtinstall\\\\(aqt\\\\)"
] |
[
"tests/test_cli.py::test_cli_help",
"tests/test_cli.py::test_cli_check_module",
"tests/test_cli.py::test_cli_check_combination",
"tests/test_cli.py::test_cli_check_version",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-6.1-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5.12-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5.13-expected_version2-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5-expected_version3-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-<5.14.5-expected_version4-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-mingw32-6.0-expected_version5-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-winrt-mingw32-6-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-winrt-mingw32-bad",
"tests/test_cli.py::test_cli_determine_qt_version[windows-android-android_x86-6-expected_version8-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-android_x86-6-expected_version9-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-android_fake-6-expected_version10-False]",
"tests/test_cli.py::test_cli_invalid_version[5.15]",
"tests/test_cli.py::test_cli_invalid_version[five-dot-fifteen]",
"tests/test_cli.py::test_cli_invalid_version[5]",
"tests/test_cli.py::test_cli_invalid_version[5.5.5.5]",
"tests/test_cli.py::test_cli_check_mirror",
"tests/test_cli.py::test_set_arch[impossible_arch-windows-desktop-6.2.0-impossible_arch]",
"tests/test_cli.py::test_set_arch[-windows-desktop-6.2.0-None]",
"tests/test_cli.py::test_set_arch[None-windows-desktop-6.2.0-None]",
"tests/test_cli.py::test_set_arch[None-linux-desktop-6.2.0-gcc_64]",
"tests/test_cli.py::test_set_arch[None-mac-desktop-6.2.0-clang_64]",
"tests/test_cli.py::test_set_arch[None-mac-ios-6.2.0-ios]",
"tests/test_cli.py::test_set_arch[None-mac-android-6.2.0-android]",
"tests/test_cli.py::test_set_arch[None-mac-android-5.12.0-None]",
"tests/test_cli.py::test_set_arch[impossible_arch-windows-desktop-6.2-impossible_arch]",
"tests/test_cli.py::test_set_arch[-windows-desktop-6.2-None]",
"tests/test_cli.py::test_set_arch[None-windows-desktop-6.2-None]",
"tests/test_cli.py::test_set_arch[None-linux-desktop-6.2-gcc_64]",
"tests/test_cli.py::test_set_arch[None-mac-desktop-6.2-clang_64]",
"tests/test_cli.py::test_set_arch[None-mac-ios-6.2-ios]",
"tests/test_cli.py::test_set_arch[None-mac-android-6.2-None]",
"tests/test_cli.py::test_cli_input_errors[install-qt",
"tests/test_cli.py::test_cli_input_errors[install-src",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[install",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[src",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[doc",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[example",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[tool",
"tests/test_cli.py::test_cli_legacy_tool_new_syntax[tool",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[install",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[src",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[doc",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[examples",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[tool",
"tests/test_cli.py::test_cli_unexpected_error",
"tests/test_cli.py::test_cli_set_7zip",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.14.0-win32_mingw73-mingw73_32-windows_x86/desktop/qt5_5140/Updates.xml-archives2-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.9.0-win32_mingw53-mingw53_32-windows_x86/desktop/qt5_59/Updates.xml-archives3-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd4-windows-desktop-5.9.0-win32_mingw53-mingw53_32-windows_x86/desktop/qt5_59/Updates.xml-archives4-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd5-windows-desktop-5.14.0-win32_mingw73-mingw73_32-windows_x86/desktop/qt5_5140/Updates.xml-archives5-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd6-windows-desktop-5.14.0-win64_mingw73-mingw73_64-windows_x86/desktop/qt5_5140/Updates.xml-archives6-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd7-windows-desktop-6.2.0-win64_mingw73-mingw73_64-windows_x86/desktop/qt6_620/Updates.xml-archives7-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd8-windows-desktop-6.1.0-win64_mingw81-mingw81_64-windows_x86/desktop/qt6_610/Updates.xml-archives8-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd9-windows-android-6.1.0-android_armv7-android_armv7-windows_x86/android/qt6_610_armv7/Updates.xml-archives9-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install_nonexistent_archives[install-qt",
"tests/test_install.py::test_install_nonexistent_archives[install-src",
"tests/test_install.py::test_install_nonexistent_archives[install-tool",
"tests/test_install.py::test_install_pool_exception[RuntimeError()-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_pool_exception[KeyboardInterrupt()-../aqt/settings.ini-Caught",
"tests/test_install.py::test_install_pool_exception[MemoryError()-../aqt/settings.ini-Caught",
"tests/test_install.py::test_install_pool_exception[MemoryError()-data/settings_no_concurrency.ini-Caught",
"tests/test_install.py::test_install_installer_archive_extraction_err"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-10-30 23:31:25+00:00
|
mit
| 3,977 |
|
miurahr__aqtinstall-458
|
diff --git a/aqt/helper.py b/aqt/helper.py
index 2e3b74f..ecb98eb 100644
--- a/aqt/helper.py
+++ b/aqt/helper.py
@@ -79,7 +79,7 @@ def getUrl(url: str, timeout) -> str:
return result
-def downloadBinaryFile(url: str, out: str, hash_algo: str, exp: bytes, timeout):
+def downloadBinaryFile(url: str, out: Path, hash_algo: str, exp: bytes, timeout):
logger = getLogger("aqt.helper")
filename = Path(url).name
with requests.Session() as session:
@@ -114,7 +114,7 @@ def downloadBinaryFile(url: str, out: str, hash_algo: str, exp: bytes, timeout):
raise ArchiveChecksumError(
f"Downloaded file {filename} is corrupted! Detect checksum error.\n"
f"Expect {exp.hex()}: {url}\n"
- f"Actual {hash.digest().hex()}: {out}"
+ f"Actual {hash.digest().hex()}: {out.name}"
)
@@ -305,6 +305,14 @@ class SettingsClass:
result = record["modules"]
return result
+ @property
+ def archive_download_location(self):
+ return self.config.get("aqt", "archive_download_location", fallback=".")
+
+ @property
+ def always_keep_archives(self):
+ return self.config.getboolean("aqt", "always_keep_archives", fallback=False)
+
@property
def concurrency(self):
"""concurrency configuration.
diff --git a/aqt/installer.py b/aqt/installer.py
index cc42402..64d295e 100644
--- a/aqt/installer.py
+++ b/aqt/installer.py
@@ -33,6 +33,8 @@ import sys
import time
from logging import getLogger
from logging.handlers import QueueHandler
+from pathlib import Path
+from tempfile import TemporaryDirectory
from typing import Any, Callable, List, Optional
import aqt
@@ -219,6 +221,24 @@ class Cli:
getLogger("aqt.installer").info(f"Resolved spec '{qt_version_or_spec}' to {version}")
return version
+ @staticmethod
+ def choose_archive_dest(archive_dest: Optional[str], keep: bool, temp_dir: str) -> Path:
+ """
+ Choose archive download destination, based on context.
+
+ There are three potential behaviors here:
+ 1. By default, return a temp directory that will be removed on program exit.
+ 2. If the user has asked to keep archives, but has not specified a destination,
+ we return Settings.archive_download_location ("." by default).
+ 3. If the user has asked to keep archives and specified a destination,
+ we create the destination dir if it doesn't exist, and return that directory.
+ """
+ if not archive_dest:
+ return Path(Settings.archive_download_location if keep else temp_dir)
+ dest = Path(archive_dest)
+ dest.mkdir(parents=True, exist_ok=True)
+ return dest
+
def run_install_qt(self, args):
"""Run install subcommand"""
start_time = time.perf_counter()
@@ -235,7 +255,8 @@ class Cli:
else:
qt_version: str = args.qt_version
Cli._validate_version_str(qt_version)
- keep = args.keep
+ keep: bool = args.keep or Settings.always_keep_archives
+ archive_dest: Optional[str] = args.archive_dest
output_dir = args.outputdir
if output_dir is None:
base_dir = os.getcwd()
@@ -295,7 +316,9 @@ class Cli:
base,
)
target_config = qt_archives.get_target_config()
- run_installer(qt_archives.get_packages(), base_dir, sevenzip, keep)
+ with TemporaryDirectory() as temp_dir:
+ _archive_dest = Cli.choose_archive_dest(archive_dest, keep, temp_dir)
+ run_installer(qt_archives.get_packages(), base_dir, sevenzip, keep, _archive_dest)
if not nopatch:
Updater.update(target_config, base_dir)
self.logger.info("Finished installation")
@@ -320,7 +343,8 @@ class Cli:
base_dir = os.getcwd()
else:
base_dir = output_dir
- keep = args.keep
+ keep: bool = args.keep or Settings.always_keep_archives
+ archive_dest: Optional[str] = args.archive_dest
if args.base is not None:
base = args.base
else:
@@ -353,7 +377,9 @@ class Cli:
),
base,
)
- run_installer(srcdocexamples_archives.get_packages(), base_dir, sevenzip, keep)
+ with TemporaryDirectory() as temp_dir:
+ _archive_dest = Cli.choose_archive_dest(archive_dest, keep, temp_dir)
+ run_installer(srcdocexamples_archives.get_packages(), base_dir, sevenzip, keep, _archive_dest)
self.logger.info("Finished installation")
def run_install_src(self, args):
@@ -405,7 +431,8 @@ class Cli:
version = getattr(args, "version", None)
if version is not None:
Cli._validate_version_str(version, allow_minus=True)
- keep = args.keep
+ keep: bool = args.keep or Settings.always_keep_archives
+ archive_dest: Optional[str] = args.archive_dest
if args.base is not None:
base = args.base
else:
@@ -442,7 +469,9 @@ class Cli:
),
base,
)
- run_installer(tool_archives.get_packages(), base_dir, sevenzip, keep)
+ with TemporaryDirectory() as temp_dir:
+ _archive_dest = Cli.choose_archive_dest(archive_dest, keep, temp_dir)
+ run_installer(tool_archives.get_packages(), base_dir, sevenzip, keep, _archive_dest)
self.logger.info("Finished installation")
self.logger.info("Time elapsed: {time:.8f} second".format(time=time.perf_counter() - start_time))
@@ -767,6 +796,13 @@ class Cli:
action="store_true",
help="Keep downloaded archive when specified, otherwise remove after install",
)
+ subparser.add_argument(
+ "-d",
+ "--archive-dest",
+ type=str,
+ default=None,
+ help="Set the destination path for downloaded archives (temp directory by default).",
+ )
def _set_module_options(self, subparser):
subparser.add_argument("-m", "--modules", nargs="*", help="Specify extra modules to install")
@@ -838,14 +874,14 @@ class Cli:
return function(fallback_url)
-def run_installer(archives: List[QtPackage], base_dir: str, sevenzip: Optional[str], keep: bool):
+def run_installer(archives: List[QtPackage], base_dir: str, sevenzip: Optional[str], keep: bool, archive_dest: Path):
queue = multiprocessing.Manager().Queue(-1)
listener = MyQueueListener(queue)
listener.start()
#
tasks = []
for arc in archives:
- tasks.append((arc, base_dir, sevenzip, queue, keep))
+ tasks.append((arc, base_dir, sevenzip, queue, archive_dest, keep))
ctx = multiprocessing.get_context("spawn")
pool = ctx.Pool(Settings.concurrency, init_worker_sh)
@@ -896,6 +932,7 @@ def installer(
base_dir: str,
command: Optional[str],
queue: multiprocessing.Queue,
+ archive_dest: Path,
keep: bool = False,
response_timeout: Optional[int] = None,
):
@@ -906,7 +943,7 @@ def installer(
name = qt_archive.name
url = qt_archive.archive_url
hashurl = qt_archive.hashurl
- archive = qt_archive.archive
+ archive: Path = archive_dest / qt_archive.archive
start_time = time.perf_counter()
# set defaults
Settings.load_settings()
@@ -943,10 +980,10 @@ def installer(
"-bd",
"-y",
"-o{}".format(base_dir),
- archive,
+ str(archive),
]
else:
- command_args = [command, "x", "-aoa", "-bd", "-y", archive]
+ command_args = [command, "x", "-aoa", "-bd", "-y", str(archive)]
try:
proc = subprocess.run(command_args, stdout=subprocess.PIPE, check=True)
logger.debug(proc.stdout)
@@ -955,7 +992,7 @@ def installer(
raise ArchiveExtractionError(msg) from cpe
if not keep:
os.unlink(archive)
- logger.info("Finished installation of {} in {:.8f}".format(archive, time.perf_counter() - start_time))
+ logger.info("Finished installation of {} in {:.8f}".format(archive.name, time.perf_counter() - start_time))
qh.flush()
qh.close()
logger.removeHandler(qh)
diff --git a/aqt/settings.ini b/aqt/settings.ini
index 4748cee..d165c08 100644
--- a/aqt/settings.ini
+++ b/aqt/settings.ini
@@ -5,6 +5,8 @@ concurrency: 4
baseurl: https://download.qt.io
7zcmd: 7z
print_stacktrace_on_error: False
+always_keep_archives: False
+archive_download_location: .
[requests]
connection_timeout: 3.5
diff --git a/docs/cli.rst b/docs/cli.rst
index b29db53..463a0fc 100644
--- a/docs/cli.rst
+++ b/docs/cli.rst
@@ -239,7 +239,20 @@ are described here:
.. option:: --keep, -k
- Keep downloaded archive when specified, otherwise remove after install
+ Keep downloaded archive when specified, otherwise remove after install.
+ Use ``--archive-dest <path>`` to choose where aqt will place these files.
+ If you do not specify a download destination, aqt will place these files in
+ the current working directory.
+
+.. option:: --archive-dest <path>
+
+ Set the destination path for downloaded archives (temp directory by default).
+ All downloaded archives will be automatically deleted unless you have
+ specified the ``--keep`` option above, or ``aqt`` crashes.
+
+ Note that this option refers to the intermediate ``.7z`` archives that ``aqt``
+ downloads and then extracts to ``--outputdir``.
+ Most users will not need to keep these files.
.. option:: --modules, -m (<list of modules> | all)
@@ -295,6 +308,7 @@ install-qt command
[-E | --external <7zip command>]
[--internal]
[-k | --keep]
+ [-d | --archive-dest] <path>
[-m | --modules (all | <module> [<module>...])]
[--archives <archive> [<archive>...]]
[--noarchives]
@@ -368,6 +382,7 @@ install-src command
[-E | --external <7zip command>]
[--internal]
[-k | --keep]
+ [-d | --archive-dest] <path>
[-m | --modules (all | <module> [<module>...])]
[--archives <archive> [<archive>...]]
[--kde]
@@ -425,6 +440,7 @@ install-doc command
[-E | --external <7zip command>]
[--internal]
[-k | --keep]
+ [-d | --archive-dest] <path>
[-m | --modules (all | <module> [<module>...])]
[--archives <archive> [<archive>...]]
<host> <target> (<Qt version> | <spec>)
@@ -473,6 +489,7 @@ install-example command
[-E | --external <7zip command>]
[--internal]
[-k | --keep]
+ [-d | --archive-dest] <path>
[-m | --modules (all | <module> [<module>...])]
[--archives <archive> [<archive>...]]
<host> <target> (<Qt version> | <spec>)
@@ -525,6 +542,7 @@ install-tool command
[-E | --external <7zip command>]
[--internal]
[-k | --keep]
+ [-d | --archive-dest] <path>
<host> <target> <tool name> [<tool variant name>]
Install tools like QtIFW, mingw, Cmake, Conan, and vcredist.
diff --git a/docs/configuration.rst b/docs/configuration.rst
index 9cb9572..f9dba17 100644
--- a/docs/configuration.rst
+++ b/docs/configuration.rst
@@ -20,6 +20,8 @@ A file is like as follows:
baseurl: https://download.qt.io
7zcmd: 7z
print_stacktrace_on_error: False
+ always_keep_archives: False
+ archive_download_location: .
[requests]
connection_timeout: 3.5
@@ -71,6 +73,18 @@ print_stacktrace_on_error:
The ``False`` setting will hide the stack trace, unless an unhandled
exception occurs.
+always_keep_archives:
+ This is either ``True`` or ``False``.
+ The ``True`` setting turns on the ``--keep`` option every time you run aqt,
+ and cannot be overridden by command line options.
+ The ``False`` setting will require you to set ``--keep`` manually every time
+ you run aqt, unless you don't want to keep ``.7z`` archives.
+
+archive_download_location:
+ This is the relative or absolute path to the location in which ``.7z`` archives
+ will be downloaded, when ``--keep`` is turned on.
+ You can override this location with the ``--archives-dest`` option.
+
The ``[requests]`` section controls the way that ``aqt`` makes network requests.
|
miurahr/aqtinstall
|
d63bbd146c6852b81caca72ab6abe9aa8c2962f2
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 3b1d533..260d75b 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -351,3 +351,26 @@ def test_cli_set_7zip(monkeypatch):
cli._set_sevenzip("some_nonexistent_binary")
assert err.type == CliInputError
assert format(err.value) == "Specified 7zip command executable does not exist: 'some_nonexistent_binary'"
+
+
[email protected](
+ "archive_dest, keep, temp_dir, expect, should_make_dir",
+ (
+ (None, False, "temp", "temp", False),
+ (None, True, "temp", ".", False),
+ ("my_archives", False, "temp", "my_archives", True),
+ ("my_archives", True, "temp", "my_archives", True),
+ ),
+)
+def test_cli_choose_archive_dest(
+ monkeypatch, archive_dest: Optional[str], keep: bool, temp_dir: str, expect: str, should_make_dir: bool
+):
+ enclosed = {"made_dir": False}
+
+ def mock_mkdir(*args, **kwargs):
+ enclosed["made_dir"] = True
+
+ monkeypatch.setattr("aqt.installer.Path.mkdir", mock_mkdir)
+
+ assert Cli.choose_archive_dest(archive_dest, keep, temp_dir) == Path(expect)
+ assert enclosed["made_dir"] == should_make_dir
diff --git a/tests/test_helper.py b/tests/test_helper.py
index fe7666e..eef302e 100644
--- a/tests/test_helper.py
+++ b/tests/test_helper.py
@@ -127,10 +127,10 @@ def test_helper_downloadBinary_wrong_checksum(tmp_path, monkeypatch):
expected_err = (
f"Downloaded file test.xml is corrupted! Detect checksum error."
f"\nExpect {wrong_hash.hex()}: {url}"
- f"\nActual {actual_hash.hex()}: {out}"
+ f"\nActual {actual_hash.hex()}: {out.name}"
)
with pytest.raises(ArchiveChecksumError) as e:
- helper.downloadBinaryFile(url, str(out), "md5", wrong_hash, 60)
+ helper.downloadBinaryFile(url, out, "md5", wrong_hash, 60)
assert e.type == ArchiveChecksumError
assert format(e.value) == expected_err
diff --git a/tests/test_install.py b/tests/test_install.py
index 6284914..e0229ab 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -146,11 +146,11 @@ def make_mock_geturl_download_archive(
def locate_archive() -> MockArchive:
for arc in archives:
- if out == arc.filename_7z:
+ if Path(out).name == arc.filename_7z:
return arc
assert False, "Requested an archive that was not mocked"
- locate_archive().write_compressed_archive(Path("./"))
+ locate_archive().write_compressed_archive(Path(out).parent)
return mock_getUrl, mock_download_archive
@@ -731,6 +731,7 @@ def test_install_installer_archive_extraction_err(monkeypatch):
base_dir=temp_dir,
command="some_nonexistent_7z_extractor",
queue=MockMultiprocessingManager.Queue(),
+ archive_dest=Path(temp_dir),
)
assert err.type == ArchiveExtractionError
err_msg = format(err.value).rstrip()
|
Feature: specify the download location of 7z archives
I am a little unclear on why we are downloading to the working directory in the first place. If the user happens to have files in the working directory with the same names as the archives downloaded, these files will be overwritten and then deleted. Additionally, if `aqt` fails before finishing this process, the working directory will be littered with `.7z` files that may or may not be partially downloaded.
I think it might be more respectful of the user's disk space to use a temporary directory to download these files. A temp directory would delete itself automatically when the program ends, whether an error occurs of not. However, this would make it more difficult to attempt to recover an unfinished installation.
Originally posted by @ddalcino in https://github.com/miurahr/aqtinstall/pull/420#discussion_r721494482
|
0.0
|
d63bbd146c6852b81caca72ab6abe9aa8c2962f2
|
[
"tests/test_cli.py::test_cli_choose_archive_dest[None-False-temp-temp-False]",
"tests/test_cli.py::test_cli_choose_archive_dest[None-True-temp-.-False]",
"tests/test_cli.py::test_cli_choose_archive_dest[my_archives-False-temp-my_archives-True]",
"tests/test_cli.py::test_cli_choose_archive_dest[my_archives-True-temp-my_archives-True]",
"tests/test_helper.py::test_helper_downloadBinary_wrong_checksum",
"tests/test_install.py::test_install_installer_archive_extraction_err"
] |
[
"tests/test_cli.py::test_cli_help",
"tests/test_cli.py::test_cli_check_module",
"tests/test_cli.py::test_cli_check_combination",
"tests/test_cli.py::test_cli_check_version",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-6.1-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5.12-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5.13-expected_version2-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5-expected_version3-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-<5.14.5-expected_version4-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-mingw32-6.0-expected_version5-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-winrt-mingw32-6-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-winrt-mingw32-bad",
"tests/test_cli.py::test_cli_determine_qt_version[windows-android-android_x86-6-expected_version8-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-android_x86-6-expected_version9-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-android_fake-6-expected_version10-False]",
"tests/test_cli.py::test_cli_invalid_version[5.15]",
"tests/test_cli.py::test_cli_invalid_version[five-dot-fifteen]",
"tests/test_cli.py::test_cli_invalid_version[5]",
"tests/test_cli.py::test_cli_invalid_version[5.5.5.5]",
"tests/test_cli.py::test_cli_validate_version[1.2.3-False-False-False-True]",
"tests/test_cli.py::test_cli_validate_version[1.2.-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[latest-True-False-False-True]",
"tests/test_cli.py::test_cli_validate_version[latest-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[-False-True-False-True]",
"tests/test_cli.py::test_cli_validate_version[-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[1.2.3-0-123-False-False-True-True]",
"tests/test_cli.py::test_cli_validate_version[1.2.3-0-123-False-False-False-False]",
"tests/test_cli.py::test_cli_check_mirror",
"tests/test_cli.py::test_set_arch[impossible_arch-windows-desktop-6.2.0-impossible_arch]",
"tests/test_cli.py::test_set_arch[-windows-desktop-6.2.0-None]",
"tests/test_cli.py::test_set_arch[None-windows-desktop-6.2.0-None]",
"tests/test_cli.py::test_set_arch[None-linux-desktop-6.2.0-gcc_64]",
"tests/test_cli.py::test_set_arch[None-mac-desktop-6.2.0-clang_64]",
"tests/test_cli.py::test_set_arch[None-mac-ios-6.2.0-ios]",
"tests/test_cli.py::test_set_arch[None-mac-android-6.2.0-android]",
"tests/test_cli.py::test_set_arch[None-mac-android-5.12.0-None]",
"tests/test_cli.py::test_set_arch[impossible_arch-windows-desktop-6.2-impossible_arch]",
"tests/test_cli.py::test_set_arch[-windows-desktop-6.2-None]",
"tests/test_cli.py::test_set_arch[None-windows-desktop-6.2-None]",
"tests/test_cli.py::test_set_arch[None-linux-desktop-6.2-gcc_64]",
"tests/test_cli.py::test_set_arch[None-mac-desktop-6.2-clang_64]",
"tests/test_cli.py::test_set_arch[None-mac-ios-6.2-ios]",
"tests/test_cli.py::test_set_arch[None-mac-android-6.2-None]",
"tests/test_cli.py::test_cli_input_errors[install-qt",
"tests/test_cli.py::test_cli_input_errors[install-src",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[install",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[src",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[doc",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[example",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[tool",
"tests/test_cli.py::test_cli_legacy_tool_new_syntax[tool",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[install",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[src",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[doc",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[examples",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[tool",
"tests/test_cli.py::test_cli_unexpected_error",
"tests/test_cli.py::test_cli_set_7zip",
"tests/test_helper.py::test_helper_altlink",
"tests/test_helper.py::test_settings",
"tests/test_helper.py::test_helper_downloadBinary_md5",
"tests/test_helper.py::test_helper_downloadBinary_sha256",
"tests/test_helper.py::test_helper_downloadBinary_connection_err[mock_exception0-Connection",
"tests/test_helper.py::test_helper_downloadBinary_connection_err[mock_exception1-Connection",
"tests/test_helper.py::test_helper_downloadBinary_response_error_undefined",
"tests/test_helper.py::test_helper_retry_on_error[2-5]",
"tests/test_helper.py::test_helper_retry_on_error[5-5]",
"tests/test_helper.py::test_helper_retry_on_error[5-2]",
"tests/test_helper.py::test_helper_to_version_permissive[1.33.1-expect0]",
"tests/test_helper.py::test_helper_to_version_permissive[1.33.1-202102101246-expect1]",
"tests/test_helper.py::test_helper_to_version_permissive[1.33-202102101246-expect2]",
"tests/test_helper.py::test_helper_to_version_permissive[2020-05-19-1-expect3]",
"tests/test_helper.py::test_helper_getUrl_ok",
"tests/test_helper.py::test_helper_getUrl_redirect_5",
"tests/test_helper.py::test_helper_getUrl_redirect_too_many",
"tests/test_helper.py::test_helper_getUrl_conn_error",
"tests/test_install.py::test_install[cmd0-linux-desktop-1.2.3-0-197001020304---linux_x64/desktop/tools_qtcreator/Updates.xml-archives0-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd1-linux-desktop-1.2.3---linux_x64/desktop/tools_qtcreator/Updates.xml-archives1-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.14.0-win32_mingw73-mingw73_32-windows_x86/desktop/qt5_5140/Updates.xml-archives2-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.9.0-win32_mingw53-mingw53_32-windows_x86/desktop/qt5_59/Updates.xml-archives3-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd4-windows-desktop-5.9.0-win32_mingw53-mingw53_32-windows_x86/desktop/qt5_59/Updates.xml-archives4-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd5-windows-desktop-5.14.0-win32_mingw73-mingw73_32-windows_x86/desktop/qt5_5140/Updates.xml-archives5-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd6-windows-desktop-5.14.0-win64_mingw73-mingw73_64-windows_x86/desktop/qt5_5140/Updates.xml-archives6-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd7-windows-desktop-6.2.0-win64_mingw73-mingw73_64-windows_x86/desktop/qt6_620/Updates.xml-archives7-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd8-windows-desktop-6.1.0-win64_mingw81-mingw81_64-windows_x86/desktop/qt6_610/Updates.xml-archives8-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd9-windows-android-6.1.0-android_armv7-android_armv7-windows_x86/android/qt6_610_armv7/Updates.xml-archives9-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install_nonexistent_archives[install-qt",
"tests/test_install.py::test_install_nonexistent_archives[install-src",
"tests/test_install.py::test_install_nonexistent_archives[install-tool",
"tests/test_install.py::test_install_pool_exception[RuntimeError()-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_pool_exception[KeyboardInterrupt()-../aqt/settings.ini-Caught",
"tests/test_install.py::test_install_pool_exception[MemoryError()-../aqt/settings.ini-Caught",
"tests/test_install.py::test_install_pool_exception[MemoryError()-data/settings_no_concurrency.ini-Caught"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-11-24 21:33:24+00:00
|
mit
| 3,978 |
|
miurahr__aqtinstall-510
|
diff --git a/aqt/updater.py b/aqt/updater.py
index 2392022..86f78b9 100644
--- a/aqt/updater.py
+++ b/aqt/updater.py
@@ -24,6 +24,7 @@ import pathlib
import re
import subprocess
from logging import getLogger
+from typing import Union
import patch
@@ -33,6 +34,26 @@ from aqt.helper import Settings
from aqt.metadata import SimpleSpec, Version
+def default_desktop_arch_dir(host: str, version: Union[Version, str]) -> str:
+ version: Version = version if isinstance(version, Version) else Version(version)
+ if host == "linux":
+ return "gcc_64"
+ elif host == "mac":
+ return "macos" if version in SimpleSpec(">=6.1.2") else "clang_64"
+ else: # Windows
+ # This is a temporary solution. This arch directory cannot exist for many versions of Qt.
+ # TODO: determine this dynamically
+ return "mingw81_64"
+
+
+def dir_for_version(ver: Version) -> str:
+ return "5.9" if ver == Version("5.9.0") else f"{ver.major}.{ver.minor}.{ver.patch}"
+
+
+def unpatched_path(os_name: str, final_component: str) -> str:
+ return ("/home/qt/work/install" if os_name == "linux" else "/Users/qt/work/install") + "/" + final_component
+
+
class Updater:
def __init__(self, prefix: pathlib.Path, logger):
self.logger = logger
@@ -160,30 +181,14 @@ class Updater:
newpath=bytes(str(self.prefix), "UTF-8"),
)
- def patch_qmake_script(self, base_dir, qt_version, os_name):
- if os_name == "linux":
- self.logger.info("Patching {}/bin/qmake".format(self.prefix))
- self._patch_textfile(
- self.prefix / "bin" / "qmake",
- "/home/qt/work/install/bin",
- "{}/{}/{}/bin".format(base_dir, qt_version, "gcc_64"),
- )
- elif os_name == "mac":
- self.logger.info("Patching {}/bin/qmake".format(self.prefix))
- self._patch_textfile(
- self.prefix / "bin" / "qmake",
- "/Users/qt/work/install/bin",
- "{}/{}/{}/bin".format(base_dir, qt_version, "clang_64"),
- )
- elif os_name == "windows":
- self.logger.info("Patching {}/bin/qmake.bat".format(self.prefix))
- self._patch_textfile(
- self.prefix / "bin" / "qmake.bat",
- "/Users/qt/work/install/bin",
- "{}\\{}\\{}\\bin".format(base_dir, qt_version, "mingw81_64"),
- )
- else:
- pass
+ def patch_qmake_script(self, base_dir, qt_version: str, os_name):
+ arch_dir = default_desktop_arch_dir(os_name, qt_version)
+ sep = "\\" if os_name == "windows" else "/"
+ patched = sep.join([base_dir, qt_version, arch_dir, "bin"])
+ unpatched = unpatched_path(os_name, "bin")
+ qmake_path = self.prefix / "bin" / ("qmake.bat" if os_name == "windows" else "qmake")
+ self.logger.info(f"Patching {qmake_path}")
+ self._patch_textfile(qmake_path, unpatched, patched)
def patch_qtcore(self, target):
"""patch to QtCore"""
@@ -235,15 +240,8 @@ class Updater:
def patch_target_qt_conf(self, base_dir, qt_version, arch_dir, os_name):
target_qt_conf = self.prefix / "bin" / "target_qt.conf"
- if os_name == "linux":
- old_targetprefix = "Prefix=/home/qt/work/install/target"
- new_hostprefix = "HostPrefix=../../gcc_64"
- elif os_name == "mac":
- old_targetprefix = "Prefix=/Users/qt/work/install/target"
- new_hostprefix = "HostPrefix=../../clang_64"
- else:
- old_targetprefix = "Prefix=/Users/qt/work/install/target"
- new_hostprefix = "HostPrefix=../../mingw81_64"
+ old_targetprefix = f'Prefix={unpatched_path(os_name, "target")}'
+ new_hostprefix = f"HostPrefix=../../{default_desktop_arch_dir(os_name, qt_version)}"
new_targetprefix = "Prefix={}".format(str(pathlib.Path(base_dir).joinpath(qt_version, arch_dir, "target")))
new_hostdata = "HostData=../{}".format(arch_dir)
self._patch_textfile(target_qt_conf, old_targetprefix, new_targetprefix)
@@ -260,7 +258,7 @@ class Updater:
arch = target.arch
version = Version(target.version)
os_name = target.os_name
- version_dir = "5.9" if version == Version("5.9.0") else target.version
+ version_dir = dir_for_version(version)
if arch is None:
arch_dir = ""
elif arch.startswith("win64_mingw"):
@@ -274,8 +272,8 @@ class Updater:
arch_dir = b + "_" + a
else:
arch_dir = arch[6:]
- elif version in SimpleSpec(">=6.1.2") and os_name == "mac" and arch == "clang_64":
- arch_dir = "macos"
+ elif os_name == "mac" and arch == "clang_64":
+ arch_dir = default_desktop_arch_dir(os_name, version)
else:
arch_dir = arch
try:
diff --git a/ci/generate_azure_pipelines_matrices.py b/ci/generate_azure_pipelines_matrices.py
index ce7879b..b6bd545 100644
--- a/ci/generate_azure_pipelines_matrices.py
+++ b/ci/generate_azure_pipelines_matrices.py
@@ -269,6 +269,7 @@ mac_build_jobs.append(
mac_build_jobs.extend(
[
BuildJob("install-qt", "5.15.2", "mac", "ios", "ios", "ios"),
+ BuildJob("install-qt", "6.2.2", "mac", "ios", "ios", "ios", module="qtsensors"),
BuildJob(
"install-qt", "6.1.0", "mac", "android", "android_armv7", "android_armv7"
),
diff --git a/ci/steps.yml b/ci/steps.yml
index 8eb16d0..aaa0d58 100644
--- a/ci/steps.yml
+++ b/ci/steps.yml
@@ -54,7 +54,8 @@ steps:
if [[ "$(HOST)" == "windows" ]]; then
python -m aqt install-qt $(HOST) desktop $(QT_VERSION) mingw81_64 --archives qtbase
else
- python -m aqt install-qt $(HOST) desktop $(QT_VERSION) --archives qtbase
+ # qtdeclarative contains `qmlimportscanner`: necessary for ios builds, Qt6+
+ python -m aqt install-qt $(HOST) desktop $(QT_VERSION) --archives qtbase qtdeclarative
fi
fi
if [[ "$(OUTPUT_DIR)" != "" ]]; then
@@ -174,6 +175,21 @@ steps:
condition: and(eq(variables['TARGET'], 'android'), or(eq(variables['Agent.OS'], 'Linux'), eq(variables['Agent.OS'], 'Darwin')), ne(variables['SUBCOMMAND'], 'list'), ne(variables['SUBCOMMAND'], 'install-tool'))
displayName: Build accelbubble example application to test for android
+ ##----------------------------------------------------
+ # for iOS target
+ - bash: |
+ set -ex
+ mkdir $(Build.BinariesDirectory)/tests
+ (cd $(Build.BinariesDirectory)/tests; 7zr x $(Build.SourcesDirectory)/ci/accelbubble.7z)
+ export PATH=$(QT_BINDIR):$PATH
+ qmake $(Build.BinariesDirectory)/tests/accelbubble
+ make
+ condition: |
+ and(eq(variables['TARGET'], 'ios'),
+ ne(variables['SUBCOMMAND'], 'list'),
+ ne(variables['SUBCOMMAND'], 'install-tool'))
+ displayName: Build accelbubble example application to test for ios
+
##----------------------------------------------------
# Cache Powershell Modules in $MODULES_FOLDER
- task: Cache@2
|
miurahr/aqtinstall
|
a27fa31566272f39947a000484dafadc207443bc
|
diff --git a/tests/test_install.py b/tests/test_install.py
index a1abb93..64478f2 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -574,7 +574,117 @@ def tool_archive(host: str, tool_name: str, variant: str, date: datetime = datet
r"^aqtinstall\(aqt\) v.* on Python 3.*\n"
r"Downloading qtbase...\n"
r"Finished installation of qtbase-windows-android_armv7.7z in .*\n"
- r"Patching .*/bin/qmake.bat\n"
+ r"Patching .*6\.1\.0[/\\]android_armv7[/\\]bin[/\\]qmake.bat\n"
+ r"Finished installation\n"
+ r"Time elapsed: .* second"
+ ),
+ ),
+ (
+ "install-qt linux android 6.3.0 android_arm64_v8a".split(),
+ "linux",
+ "android",
+ "6.3.0",
+ "android_arm64_v8a",
+ "android_arm64_v8a",
+ "linux_x64/android/qt6_630_arm64_v8a/Updates.xml",
+ [
+ MockArchive(
+ filename_7z="qtbase-linux-android_arm64_v8a.7z",
+ update_xml_name="qt.qt6.630.android_arm64_v8a",
+ contents=(
+ # Qt 6 non-desktop should patch qconfig.pri, qmake script and target_qt.conf
+ PatchedFile(
+ filename="mkspecs/qconfig.pri",
+ unpatched_content="... blah blah blah ...\n"
+ "QT_EDITION = Not OpenSource\n"
+ "QT_LICHECK = Not Empty\n"
+ "... blah blah blah ...\n",
+ patched_content="... blah blah blah ...\n"
+ "QT_EDITION = OpenSource\n"
+ "QT_LICHECK =\n"
+ "... blah blah blah ...\n",
+ ),
+ PatchedFile(
+ filename="bin/target_qt.conf",
+ unpatched_content="Prefix=/home/qt/work/install/target\n"
+ "HostPrefix=../../\n"
+ "HostData=target\n",
+ patched_content="Prefix={base_dir}{sep}6.3.0{sep}android_arm64_v8a{sep}target\n"
+ "HostPrefix=../../gcc_64\n"
+ "HostData=../android_arm64_v8a\n",
+ ),
+ PatchedFile(
+ filename="bin/qmake",
+ unpatched_content="... blah blah blah ...\n"
+ "/home/qt/work/install/bin\n"
+ "... blah blah blah ...\n",
+ patched_content="... blah blah blah ...\n"
+ "{base_dir}/6.3.0/gcc_64/bin\n"
+ "... blah blah blah ...\n",
+ ),
+ ),
+ ),
+ ],
+ re.compile(
+ r"^aqtinstall\(aqt\) v.* on Python 3.*\n"
+ r"Downloading qtbase...\n"
+ r"Finished installation of qtbase-linux-android_arm64_v8a.7z in .*\n"
+ r"Patching .*6\.3\.0[/\\]android_arm64_v8a[/\\]bin[/\\]qmake\n"
+ r"Finished installation\n"
+ r"Time elapsed: .* second"
+ ),
+ ),
+ (
+ "install-qt mac ios 6.1.2".split(),
+ "mac",
+ "ios",
+ "6.1.2",
+ "ios",
+ "ios",
+ "mac_x64/ios/qt6_612/Updates.xml",
+ [
+ MockArchive(
+ filename_7z="qtbase-mac-ios.7z",
+ update_xml_name="qt.qt6.612.ios",
+ contents=(
+ # Qt 6 non-desktop should patch qconfig.pri, qmake script and target_qt.conf
+ PatchedFile(
+ filename="mkspecs/qconfig.pri",
+ unpatched_content="... blah blah blah ...\n"
+ "QT_EDITION = Not OpenSource\n"
+ "QT_LICHECK = Not Empty\n"
+ "... blah blah blah ...\n",
+ patched_content="... blah blah blah ...\n"
+ "QT_EDITION = OpenSource\n"
+ "QT_LICHECK =\n"
+ "... blah blah blah ...\n",
+ ),
+ PatchedFile(
+ filename="bin/target_qt.conf",
+ unpatched_content="Prefix=/Users/qt/work/install/target\n"
+ "HostPrefix=../../\n"
+ "HostData=target\n",
+ patched_content="Prefix={base_dir}{sep}6.1.2{sep}ios{sep}target\n"
+ "HostPrefix=../../macos\n"
+ "HostData=../ios\n",
+ ),
+ PatchedFile(
+ filename="bin/qmake",
+ unpatched_content="... blah blah blah ...\n"
+ "/Users/qt/work/install/bin\n"
+ "... blah blah blah ...\n",
+ patched_content="... blah blah blah ...\n"
+ "{base_dir}/6.1.2/macos/bin\n"
+ "... blah blah blah ...\n",
+ ),
+ ),
+ ),
+ ],
+ re.compile(
+ r"^aqtinstall\(aqt\) v.* on Python 3.*\n"
+ r"Downloading qtbase...\n"
+ r"Finished installation of qtbase-mac-ios.7z in .*\n"
+ r"Patching .*6\.1\.2[/\\]ios[/\\]bin[/\\]qmake\n"
r"Finished installation\n"
r"Time elapsed: .* second"
),
|
ios: qmake script contains non-resolvable target path for Qt 6.2.x
**Describe the bug**
Qt 6.2.x (maybe earlier versions as well) seems to have changed regarding the `ios` architecture compared to 5.15.2:
1, `$OUTPUT_DIR/6.2.3/ios/bin/qmake` is no longer independent, instead, the `macos/desktop` architecture has to be installed additionally. That's fine (although a bit unintuitive, but I guess there is not much which can be done about it). Maybe aqt could warn about that or even install the required archive (macos/desktop/qtbase) automatically?
2. It looks like `$OUTPUT_DIR/6.2.3/ios/bin/qmake` is supposed to find the `macos` `desktop` qmake, but currently it doesn't due to path changes.
#289 seems related, but apparently isn't enough to fix this.
**To Reproduce**
Steps to reproduce the behavior:
1. `python3 -m pip install "aqtinstall==2.0.6"`
2. `python3 -m aqt install-qt --outputdir "/usr/local/opt/qt/" mac ios "6.2.3" --archives qtbase qttools qttranslations`
3. `/usr/local/opt/qt/6.2.3/ios/bin/qmake`
**Expected behavior**
qmake only works when manually creating a symlink from the expected location to the new location like that:
https://github.com/hoffie/jamulus/commit/6c7e4751a1b5461e62e17600e2047919a2ce7f4f#diff-ad84ad4ff36c1685f58e8d153980cb299a85fd0f851681459248564f4d3a9b13R27
Another workaround would be not calling ios/bin/qmake by users, but if this is the advise, then ios/bin/qmake should probably not be there in the first place. :)
aqt should insert the proper path into the `qmake` script.
I believe that this place has to be adjusted with version-specific logic:
https://github.com/miurahr/aqtinstall/blob/1a82a92e4c44b0891b6df03f1f5ff371eff2de50/aqt/updater.py#L176
`clang_64` should be `macos` for Qt 6.2.x.
I may try to submit a PR this evening (but feel free to go ahead if you don't hear from me).
**`aqt` output**
```
/usr/local/opt/qt/6.2.3/ios/bin/qmake: line 7: /usr/local/opt/qt/6.2.3/clang_64/bin/qmake: No such file or directory
```
**Desktop (please complete the following information):**
- macOS 10.15 with ios target
- `aqtinstall(aqt) v2.0.6 on Python 3.9.10 [CPython Clang 12.0.0 (clang-1200.0.32.29)]` (Update: 2.1.0rc2 shows the same behavior)
**Additional context**
Of course, I might be missing something; I've just noticed that simply replacing 5.15.2 by 6.2.3 no longer leads to a working `qmake` setup for `ios`.
|
0.0
|
a27fa31566272f39947a000484dafadc207443bc
|
[
"tests/test_install.py::test_install[cmd13-mac-ios-6.1.2-ios-ios-mac_x64/ios/qt6_612/Updates.xml-archives13-^aqtinstall\\\\(aqt\\\\)"
] |
[
"tests/test_install.py::test_install[cmd0-linux-desktop-1.2.3-0-197001020304---linux_x64/desktop/tools_qtcreator/Updates.xml-archives0-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd1-linux-desktop-1.2.3---linux_x64/desktop/tools_qtcreator/Updates.xml-archives1-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.14.0-win32_mingw73-mingw73_32-windows_x86/desktop/qt5_5140/Updates.xml-archives2-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.14.2---windows_x86/desktop/qt5_5142_src_doc_examples/Updates.xml-archives3-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd4-windows-desktop-5.14.2---windows_x86/desktop/qt5_5142_src_doc_examples/Updates.xml-archives4-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd5-windows-desktop-5.9.0-win32_mingw53-mingw53_32-windows_x86/desktop/qt5_59/Updates.xml-archives5-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd6-windows-desktop-5.9.0-win32_mingw53-mingw53_32-windows_x86/desktop/qt5_59/Updates.xml-archives6-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd7-windows-desktop-5.14.0-win32_mingw73-mingw73_32-windows_x86/desktop/qt5_5140/Updates.xml-archives7-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd8-windows-desktop-5.14.0-win64_mingw73-mingw73_64-windows_x86/desktop/qt5_5140/Updates.xml-archives8-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd9-windows-desktop-6.2.0-win64_mingw73-mingw73_64-windows_x86/desktop/qt6_620/Updates.xml-archives9-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd10-windows-desktop-6.1.0-win64_mingw81-mingw81_64-windows_x86/desktop/qt6_610/Updates.xml-archives10-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd11-windows-android-6.1.0-android_armv7-android_armv7-windows_x86/android/qt6_610_armv7/Updates.xml-archives11-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install[cmd12-linux-android-6.3.0-android_arm64_v8a-android_arm64_v8a-linux_x64/android/qt6_630_arm64_v8a/Updates.xml-archives12-^aqtinstall\\\\(aqt\\\\)",
"tests/test_install.py::test_install_nonexistent_archives[install-qt",
"tests/test_install.py::test_install_nonexistent_archives[install-doc",
"tests/test_install.py::test_install_nonexistent_archives[install-example",
"tests/test_install.py::test_install_nonexistent_archives[install-tool",
"tests/test_install.py::test_install_pool_exception[RuntimeError-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_pool_exception[KeyboardInterrupt-../aqt/settings.ini-Caught",
"tests/test_install.py::test_install_pool_exception[MemoryError-../aqt/settings.ini-Caught",
"tests/test_install.py::test_install_pool_exception[MemoryError-data/settings_no_concurrency.ini-Caught",
"tests/test_install.py::test_install_installer_archive_extraction_err"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-03-28 02:03:08+00:00
|
mit
| 3,979 |
|
miurahr__aqtinstall-518
|
diff --git a/aqt/exceptions.py b/aqt/exceptions.py
index f02f032..d56fd4f 100644
--- a/aqt/exceptions.py
+++ b/aqt/exceptions.py
@@ -18,14 +18,14 @@
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-from typing import Iterable
+from typing import List
DOCS_CONFIG = "https://aqtinstall.readthedocs.io/en/stable/configuration.html#configuration"
class AqtException(Exception):
def __init__(self, *args, **kwargs):
- self.suggested_action: Iterable[str] = kwargs.pop("suggested_action", [])
+ self.suggested_action: List[str] = kwargs.pop("suggested_action", [])
self.should_show_help: bool = kwargs.pop("should_show_help", False)
super(AqtException, self).__init__(*args, **kwargs)
@@ -40,6 +40,9 @@ class AqtException(Exception):
["* " + suggestion for suggestion in self.suggested_action]
)
+ def append_suggested_follow_up(self, suggestions: List[str]):
+ self.suggested_action.extend(suggestions)
+
class ArchiveDownloadError(AqtException):
pass
diff --git a/aqt/metadata.py b/aqt/metadata.py
index 8c95cfc..7be73e6 100644
--- a/aqt/metadata.py
+++ b/aqt/metadata.py
@@ -450,7 +450,7 @@ class MetadataFactory:
return arches
def fetch_extensions(self, version: Version) -> List[str]:
- versions_extensions = MetadataFactory.get_versions_extensions(
+ versions_extensions = self.get_versions_extensions(
self.fetch_http(self.archive_id.to_url(), False), self.archive_id.category
)
filtered = filter(
@@ -467,7 +467,7 @@ class MetadataFactory:
def get_version(ver_ext: Tuple[Version, str]):
return ver_ext[0]
- versions_extensions = MetadataFactory.get_versions_extensions(
+ versions_extensions = self.get_versions_extensions(
self.fetch_http(self.archive_id.to_url(), False), self.archive_id.category
)
versions = sorted(filter(None, map(get_version, filter(filter_by, versions_extensions))))
@@ -479,7 +479,7 @@ class MetadataFactory:
def fetch_tools(self) -> List[str]:
html_doc = self.fetch_http(self.archive_id.to_url(), False)
- return list(MetadataFactory.iterate_folders(html_doc, "tools"))
+ return list(self.iterate_folders(html_doc, "tools"))
def fetch_tool_modules(self, tool_name: str) -> List[str]:
tool_data = self._fetch_module_metadata(tool_name)
@@ -588,24 +588,32 @@ class MetadataFactory:
f"Connection to '{base_url}' failed. Retrying with fallback '{base_urls[i + 1]}'."
)
- @staticmethod
- def iterate_folders(html_doc: str, filter_category: str = "") -> Generator[str, None, None]:
+ def iterate_folders(self, html_doc: str, filter_category: str = "") -> Generator[str, None, None]:
def table_row_to_folder(tr: bs4.element.Tag) -> str:
try:
return tr.find_all("td")[1].a.contents[0].rstrip("/")
except (AttributeError, IndexError):
return ""
- soup: bs4.BeautifulSoup = bs4.BeautifulSoup(html_doc, "html.parser")
- for row in soup.body.table.find_all("tr"):
- content: str = table_row_to_folder(row)
- if not content or content == "Parent Directory":
- continue
- if content.startswith(filter_category):
- yield content
-
- @staticmethod
- def get_versions_extensions(html_doc: str, category: str) -> Iterator[Tuple[Optional[Version], str]]:
+ try:
+ soup: bs4.BeautifulSoup = bs4.BeautifulSoup(html_doc, "html.parser")
+ for row in soup.body.table.find_all("tr"):
+ content: str = table_row_to_folder(row)
+ if not content or content == "Parent Directory":
+ continue
+ if content.startswith(filter_category):
+ yield content
+ except Exception as e:
+ url = posixpath.join(Settings.baseurl, self.archive_id.to_url())
+ raise ArchiveConnectionError(
+ f"Failed to retrieve the expected HTML page at {url}",
+ suggested_action=[
+ "Check your network connection.",
+ f"Make sure that you can access {url} in your web browser.",
+ ],
+ ) from e
+
+ def get_versions_extensions(self, html_doc: str, category: str) -> Iterator[Tuple[Optional[Version], str]]:
def folder_to_version_extension(folder: str) -> Tuple[Optional[Version], str]:
components = folder.split("_", maxsplit=2)
ext = "" if len(components) < 3 else components[2]
@@ -617,7 +625,7 @@ class MetadataFactory:
return map(
folder_to_version_extension,
- MetadataFactory.iterate_folders(html_doc, category),
+ self.iterate_folders(html_doc, category),
)
@staticmethod
@@ -792,5 +800,5 @@ def show_list(meta: MetadataFactory):
else:
print(*output, sep=" ")
except (ArchiveDownloadError, ArchiveConnectionError) as e:
- e.suggested_action = suggested_follow_up(meta)
+ e.append_suggested_follow_up(suggested_follow_up(meta))
raise e from e
|
miurahr/aqtinstall
|
320df539c0cd050686022e004805282bd86e7760
|
diff --git a/tests/test_list.py b/tests/test_list.py
index 57e308e..de92e96 100644
--- a/tests/test_list.py
+++ b/tests/test_list.py
@@ -1,6 +1,7 @@
import hashlib
import json
import os
+import posixpath
import re
import shutil
import sys
@@ -178,6 +179,31 @@ def test_list_versions_tools(monkeypatch, spec_regex, os_name, target, in_file,
assert f"{all_ver_for_spec}" == row
[email protected](
+ "html_doc",
+ (
+ "<html><body>Login to my public WIFI network:<form>...</form></body></html>",
+ "<html>malformed-html/",
+ ),
+)
+def test_list_bad_html(monkeypatch, html_doc: str):
+ monkeypatch.setattr(MetadataFactory, "fetch_http", lambda *args, **kwargs: html_doc)
+ archive_id = ArchiveId("qt", "linux", "desktop")
+ expected_url = posixpath.join(Settings.baseurl, archive_id.to_url())
+ expected_exception = ArchiveConnectionError(
+ f"Failed to retrieve the expected HTML page at {expected_url}",
+ suggested_action=[
+ "Check your network connection.",
+ f"Make sure that you can access {expected_url} in your web browser.",
+ ],
+ )
+
+ with pytest.raises(ArchiveConnectionError) as e:
+ MetadataFactory(archive_id).fetch_versions()
+ assert e.type == ArchiveConnectionError
+ assert format(e.value) == format(expected_exception)
+
+
@pytest.mark.parametrize(
"version,extension,in_file,expect_out_file",
[
|
`MetadataFactory` makes inappropriate assumptions about the HTML files it retrieves.
**Describe the bug**
`MetadataFactory` improperly assumes that HTML pages at download.qt.io will always contain a body that contains a table. Infrequently, the server will return something unexpected, and `aqt` should be able to provide a reasonable error message.
**To Reproduce**
Run `aqt list-qt linux desktop`, under the condition that the URL https://download.qt.io/online/qtsdkrepository/linux_x64/desktop/ returns a page without a table.
**Expected behavior**
The `aqt list-qt linux desktop` command returns a list of Qt versions.
**`aqt` output**
```
'NoneType' object has no attribute 'find_all'
Traceback (most recent call last):
File "/home/garald/.local/lib/python3.8/site-packages/aqt/installer.py", line 108, in run
args.func(args)
File "/home/garald/.local/lib/python3.8/site-packages/aqt/installer.py", line 524, in run_list_qt
show_list(meta)
File "/home/garald/.local/lib/python3.8/site-packages/aqt/metadata.py", line 775, in show_list
output = meta.getList()
File "/home/garald/.local/lib/python3.8/site-packages/aqt/metadata.py", line 435, in getList
return self._action()
File "/home/garald/.local/lib/python3.8/site-packages/aqt/metadata.py", line 473, in fetch_versions
versions = sorted(filter(None, map(get_version, filter(filter_by, versions_extensions))))
File "/home/garald/.local/lib/python3.8/site-packages/aqt/metadata.py", line 600, in iterate_folders
for row in soup.body.table.find_all("tr"):
AttributeError: 'NoneType' object has no attribute 'find_all'
aqtinstall(aqt) v2.1.0 on Python 3.8.10 [CPython GCC 9.4.0]
Working dir: /home/garald
Arguments: ['/home/garald/.local/bin/aqt', 'list-qt', 'linux', 'desktop'] Host: uname_result(system='Linux', node='garald-H310M-S2-2-0', release='5.4.0-109-generic', version='#123-Ubuntu SMP Fri Apr 8 09:10:54 UTC 2022', machine='x86_64', processor='x86_64')
===========================PLEASE FILE A BUG REPORT===========================
You have discovered a bug in aqt.
Please file a bug report at https://github.com/miurahr/aqtinstall/issues.
Please remember to include a copy of this program's output in your report.
```
**Desktop (please complete the following information):**
- OS: Linux
- aqtinstall(aqt) v2.1.0 on Python 3.8.10 [CPython GCC 9.4.0]
**Additional context**
This report comes from an off-topic comment posted in #496, but it is certainly a bug that needs to be addressed. I do not have all the context for this bug, but there's enough information in the program output to understand what happened.
|
0.0
|
320df539c0cd050686022e004805282bd86e7760
|
[
"tests/test_list.py::test_list_bad_html[<html><body>Login",
"tests/test_list.py::test_list_bad_html[<html>malformed-html/]"
] |
[
"tests/test_list.py::test_list_extension_for_arch[wasm_32-version0-wasm]",
"tests/test_list.py::test_list_extension_for_arch[mingw-version1-]",
"tests/test_list.py::test_list_extension_for_arch[android_fake-version2-]",
"tests/test_list.py::test_list_extension_for_arch[android_x86-version3-]",
"tests/test_list.py::test_list_extension_for_arch[android_x86-version4-x86]",
"tests/test_list.py::test_list_extension_for_arch[android_x86-version5-x86]",
"tests/test_list.py::test_list_possible_extension_for_arch[wasm_32-expect0]",
"tests/test_list.py::test_list_possible_extension_for_arch[mingw-expect1]",
"tests/test_list.py::test_list_possible_extension_for_arch[android_fake-expect2]",
"tests/test_list.py::test_list_possible_extension_for_arch[android-expect3]",
"tests/test_list.py::test_list_possible_extension_for_arch[android_x86-expect4]",
"tests/test_list.py::test_versions[init_data0-[[Version('1.1.1'),",
"tests/test_list.py::test_versions[init_data1-[]--expect_flat1-None-False]",
"tests/test_list.py::test_versions[init_data2-[[Version('1.2.3')]]-1.2.3-expect_flat2-expect_last2-True]",
"tests/test_list.py::test_list_versions_tools[windows-android-windows-android.html-windows-android-expect.json]",
"tests/test_list.py::test_list_versions_tools[windows-desktop-windows-desktop.html-windows-desktop-expect.json]",
"tests/test_list.py::test_list_versions_tools[windows-winrt-windows-winrt.html-windows-winrt-expect.json]",
"tests/test_list.py::test_list_versions_tools[linux-android-linux-android.html-linux-android-expect.json]",
"tests/test_list.py::test_list_versions_tools[linux-desktop-linux-desktop.html-linux-desktop-expect.json]",
"tests/test_list.py::test_list_versions_tools[mac-android-mac-android.html-mac-android-expect.json]",
"tests/test_list.py::test_list_versions_tools[mac-desktop-mac-desktop.html-mac-desktop-expect.json]",
"tests/test_list.py::test_list_versions_tools[mac-ios-mac-ios.html-mac-ios-expect.json]",
"tests/test_list.py::test_list_architectures_and_modules[5.14.0--windows-5140-update.xml-windows-5140-expect.json]",
"tests/test_list.py::test_list_architectures_and_modules[5.15.0--windows-5150-update.xml-windows-5150-expect.json]",
"tests/test_list.py::test_list_architectures_and_modules[5.15.2-src_doc_examples-windows-5152-src-doc-example-update.xml-windows-5152-src-doc-example-expect.json]",
"tests/test_list.py::test_list_architectures_and_modules[6.2.0--windows-620-update.xml-windows-620-expect.json]",
"tests/test_list.py::test_list_src_doc_examples_archives[src-windows-5.15.2-expected0]",
"tests/test_list.py::test_list_src_doc_examples_archives[doc-windows-5.15.2-expected1]",
"tests/test_list.py::test_list_src_doc_examples_archives[examples-windows-5.15.2-expected2]",
"tests/test_list.py::test_list_src_doc_examples_modules[doc-windows-5.15.2-expected0]",
"tests/test_list.py::test_list_src_doc_examples_modules[examples-windows-5.15.2-expected1]",
"tests/test_list.py::test_list_src_doc_examples_cli[list-src",
"tests/test_list.py::test_list_src_doc_examples_cli[list-doc",
"tests/test_list.py::test_list_src_doc_examples_cli[list-example",
"tests/test_list.py::test_list_archives[5.14.0-win32_mingw73-modules_to_query0-modules_failed_query0]",
"tests/test_list.py::test_list_archives[5.14.0-win32_mingw73-modules_to_query1-modules_failed_query1]",
"tests/test_list.py::test_list_archives[5.14.0-win32_mingw73-modules_to_query2-modules_failed_query2]",
"tests/test_list.py::test_list_archives[5.14.0-win32_mingw73-modules_to_query3-modules_failed_query3]",
"tests/test_list.py::test_list_archives[5.14.0-win64_msvc2017_64-modules_to_query4-modules_failed_query4]",
"tests/test_list.py::test_list_archives[5.14.0-win64_msvc2017_64-modules_to_query5-modules_failed_query5]",
"tests/test_list.py::test_list_archives_insufficient_args",
"tests/test_list.py::test_list_archives_bad_xml",
"tests/test_list.py::test_tool_modules[mac-desktop-tools_cmake]",
"tests/test_list.py::test_tool_modules[mac-desktop-tools_ifw]",
"tests/test_list.py::test_tool_modules[mac-desktop-tools_qtcreator]",
"tests/test_list.py::test_list_qt_cli[--extensions",
"tests/test_list.py::test_list_qt_cli[--spec",
"tests/test_list.py::test_list_qt_cli[--modules",
"tests/test_list.py::test_list_qt_cli[--extension",
"tests/test_list.py::test_list_qt_cli[--arch",
"tests/test_list.py::test_list_targets[list-qt-windows-expect0]",
"tests/test_list.py::test_list_targets[list-qt-linux-expect1]",
"tests/test_list.py::test_list_targets[list-qt-mac-expect2]",
"tests/test_list.py::test_list_targets[list-tool-windows-expect3]",
"tests/test_list.py::test_list_targets[list-tool-linux-expect4]",
"tests/test_list.py::test_list_targets[list-tool-mac-expect5]",
"tests/test_list.py::test_list_wrong_target[list-qt-windows-ios]",
"tests/test_list.py::test_list_wrong_target[list-qt-linux-ios]",
"tests/test_list.py::test_list_wrong_target[list-qt-linux-winrt]",
"tests/test_list.py::test_list_wrong_target[list-qt-mac-winrt]",
"tests/test_list.py::test_list_wrong_target[list-tool-windows-ios]",
"tests/test_list.py::test_list_wrong_target[list-tool-linux-ios]",
"tests/test_list.py::test_list_wrong_target[list-tool-linux-winrt]",
"tests/test_list.py::test_list_wrong_target[list-tool-mac-winrt]",
"tests/test_list.py::test_invalid_spec[list-qt-not",
"tests/test_list.py::test_invalid_spec[list-qt-1...3]",
"tests/test_list.py::test_invalid_spec[list-qt-]",
"tests/test_list.py::test_invalid_spec[list-qt->3",
"tests/test_list.py::test_list_choose_tool_by_version[simple_spec0-mytool.999]",
"tests/test_list.py::test_list_choose_tool_by_version[simple_spec1-mytool.999]",
"tests/test_list.py::test_list_choose_tool_by_version[simple_spec2-mytool.355]",
"tests/test_list.py::test_list_choose_tool_by_version[simple_spec3-mytool.300]",
"tests/test_list.py::test_list_choose_tool_by_version[simple_spec4-mytool.355]",
"tests/test_list.py::test_list_choose_tool_by_version[simple_spec5-mytool.350]",
"tests/test_list.py::test_list_choose_tool_by_version[simple_spec6-None]",
"tests/test_list.py::test_list_invalid_extensions[android--6.2.0-Qt",
"tests/test_list.py::test_list_invalid_extensions[android-arm64_v8a-5.13.0-The",
"tests/test_list.py::test_list_invalid_extensions[desktop-arm64_v8a-5.13.0-The",
"tests/test_list.py::test_list_invalid_extensions[desktop-arm64_v8a-6.2.0-The",
"tests/test_list.py::test_list_invalid_extensions[desktop-wasm-5.12.11-The",
"tests/test_list.py::test_list_invalid_extensions[desktop-wasm-6.1.9-The",
"tests/test_list.py::test_list_invalid_extensions[android-wasm-5.12.11-The",
"tests/test_list.py::test_list_invalid_extensions[android-wasm-5.14.0-The",
"tests/test_list.py::test_list_invalid_extensions[android-wasm-6.1.9-Qt",
"tests/test_list.py::test_suggested_follow_up[meta0-expected_message0]",
"tests/test_list.py::test_suggested_follow_up[meta1-expected_message1]",
"tests/test_list.py::test_suggested_follow_up[meta2-expected_message2]",
"tests/test_list.py::test_suggested_follow_up[meta3-expected_message3]",
"tests/test_list.py::test_suggested_follow_up[meta4-expected_message4]",
"tests/test_list.py::test_suggested_follow_up[meta5-expected_message5]",
"tests/test_list.py::test_suggested_follow_up[meta6-expected_message6]",
"tests/test_list.py::test_suggested_follow_up[meta7-expected_message7]",
"tests/test_list.py::test_suggested_follow_up[meta8-expected_message8]",
"tests/test_list.py::test_suggested_follow_up[meta9-expected_message9]",
"tests/test_list.py::test_suggested_follow_up[meta10-expected_message10]",
"tests/test_list.py::test_suggested_follow_up[meta11-expected_message11]",
"tests/test_list.py::test_suggested_follow_up[meta12-expected_message12]",
"tests/test_list.py::test_suggested_follow_up[meta13-expected_message13]",
"tests/test_list.py::test_format_suggested_follow_up",
"tests/test_list.py::test_format_suggested_follow_up_empty",
"tests/test_list.py::test_list_describe_filters[meta0-qt/mac/desktop",
"tests/test_list.py::test_list_describe_filters[meta1-qt/mac/desktop/wasm",
"tests/test_list.py::test_list_describe_filters[meta2-qt/mac/desktop]",
"tests/test_list.py::test_list_describe_filters[meta3-qt/mac/desktop/wasm]",
"tests/test_list.py::test_list_to_version[archive_id0-None-5.12.42-expect0]",
"tests/test_list.py::test_list_to_version[archive_id1-None-not",
"tests/test_list.py::test_list_to_version[archive_id2-spec2-latest-expect2]",
"tests/test_list.py::test_list_to_version[archive_id3-spec3-latest-expect3]",
"tests/test_list.py::test_list_fetch_tool_by_simple_spec",
"tests/test_list.py::test_show_list_tools_long_ifw[120-Tool",
"tests/test_list.py::test_show_list_tools_long_ifw[80-Tool",
"tests/test_list.py::test_show_list_tools_long_ifw[0-Tool",
"tests/test_list.py::test_show_list_versions",
"tests/test_list.py::test_show_list_tools",
"tests/test_list.py::test_show_list_empty",
"tests/test_list.py::test_show_list_bad_connection",
"tests/test_list.py::test_list_tool_cli[mac-desktop-tools_cmake]",
"tests/test_list.py::test_fetch_http_ok",
"tests/test_list.py::test_fetch_http_failover",
"tests/test_list.py::test_fetch_http_download_error[ArchiveDownloadError]",
"tests/test_list.py::test_fetch_http_download_error[ArchiveConnectionError]"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-04-20 01:31:23+00:00
|
mit
| 3,980 |
|
miurahr__aqtinstall-613
|
diff --git a/aqt/helper.py b/aqt/helper.py
index 6208a89..2e6dee7 100644
--- a/aqt/helper.py
+++ b/aqt/helper.py
@@ -27,6 +27,7 @@ import os
import posixpath
import secrets
import sys
+import threading
from logging import Handler, getLogger
from logging.handlers import QueueListener
from pathlib import Path
@@ -321,13 +322,30 @@ class SettingsClass:
"""
Class to hold configuration and settings.
Actual values are stored in 'settings.ini' file.
- It also holds a combinations database.
+ It also holds a `combinations` database.
"""
+ # this class is Borg
+ _shared_state: Dict[str, Any] = {
+ "config": None,
+ "configfile": None,
+ "loggingconf": None,
+ "_combinations": None,
+ "_lock": threading.Lock(),
+ }
+
+ def __new__(cls, *p, **k):
+ self = object.__new__(cls, *p, **k)
+ self.__dict__ = cls._shared_state
+ return self
+
def __init__(self):
- self.config = MyConfigParser()
- self.configfile = os.path.join(os.path.dirname(__file__), "settings.ini")
- self.loggingconf = os.path.join(os.path.dirname(__file__), "logging.ini")
+ if self.config is None:
+ with self._lock:
+ if self.config is None:
+ self.config = MyConfigParser()
+ self.configfile = os.path.join(os.path.dirname(__file__), "settings.ini")
+ self.loggingconf = os.path.join(os.path.dirname(__file__), "logging.ini")
def load_settings(self, file: Optional[Union[str, TextIO]] = None) -> None:
with open(
@@ -478,6 +496,5 @@ Settings = SettingsClass()
def setup_logging(env_key="LOG_CFG"):
config = os.getenv(env_key, None)
if config is not None and os.path.exists(config):
- logging.config.fileConfig(config)
- else:
- logging.config.fileConfig(Settings.loggingconf)
+ Settings.loggingconf = config
+ logging.config.fileConfig(Settings.loggingconf)
diff --git a/aqt/installer.py b/aqt/installer.py
index 33aec9a..1a16cad 100644
--- a/aqt/installer.py
+++ b/aqt/installer.py
@@ -1099,7 +1099,7 @@ def run_installer(archives: List[QtPackage], base_dir: str, sevenzip: Optional[s
#
tasks = []
for arc in archives:
- tasks.append((arc, base_dir, sevenzip, queue, archive_dest, keep))
+ tasks.append((arc, base_dir, sevenzip, queue, archive_dest, Settings.configfile, keep))
ctx = multiprocessing.get_context("spawn")
if is_64bit():
pool = ctx.Pool(Settings.concurrency, init_worker_sh, (), 4)
@@ -1154,8 +1154,8 @@ def installer(
command: Optional[str],
queue: multiprocessing.Queue,
archive_dest: Path,
- keep: bool = False,
- response_timeout: Optional[int] = None,
+ settings_ini: str,
+ keep: bool,
):
"""
Installer function to download archive files and extract it.
@@ -1165,10 +1165,9 @@ def installer(
base_url = qt_package.base_url
archive: Path = archive_dest / qt_package.archive
start_time = time.perf_counter()
- # set defaults
- Settings.load_settings()
- # set logging
- setup_logging() # XXX: why need to load again?
+ Settings.load_settings(file=settings_ini)
+ # setup queue logger
+ setup_logging()
qh = QueueHandler(queue)
logger = getLogger()
for handler in logger.handlers:
@@ -1176,10 +1175,7 @@ def installer(
logger.removeHandler(handler)
logger.addHandler(qh)
#
- if response_timeout is None:
- timeout = (Settings.connection_timeout, Settings.response_timeout)
- else:
- timeout = (Settings.connection_timeout, response_timeout)
+ timeout = (Settings.connection_timeout, Settings.response_timeout)
hash = get_hash(qt_package.archive_path, algorithm="sha256", timeout=timeout)
def download_bin(_base_url):
diff --git a/ci/settings.ini b/ci/settings.ini
index ae1f837..9aac817 100644
--- a/ci/settings.ini
+++ b/ci/settings.ini
@@ -9,7 +9,10 @@ baseurl: https://download.qt.io
connection_timeout: 30
response_timeout: 30
max_retries: 5
+max_retries_on_connection_error: 5
retry_backoff: 0.1
+max_retries_on_checksum_error: 5
+max_retries_to_retrieve_hash: 5
[mirrors]
blacklist:
|
miurahr/aqtinstall
|
28e9f00cef12216ab0223ea9d13e57a43c0178ce
|
diff --git a/tests/test_install.py b/tests/test_install.py
index 79945b4..fc373ff 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -1215,6 +1215,8 @@ def test_install_installer_archive_extraction_err(monkeypatch):
command="some_nonexistent_7z_extractor",
queue=MockMultiprocessingManager.Queue(),
archive_dest=Path(temp_dir),
+ settings_ini=Settings.configfile,
+ keep=False,
)
assert err.type == ArchiveExtractionError
err_msg = format(err.value).rstrip()
|
Setting class does not always hold the user's settings
**Describe the bug**
I'm working on some changes in aqt, and it seems to me that the `Settings` object is not really a singleton, but several instances exist of it. Only one of them has the user's settings.
**To Reproduce**
Add a line `print(f"Trusted mirrors from {self}")` in the implementation of the `trusted_mirrors` property in `helper.py`. The run aqt. You'll see that it prints different values for self. If you also have a configuration file with some custom settings, you'll see that they are often missing.
I'm trying to reimplement the SettingsClass as a singleton as described [here](https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python) but I must be doing something wrong and so far I haven't had any luck in getting this work properly.
|
0.0
|
28e9f00cef12216ab0223ea9d13e57a43c0178ce
|
[
"tests/test_install.py::test_install_installer_archive_extraction_err"
] |
[
"tests/test_install.py::test_install[cmd0-linux-desktop-1.2.3-0-197001020304-arch0-arch_dir0-updates_url0-archives0-^INFO",
"tests/test_install.py::test_install[cmd1-linux-desktop-1.2.3-arch1-arch_dir1-updates_url1-archives1-^INFO",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.14.0-arch2-arch_dir2-updates_url2-archives2-^INFO",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.14.0-arch3-arch_dir3-updates_url3-archives3-^INFO",
"tests/test_install.py::test_install[cmd4-windows-desktop-5.14.2-arch4-arch_dir4-updates_url4-archives4-^INFO",
"tests/test_install.py::test_install[cmd5-windows-desktop-5.14.2-arch5-arch_dir5-updates_url5-archives5-^INFO",
"tests/test_install.py::test_install[cmd6-windows-desktop-5.9.0-arch6-arch_dir6-updates_url6-archives6-^INFO",
"tests/test_install.py::test_install[cmd7-windows-desktop-5.9.0-arch7-arch_dir7-updates_url7-archives7-^INFO",
"tests/test_install.py::test_install[cmd8-windows-desktop-5.14.0-arch8-arch_dir8-updates_url8-archives8-^INFO",
"tests/test_install.py::test_install[cmd9-windows-desktop-5.14.0-arch9-arch_dir9-updates_url9-archives9-^INFO",
"tests/test_install.py::test_install[cmd10-windows-desktop-6.2.0-arch10-arch_dir10-updates_url10-archives10-^INFO",
"tests/test_install.py::test_install[cmd11-windows-desktop-6.1.0-arch11-arch_dir11-updates_url11-archives11-^INFO",
"tests/test_install.py::test_install[cmd12-windows-android-6.1.0-arch12-arch_dir12-updates_url12-archives12-^INFO",
"tests/test_install.py::test_install[cmd13-linux-android-6.4.1-arch13-arch_dir13-updates_url13-archives13-^INFO",
"tests/test_install.py::test_install[cmd14-linux-android-6.3.0-arch14-arch_dir14-updates_url14-archives14-^INFO",
"tests/test_install.py::test_install[cmd15-mac-ios-6.1.2-arch15-arch_dir15-updates_url15-archives15-^INFO",
"tests/test_install.py::test_install[cmd16-mac-ios-6.1.2-arch16-arch_dir16-updates_url16-archives16-^INFO",
"tests/test_install.py::test_install[cmd17-windows-desktop-6.2.4-arch17-arch_dir17-updates_url17-archives17-^INFO",
"tests/test_install.py::test_install_nonexistent_archives[install-qt",
"tests/test_install.py::test_install_nonexistent_archives[install-doc",
"tests/test_install.py::test_install_nonexistent_archives[install-example",
"tests/test_install.py::test_install_nonexistent_archives[install-tool",
"tests/test_install.py::test_install_pool_exception[RuntimeError-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_pool_exception[KeyboardInterrupt-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[MemoryError-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[MemoryError-data/settings_no_concurrency.ini-WARNING",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd0-linux-desktop-1.2.3-0-197001020304---https://www.alt.qt.mirror.com-linux_x64/desktop/tools_qtcreator/Updates.xml-archives0-^INFO",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd1-windows-desktop-5.12.10-win32_mingw73-mingw73_32-https://www.alt.qt.mirror.com-windows_x86/desktop/qt5_51210/Updates.xml-archives1-^INFO"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-11-16 02:30:08+00:00
|
mit
| 3,981 |
|
miurahr__aqtinstall-627
|
diff --git a/aqt/updater.py b/aqt/updater.py
index 60a31c0..4ccf3dc 100644
--- a/aqt/updater.py
+++ b/aqt/updater.py
@@ -20,10 +20,12 @@
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import logging
import os
+import re
+import stat
import subprocess
from logging import getLogger
from pathlib import Path
-from typing import Dict, Optional
+from typing import Dict, List, Optional, Union
import patch
@@ -35,8 +37,8 @@ from aqt.metadata import ArchiveId, MetadataFactory, QtRepoProperty, SimpleSpec,
dir_for_version = QtRepoProperty.dir_for_version
-def unpatched_path(os_name: str, final_component: str) -> str:
- return ("/home/qt/work/install" if os_name == "linux" else "/Users/qt/work/install") + "/" + final_component
+def unpatched_paths() -> List[str]:
+ return ["/home/qt/work/install", "/Users/qt/work/install"]
class Updater:
@@ -69,12 +71,16 @@ class Updater:
file.write_text(data, "UTF-8")
os.chmod(str(file), st.st_mode)
- def _patch_textfile(self, file: Path, old: str, new: str):
+ def _patch_textfile(self, file: Path, old: Union[str, re.Pattern], new: str, *, is_executable: bool = False):
st = file.stat()
+ file_mode = st.st_mode | (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH if is_executable else 0)
data = file.read_text("UTF-8")
- data = data.replace(old, new)
+ if isinstance(old, re.Pattern):
+ data = old.sub(new, data)
+ else:
+ data = data.replace(old, new)
file.write_text(data, "UTF-8")
- os.chmod(str(file), st.st_mode)
+ os.chmod(str(file), file_mode)
def _detect_qmake(self) -> bool:
"""detect Qt configurations from qmake."""
@@ -171,10 +177,10 @@ class Updater:
def patch_qmake_script(self, base_dir, qt_version: str, os_name: str, desktop_arch_dir: str):
sep = "\\" if os_name == "windows" else "/"
patched = sep.join([base_dir, qt_version, desktop_arch_dir, "bin"])
- unpatched = unpatched_path(os_name, "bin")
qmake_path = self.prefix / "bin" / ("qmake.bat" if os_name == "windows" else "qmake")
self.logger.info(f"Patching {qmake_path}")
- self._patch_textfile(qmake_path, unpatched, patched)
+ for unpatched in unpatched_paths():
+ self._patch_textfile(qmake_path, f"{unpatched}/bin", patched, is_executable=True)
def patch_qtcore(self, target):
"""patch to QtCore"""
@@ -226,14 +232,29 @@ class Updater:
def patch_target_qt_conf(self, base_dir: str, qt_version: str, arch_dir: str, os_name: str, desktop_arch_dir: str):
target_qt_conf = self.prefix / "bin" / "target_qt.conf"
- old_targetprefix = f'Prefix={unpatched_path(os_name, "target")}'
new_hostprefix = f"HostPrefix=../../{desktop_arch_dir}"
new_targetprefix = "Prefix={}".format(str(Path(base_dir).joinpath(qt_version, arch_dir, "target")))
new_hostdata = "HostData=../{}".format(arch_dir)
- self._patch_textfile(target_qt_conf, old_targetprefix, new_targetprefix)
+ new_host_lib_execs = "./bin" if os_name == "windows" else "./libexec"
+ old_host_lib_execs = re.compile(r"^HostLibraryExecutables=[^\n]*$", flags=re.MULTILINE)
+
+ self._patch_textfile(target_qt_conf, old_host_lib_execs, f"HostLibraryExecutables={new_host_lib_execs}")
+ for unpatched in unpatched_paths():
+ self._patch_textfile(target_qt_conf, f"Prefix={unpatched}/target", new_targetprefix)
self._patch_textfile(target_qt_conf, "HostPrefix=../../", new_hostprefix)
self._patch_textfile(target_qt_conf, "HostData=target", new_hostdata)
+ def patch_qdevice_file(self, base_dir: str, qt_version: str, arch_dir: str, os_name: str):
+ """Qt 6.4.1+ specific, but it should not hurt anything if `mkspecs/qdevice.pri` does not exist"""
+
+ qdevice = Path(base_dir) / qt_version / arch_dir / "mkspecs/qdevice.pri"
+ if not qdevice.exists():
+ return
+
+ old_line = re.compile(r"^DEFAULT_ANDROID_NDK_HOST =[^\n]*$", flags=re.MULTILINE)
+ new_line = f"DEFAULT_ANDROID_NDK_HOST = {'darwin' if os_name == 'mac' else os_name}-x86_64"
+ self._patch_textfile(qdevice, old_line, new_line)
+
@classmethod
def update(cls, target: TargetConfig, base_path: Path, installed_desktop_arch_dir: Optional[str]):
"""
@@ -290,6 +311,7 @@ class Updater:
updater.patch_qmake_script(base_dir, version_dir, target.os_name, desktop_arch_dir)
updater.patch_target_qt_conf(base_dir, version_dir, arch_dir, target.os_name, desktop_arch_dir)
+ updater.patch_qdevice_file(base_dir, version_dir, arch_dir, target.os_name)
except IOError as e:
raise UpdaterError(f"Updater caused an IO error: {e}") from e
diff --git a/ci/generate_azure_pipelines_matrices.py b/ci/generate_azure_pipelines_matrices.py
index 53d9dd1..25b75ad 100644
--- a/ci/generate_azure_pipelines_matrices.py
+++ b/ci/generate_azure_pipelines_matrices.py
@@ -296,17 +296,24 @@ mac_build_jobs.extend(
[
BuildJob("install-qt", "6.4.0", "mac", "ios", "ios", "ios", module="qtsensors", is_autodesktop=True),
BuildJob("install-qt", "6.2.4", "mac", "ios", "ios", "ios", module="qtsensors", is_autodesktop=False),
+ BuildJob("install-qt", "6.4.1", "mac", "android", "android_armv7", "android_armv7", is_autodesktop=True),
BuildJob("install-qt", "6.1.0", "mac", "android", "android_armv7", "android_armv7", is_autodesktop=True),
]
)
linux_build_jobs.extend(
- [BuildJob("install-qt", "6.1.0", "linux", "android", "android_armv7", "android_armv7", is_autodesktop=True)]
+ [
+ BuildJob("install-qt", "6.1.0", "linux", "android", "android_armv7", "android_armv7", is_autodesktop=True),
+ BuildJob("install-qt", "6.4.1", "linux", "android", "android_arm64_v8a", "android_arm64_v8a", is_autodesktop=True),
+ ]
)
# Qt 6.3.0 for Windows-Android has win64_mingw available, but not win64_mingw81.
# This will test that the path to mingw is not hardcoded.
windows_build_jobs.extend(
- [BuildJob("install-qt", "6.3.0", "windows", "android", "android_armv7", "android_armv7", is_autodesktop=True)]
+ [
+ BuildJob("install-qt", "6.3.0", "windows", "android", "android_armv7", "android_armv7", is_autodesktop=True),
+ BuildJob("install-qt", "6.4.1", "windows", "android", "android_x86_64", "android_x86_64", is_autodesktop=True),
+ ]
)
# Test binary patch of qmake
|
miurahr/aqtinstall
|
2c8b23d649a0c856dd575cf376438b3e9edf4beb
|
diff --git a/tests/test_install.py b/tests/test_install.py
index bd31df4..79945b4 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -635,6 +635,81 @@ def tool_archive(host: str, tool_name: str, variant: str, date: datetime = datet
r"INFO : Time elapsed: .* second"
),
),
+ (
+ "install-qt linux android 6.4.1 android_arm64_v8a".split(),
+ "linux",
+ "android",
+ "6.4.1",
+ {"std": "android_arm64_v8a"},
+ {"std": "android_arm64_v8a"},
+ {"std": "linux_x64/android/qt6_641_arm64_v8a/Updates.xml"},
+ {
+ "std": [
+ MockArchive(
+ filename_7z="qtbase-MacOS-MacOS_12-Clang-Android-Android_ANY-ARM64.7z",
+ update_xml_name="qt.qt6.641.android_arm64_v8a",
+ contents=(
+ # Qt 6 non-desktop should patch qconfig.pri, qmake script and target_qt.conf
+ PatchedFile(
+ filename="mkspecs/qconfig.pri",
+ unpatched_content="... blah blah blah ...\n"
+ "QT_EDITION = Not OpenSource\n"
+ "QT_LICHECK = Not Empty\n"
+ "... blah blah blah ...\n",
+ patched_content="... blah blah blah ...\n"
+ "QT_EDITION = OpenSource\n"
+ "QT_LICHECK =\n"
+ "... blah blah blah ...\n",
+ ),
+ PatchedFile(
+ filename="mkspecs/qdevice.pri",
+ unpatched_content="blah blah blah...\n"
+ "DEFAULT_ANDROID_NDK_HOST = mac-x86_64\n"
+ "blah blah blah...\n",
+ patched_content="blah blah blah...\n"
+ "DEFAULT_ANDROID_NDK_HOST = linux-x86_64\n"
+ "blah blah blah...\n",
+ ),
+ PatchedFile(
+ filename="bin/target_qt.conf",
+ unpatched_content="Prefix=/Users/qt/work/install/target\n"
+ "HostPrefix=../../\n"
+ "HostData=target\n"
+ "HostLibraryExecutables=./bin\n"
+ "HostLibraryExecutables=./libexec\n",
+ patched_content="Prefix={base_dir}{sep}6.4.1{sep}android_arm64_v8a{sep}target\n"
+ "HostPrefix=../../gcc_64\n"
+ "HostData=../android_arm64_v8a\n"
+ "HostLibraryExecutables=./libexec\n"
+ "HostLibraryExecutables=./libexec\n",
+ ),
+ PatchedFile(
+ filename="bin/qmake",
+ unpatched_content="... blah blah blah ...\n"
+ "/home/qt/work/install/bin\n"
+ "/Users/qt/work/install/bin\n"
+ "... blah blah blah ...\n",
+ patched_content="... blah blah blah ...\n"
+ "{base_dir}/6.4.1/gcc_64/bin\n"
+ "{base_dir}/6.4.1/gcc_64/bin\n"
+ "... blah blah blah ...\n",
+ ),
+ ),
+ ),
+ ]
+ },
+ re.compile(
+ r"^INFO : aqtinstall\(aqt\) v.* on Python 3.*\n"
+ r"WARNING : You are installing the android version of Qt, which requires that the desktop version of "
+ r"Qt is also installed. You can install it with the following command:\n"
+ r" `aqt install-qt linux desktop 6\.4\.1 gcc_64`\n"
+ r"INFO : Downloading qtbase\.\.\.\n"
+ r"Finished installation of qtbase-MacOS-MacOS_12-Clang-Android-Android_ANY-ARM64\.7z in .*\n"
+ r"INFO : Patching .*6\.4\.1[/\\]android_arm64_v8a[/\\]bin[/\\]qmake\n"
+ r"INFO : Finished installation\n"
+ r"INFO : Time elapsed: .* second"
+ ),
+ ),
(
"install-qt linux android 6.3.0 android_arm64_v8a".split(),
"linux",
@@ -939,6 +1014,8 @@ def test_install(
for patched_file in archive.contents:
file_path = installed_path / patched_file.filename
assert file_path.is_file()
+ if file_path.name == "qmake":
+ assert os.access(file_path, os.X_OK), "qmake file must be executable"
expect_content = patched_file.expected_content(base_dir=output_dir, sep=os.sep)
actual_content = file_path.read_text(encoding="utf_8")
|
Cannot add Qt 6.4.1 Android Arm64_v8a as a Qt Kit into QtCreator
**Description**
When trying to add Qt 6.4.1 Android Arm64_v8a as a Qt Version for Kit into QtCreator, I am getting an error:
The qmake executable /opt/Qt/6.4.1/android_arm64_v8a/bin/qmake could not be added: "/opt/Qt/6.4.1/android_arm64_v8a/bin/qmake" produced no output: /opt/Qt/6.4.1/android_arm64_v8a/bin/qmake: 7: /Users/qt/work/install/bin/qmake: not found
However, via an official installer I can add this Qt version without any issues and I can compile and deploy everything as usual.
**To Reproduce**
1. aqt install-qt -O /opt/Qt linux android 6.4.1 android_arm64_v8a --autodesktop
2. Open QtCreator 8.0.2, add /opt/Qt/6.4.1/android_arm64_v8a/bin/qmake as Qt Version.
3. See the error.
**Expected behavior**
Works the same as for the official installer.
**Desktop:**
- OS: Ubuntu 22.04
- `aqt` version: aqtinstall(aqt) v3.0.2 on Python 3.10.6 [CPython GCC 11.3.0]
UPD:
I don't have such problem with Qt 6.4.0 installed via aqtinstall.
|
0.0
|
2c8b23d649a0c856dd575cf376438b3e9edf4beb
|
[
"tests/test_install.py::test_install[cmd13-linux-android-6.4.1-arch13-arch_dir13-updates_url13-archives13-^INFO",
"tests/test_install.py::test_install[cmd14-linux-android-6.3.0-arch14-arch_dir14-updates_url14-archives14-^INFO",
"tests/test_install.py::test_install[cmd15-mac-ios-6.1.2-arch15-arch_dir15-updates_url15-archives15-^INFO",
"tests/test_install.py::test_install[cmd16-mac-ios-6.1.2-arch16-arch_dir16-updates_url16-archives16-^INFO"
] |
[
"tests/test_install.py::test_install[cmd0-linux-desktop-1.2.3-0-197001020304-arch0-arch_dir0-updates_url0-archives0-^INFO",
"tests/test_install.py::test_install[cmd1-linux-desktop-1.2.3-arch1-arch_dir1-updates_url1-archives1-^INFO",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.14.0-arch2-arch_dir2-updates_url2-archives2-^INFO",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.14.0-arch3-arch_dir3-updates_url3-archives3-^INFO",
"tests/test_install.py::test_install[cmd4-windows-desktop-5.14.2-arch4-arch_dir4-updates_url4-archives4-^INFO",
"tests/test_install.py::test_install[cmd5-windows-desktop-5.14.2-arch5-arch_dir5-updates_url5-archives5-^INFO",
"tests/test_install.py::test_install[cmd6-windows-desktop-5.9.0-arch6-arch_dir6-updates_url6-archives6-^INFO",
"tests/test_install.py::test_install[cmd7-windows-desktop-5.9.0-arch7-arch_dir7-updates_url7-archives7-^INFO",
"tests/test_install.py::test_install[cmd8-windows-desktop-5.14.0-arch8-arch_dir8-updates_url8-archives8-^INFO",
"tests/test_install.py::test_install[cmd9-windows-desktop-5.14.0-arch9-arch_dir9-updates_url9-archives9-^INFO",
"tests/test_install.py::test_install[cmd10-windows-desktop-6.2.0-arch10-arch_dir10-updates_url10-archives10-^INFO",
"tests/test_install.py::test_install[cmd11-windows-desktop-6.1.0-arch11-arch_dir11-updates_url11-archives11-^INFO",
"tests/test_install.py::test_install[cmd12-windows-android-6.1.0-arch12-arch_dir12-updates_url12-archives12-^INFO",
"tests/test_install.py::test_install[cmd17-windows-desktop-6.2.4-arch17-arch_dir17-updates_url17-archives17-^INFO",
"tests/test_install.py::test_install_nonexistent_archives[install-qt",
"tests/test_install.py::test_install_nonexistent_archives[install-doc",
"tests/test_install.py::test_install_nonexistent_archives[install-example",
"tests/test_install.py::test_install_nonexistent_archives[install-tool",
"tests/test_install.py::test_install_pool_exception[RuntimeError-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_pool_exception[KeyboardInterrupt-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[MemoryError-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[MemoryError-data/settings_no_concurrency.ini-WARNING",
"tests/test_install.py::test_install_installer_archive_extraction_err",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd0-linux-desktop-1.2.3-0-197001020304---https://www.alt.qt.mirror.com-linux_x64/desktop/tools_qtcreator/Updates.xml-archives0-^INFO",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd1-windows-desktop-5.12.10-win32_mingw73-mingw73_32-https://www.alt.qt.mirror.com-windows_x86/desktop/qt5_51210/Updates.xml-archives1-^INFO"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-12-03 01:33:42+00:00
|
mit
| 3,982 |
|
miurahr__aqtinstall-633
|
diff --git a/aqt/archives.py b/aqt/archives.py
index 77eb5d7..214ca0e 100644
--- a/aqt/archives.py
+++ b/aqt/archives.py
@@ -22,7 +22,7 @@
import posixpath
from dataclasses import dataclass, field
from logging import getLogger
-from typing import Dict, Iterable, List, Optional, Tuple
+from typing import Dict, Iterable, List, Optional, Set, Tuple
from xml.etree.ElementTree import Element # noqa
from defusedxml import ElementTree
@@ -293,7 +293,7 @@ class QtArchives:
self.logger = getLogger("aqt.archives")
self.archives: List[QtPackage] = []
self.subarchives: Optional[Iterable[str]] = subarchives
- self.mod_list: Iterable[str] = modules or []
+ self.mod_list: Set[str] = set(modules or [])
self.is_include_base_package: bool = is_include_base_package
self.timeout = timeout
try:
|
miurahr/aqtinstall
|
eae2568e49a340d8de8d2663fc0f5ce6a94dd5e3
|
diff --git a/tests/test_install.py b/tests/test_install.py
index fc373ff..9cae23d 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -575,6 +575,30 @@ def tool_archive(host: str, tool_name: str, variant: str, date: datetime = datet
r"INFO : Time elapsed: .* second"
),
),
+ ( # Duplicates in the modules list
+ "install-qt windows desktop 6.1.0 win64_mingw81 -m qtcharts qtcharts qtcharts".split(),
+ "windows",
+ "desktop",
+ "6.1.0",
+ {"std": "win64_mingw81"},
+ {"std": "mingw81_64"},
+ {"std": "windows_x86/desktop/qt6_610/Updates.xml"},
+ {
+ "std": [
+ plain_qtbase_archive("qt.qt6.610.win64_mingw81", "win64_mingw81"),
+ qtcharts_module("6.1.0", "win64_mingw81"),
+ ]
+ },
+ re.compile(
+ r"^INFO : aqtinstall\(aqt\) v.* on Python 3.*\n"
+ r"INFO : Downloading qtbase...\n"
+ r"Finished installation of qtbase-windows-win64_mingw81.7z in .*\n"
+ r"INFO : Downloading qtcharts...\n"
+ r"Finished installation of qtcharts-windows-win64_mingw81.7z in .*\n"
+ r"INFO : Finished installation\n"
+ r"INFO : Time elapsed: .* second"
+ ),
+ ),
(
"install-qt windows android 6.1.0 android_armv7".split(),
"windows",
|
ERROR: Detected a package name collision
This bug happened to me when I added `qthttpserver` to an installation. Without `qthttpserver` everything installs fine.
List cmd:
`$ aqt list-qt linux desktop --modules 6.4.2 gcc_64`
debug_info qt3d qt5compat qtcharts qtconnectivity qtdatavis3d qthttpserver qtimageformats qtlanguageserver qtlottie qtmultimedia qtnetworkauth qtpdf qtpositioning qtquick3d qtquick3dphysics qtquicktimeline qtremoteobjects qtscxml qtsensors qtserialbus qtserialport qtshadertools qtspeech qtvirtualkeyboard qtwaylandcompositor qtwebchannel qtwebengine qtwebsockets qtwebview
Install cmd:
`$ aqt install-qt -O /opt/Qt linux desktop 6.4.2 gcc_64 --m qt5compat qtcharts qthttpserver qtimageformats qtlottie qtmultimedia qtquicktimeline qtspeech qtwebchannel qtwebsockets qthttpserver`
INFO : aqtinstall(aqt) v3.1.0 on Python 3.10.6 [CPython GCC 11.3.0]
WARNING : Specified Qt version is unknown: 6.4.2.
ERROR : Detected a package name collision
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/aqt/installer.py", line 177, in run
args.func(args)
File "/usr/local/lib/python3.10/dist-packages/aqt/installer.py", line 400, in run_install_qt
qt_archives: QtArchives = retry_on_bad_connection(
File "/usr/local/lib/python3.10/dist-packages/aqt/helper.py", line 165, in retry_on_bad_connection
return function(base_url)
File "/usr/local/lib/python3.10/dist-packages/aqt/installer.py", line 401, in <lambda>
lambda base_url: QtArchives(
File "/usr/local/lib/python3.10/dist-packages/aqt/archives.py", line 300, in __init__
self._get_archives()
File "/usr/local/lib/python3.10/dist-packages/aqt/archives.py", line 365, in _get_archives
self._get_archives_base(f"qt{self.version.major}_{self._version_str()}{self._arch_ext()}", self._target_packages())
File "/usr/local/lib/python3.10/dist-packages/aqt/archives.py", line 361, in _target_packages
target_packages.add(module, package_names)
File "/usr/local/lib/python3.10/dist-packages/aqt/archives.py", line 94, in add
assert package_name not in self._packages_to_modules, "Detected a package name collision"
AssertionError: Detected a package name collision
ERROR : aqtinstall(aqt) v3.1.0 on Python 3.10.6 [CPython GCC 11.3.0]
Working dir: `/`
Arguments: `['/usr/local/bin/aqt', 'install-qt', '-O', '/opt/Qt', 'linux', 'desktop', '6.4.2', 'gcc_64', '--m', 'qt5compat', 'qtcharts', 'qthttpserver', 'qtimageformats', 'qtlottie', 'qtmultimedia', 'qtquicktimeline', 'qtspeech', 'qtwebchannel', 'qtwebsockets', 'qthttpserver']` Host: `uname_result(system='Linux', node='4a4d7c6111e3', release='5.15.0-53-generic', version='#59-Ubuntu SMP Mon Oct 17 18:53:30 UTC 2022', machine='x86_64')`
===========================PLEASE FILE A BUG REPORT===========================
You have discovered a bug in aqt.
Please file a bug report at https://github.com/miurahr/aqtinstall/issues
Please remember to include a copy of this program's output in your report.
|
0.0
|
eae2568e49a340d8de8d2663fc0f5ce6a94dd5e3
|
[
"tests/test_install.py::test_install[cmd12-windows-desktop-6.1.0-arch12-arch_dir12-updates_url12-archives12-^INFO"
] |
[
"tests/test_install.py::test_install[cmd0-linux-desktop-1.2.3-0-197001020304-arch0-arch_dir0-updates_url0-archives0-^INFO",
"tests/test_install.py::test_install[cmd1-linux-desktop-1.2.3-arch1-arch_dir1-updates_url1-archives1-^INFO",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.14.0-arch2-arch_dir2-updates_url2-archives2-^INFO",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.14.0-arch3-arch_dir3-updates_url3-archives3-^INFO",
"tests/test_install.py::test_install[cmd4-windows-desktop-5.14.2-arch4-arch_dir4-updates_url4-archives4-^INFO",
"tests/test_install.py::test_install[cmd5-windows-desktop-5.14.2-arch5-arch_dir5-updates_url5-archives5-^INFO",
"tests/test_install.py::test_install[cmd6-windows-desktop-5.9.0-arch6-arch_dir6-updates_url6-archives6-^INFO",
"tests/test_install.py::test_install[cmd7-windows-desktop-5.9.0-arch7-arch_dir7-updates_url7-archives7-^INFO",
"tests/test_install.py::test_install[cmd8-windows-desktop-5.14.0-arch8-arch_dir8-updates_url8-archives8-^INFO",
"tests/test_install.py::test_install[cmd9-windows-desktop-5.14.0-arch9-arch_dir9-updates_url9-archives9-^INFO",
"tests/test_install.py::test_install[cmd10-windows-desktop-6.2.0-arch10-arch_dir10-updates_url10-archives10-^INFO",
"tests/test_install.py::test_install[cmd11-windows-desktop-6.1.0-arch11-arch_dir11-updates_url11-archives11-^INFO",
"tests/test_install.py::test_install[cmd13-windows-android-6.1.0-arch13-arch_dir13-updates_url13-archives13-^INFO",
"tests/test_install.py::test_install[cmd14-linux-android-6.4.1-arch14-arch_dir14-updates_url14-archives14-^INFO",
"tests/test_install.py::test_install[cmd15-linux-android-6.3.0-arch15-arch_dir15-updates_url15-archives15-^INFO",
"tests/test_install.py::test_install[cmd16-mac-ios-6.1.2-arch16-arch_dir16-updates_url16-archives16-^INFO",
"tests/test_install.py::test_install[cmd17-mac-ios-6.1.2-arch17-arch_dir17-updates_url17-archives17-^INFO",
"tests/test_install.py::test_install[cmd18-windows-desktop-6.2.4-arch18-arch_dir18-updates_url18-archives18-^INFO",
"tests/test_install.py::test_install_nonexistent_archives[install-qt",
"tests/test_install.py::test_install_nonexistent_archives[install-doc",
"tests/test_install.py::test_install_nonexistent_archives[install-example",
"tests/test_install.py::test_install_nonexistent_archives[install-tool",
"tests/test_install.py::test_install_pool_exception[RuntimeError-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_pool_exception[KeyboardInterrupt-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[MemoryError-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[MemoryError-data/settings_no_concurrency.ini-WARNING",
"tests/test_install.py::test_install_installer_archive_extraction_err",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd0-linux-desktop-1.2.3-0-197001020304---https://www.alt.qt.mirror.com-linux_x64/desktop/tools_qtcreator/Updates.xml-archives0-^INFO",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd1-windows-desktop-5.12.10-win32_mingw73-mingw73_32-https://www.alt.qt.mirror.com-windows_x86/desktop/qt5_51210/Updates.xml-archives1-^INFO"
] |
{
"failed_lite_validators": [
"has_issue_reference"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-01-07 15:03:17+00:00
|
mit
| 3,983 |
|
miurahr__aqtinstall-654
|
diff --git a/aqt/installer.py b/aqt/installer.py
index c6cc0c7..4af89c8 100644
--- a/aqt/installer.py
+++ b/aqt/installer.py
@@ -213,6 +213,21 @@ class Cli:
def _check_qt_arg_version_offline(self, version):
return version in Settings.available_offline_installer_version
+ def _warning_unknown_qt_version(self, qt_version: str) -> str:
+ return self._warning_on_bad_combination(f'Qt version "{qt_version}"')
+
+ def _warning_unknown_target_arch_combo(self, args: List[str]) -> str:
+ return self._warning_on_bad_combination(f"target combination \"{' '.join(args)}\"")
+
+ def _warning_unexpected_modules(self, unexpected_modules: List[str]) -> str:
+ return self._warning_on_bad_combination(f"modules {unexpected_modules}")
+
+ def _warning_on_bad_combination(self, combo_message: str) -> str:
+ return (
+ f"Specified {combo_message} did not exist when this version of aqtinstall was released. "
+ "This may not install properly, but we will try our best."
+ )
+
def _set_sevenzip(self, external):
sevenzip = external
if sevenzip is None:
@@ -257,13 +272,10 @@ class Cli:
return False
return True
- def _check_modules_arg(self, qt_version, modules):
- if modules is None:
- return True
+ def _select_unexpected_modules(self, qt_version: str, modules: Optional[List[str]]) -> List[str]:
+ """Returns a sorted list of all the requested modules that do not exist in the combinations.json file."""
available = Settings.available_modules(qt_version)
- if available is None:
- return False
- return all([m in available for m in modules])
+ return sorted(set(modules or []) - set(available or []))
@staticmethod
def _determine_qt_version(
@@ -388,14 +400,14 @@ class Cli:
auto_desktop_archives: List[QtPackage] = get_auto_desktop_archives()
if not self._check_qt_arg_versions(qt_version):
- self.logger.warning("Specified Qt version is unknown: {}.".format(qt_version))
+ self.logger.warning(self._warning_unknown_qt_version(qt_version))
if not self._check_qt_arg_combination(qt_version, os_name, target, arch):
- self.logger.warning(
- "Specified target combination is not valid or unknown: {} {} {}".format(os_name, target, arch)
- )
+ self.logger.warning(self._warning_unknown_target_arch_combo([os_name, target, arch]))
all_extra = True if modules is not None and "all" in modules else False
- if not all_extra and not self._check_modules_arg(qt_version, modules):
- self.logger.warning("Some of specified modules are unknown.")
+ if not all_extra:
+ unexpected_modules = self._select_unexpected_modules(qt_version, modules)
+ if unexpected_modules:
+ self.logger.warning(self._warning_unexpected_modules(unexpected_modules))
qt_archives: QtArchives = retry_on_bad_connection(
lambda base_url: QtArchives(
@@ -465,7 +477,7 @@ class Cli:
archives = args.archives
all_extra = True if modules is not None and "all" in modules else False
if not self._check_qt_arg_versions(qt_version):
- self.logger.warning("Specified Qt version is unknown: {}.".format(qt_version))
+ self.logger.warning(self._warning_unknown_qt_version(qt_version))
srcdocexamples_archives: SrcDocExamplesArchives = retry_on_bad_connection(
lambda base_url: SrcDocExamplesArchives(
@@ -562,7 +574,7 @@ class Cli:
for arch in archs:
if not self._check_tools_arg_combination(os_name, tool_name, arch):
- self.logger.warning("Specified target combination is not valid: {} {} {}".format(os_name, tool_name, arch))
+ self.logger.warning(self._warning_unknown_target_arch_combo([os_name, tool_name, arch]))
tool_archives: ToolArchives = retry_on_bad_connection(
lambda base_url: ToolArchives(
|
miurahr/aqtinstall
|
030b4282c971b41d9619bbc0d767ab3cb5553f60
|
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 055c949..91a568b 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -53,13 +53,23 @@ def test_cli_help(capsys):
assert expected_help(out)
-def test_cli_check_module():
[email protected](
+ "qt_version, modules, unexpected_modules",
+ (
+ ("5.11.3", ["qtcharts", "qtwebengine"], []),
+ ("5.11.3", ["not_exist"], ["not_exist"]),
+ ("5.11.3", ["qtcharts", "qtwebengine", "not_exist"], ["not_exist"]),
+ ("5.11.3", None, []),
+ ("5.15.0", ["Unknown"], ["Unknown"]),
+ ),
+)
+def test_cli_select_unexpected_modules(qt_version: str, modules: Optional[List[str]], unexpected_modules: List[str]):
cli = Cli()
cli._setup_settings()
- assert cli._check_modules_arg("5.11.3", ["qtcharts", "qtwebengine"])
- assert not cli._check_modules_arg("5.7", ["not_exist"])
- assert cli._check_modules_arg("5.14.0", None)
- assert not cli._check_modules_arg("5.15.0", ["Unknown"])
+ assert cli._select_unexpected_modules(qt_version, modules) == unexpected_modules
+
+ nonexistent_qt = "5.16.0"
+ assert cli._select_unexpected_modules(nonexistent_qt, modules) == sorted(modules or [])
def test_cli_check_combination():
diff --git a/tests/test_install.py b/tests/test_install.py
index 9cae23d..81a650a 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -1052,7 +1052,8 @@ def test_install(
(
"install-qt windows desktop 5.16.0 win32_mingw73",
None,
- "WARNING : Specified Qt version is unknown: 5.16.0.\n"
+ 'WARNING : Specified Qt version "5.16.0" did not exist when this version of aqtinstall was released. '
+ "This may not install properly, but we will try our best.\n"
"ERROR : Failed to locate XML data for Qt version '5.16.0'.\n"
"==============================Suggested follow-up:==============================\n"
"* Please use 'aqt list-qt windows desktop' to show versions available.\n",
@@ -1060,7 +1061,8 @@ def test_install(
(
"install-qt windows desktop 5.15.0 bad_arch",
"windows-5150-update.xml",
- "WARNING : Specified target combination is not valid or unknown: windows desktop bad_arch\n"
+ 'WARNING : Specified target combination "windows desktop bad_arch" did not exist when this version of '
+ "aqtinstall was released. This may not install properly, but we will try our best.\n"
"ERROR : The packages ['qt_base'] were not found while parsing XML of package information!\n"
"==============================Suggested follow-up:==============================\n"
"* Please use 'aqt list-qt windows desktop --arch 5.15.0' to show architectures available.\n",
@@ -1068,7 +1070,8 @@ def test_install(
(
"install-qt windows desktop 5.15.0 win32_mingw73 -m nonexistent foo",
"windows-5150-update.xml",
- "WARNING : Some of specified modules are unknown.\n"
+ "WARNING : Specified modules ['foo', 'nonexistent'] did not exist when this version of aqtinstall "
+ "was released. This may not install properly, but we will try our best.\n"
"ERROR : The packages ['foo', 'nonexistent', 'qt_base'] were not found"
" while parsing XML of package information!\n"
"==============================Suggested follow-up:==============================\n"
@@ -1106,7 +1109,8 @@ def test_install(
(
"install-tool windows desktop tools_vcredist nonexistent",
"windows-desktop-tools_vcredist-update.xml",
- "WARNING : Specified target combination is not valid: windows tools_vcredist nonexistent\n"
+ 'WARNING : Specified target combination "windows tools_vcredist nonexistent" did not exist when this version of '
+ "aqtinstall was released. This may not install properly, but we will try our best.\n"
"ERROR : The package 'nonexistent' was not found while parsing XML of package information!\n"
"==============================Suggested follow-up:==============================\n"
"* Please use 'aqt list-tool windows desktop tools_vcredist' to show tool variants available.\n",
@@ -1114,7 +1118,8 @@ def test_install(
(
"install-tool windows desktop tools_nonexistent nonexistent",
None,
- "WARNING : Specified target combination is not valid: windows tools_nonexistent nonexistent\n"
+ 'WARNING : Specified target combination "windows tools_nonexistent nonexistent" did not exist when this '
+ "version of aqtinstall was released. This may not install properly, but we will try our best.\n"
"ERROR : Failed to locate XML data for the tool 'tools_nonexistent'.\n"
"==============================Suggested follow-up:==============================\n"
"* Please use 'aqt list-tool windows desktop' to show tools available.\n",
|
Feature: make the message about "unknown" Qt versions and modules more friendly and easy to understand
**Is your feature request related to a problem? Please describe.**
Like jurplel/install-qt-action#172, there are some users who are afraid of installing unknown Qt stuff to the CI environment or their computers. To reduce confusion, we'd better make the message more friendly and easy to understand.
**Describe the solution you'd like**
Just monkey-typing:
```diff
- Specified Qt version is unknown: 6.4.5.
+ Specified Qt version "6.4.5" may be released after this version of aqtinstall. We will try our best.
```
```diff
- Some of specified modules are unknown.
+ Specified modules "foo", "bar" and "baz" may be released after this version of aqtinstall. We will try our best.
```
**Describe alternatives you've considered**
Be polite, be gentle. :)
**Additional context**
None.
/cc @ddalcino
|
0.0
|
030b4282c971b41d9619bbc0d767ab3cb5553f60
|
[
"tests/test_cli.py::test_cli_select_unexpected_modules[5.11.3-modules0-unexpected_modules0]",
"tests/test_cli.py::test_cli_select_unexpected_modules[5.11.3-modules1-unexpected_modules1]",
"tests/test_cli.py::test_cli_select_unexpected_modules[5.11.3-modules2-unexpected_modules2]",
"tests/test_cli.py::test_cli_select_unexpected_modules[5.11.3-None-unexpected_modules3]",
"tests/test_cli.py::test_cli_select_unexpected_modules[5.15.0-modules4-unexpected_modules4]",
"tests/test_install.py::test_install_nonexistent_archives[install-qt",
"tests/test_install.py::test_install_nonexistent_archives[install-tool"
] |
[
"tests/test_cli.py::test_cli_help",
"tests/test_cli.py::test_cli_check_combination",
"tests/test_cli.py::test_cli_check_version",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-6.1-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5.12-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5.13-expected_version2-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-5-expected_version3-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-wasm_32-<5.14.5-expected_version4-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-mingw32-6.0-expected_version5-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-winrt-mingw32-6-None-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-winrt-mingw32-bad",
"tests/test_cli.py::test_cli_determine_qt_version[windows-android-android_x86-6-expected_version8-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-android_x86-6-expected_version9-False]",
"tests/test_cli.py::test_cli_determine_qt_version[windows-desktop-android_fake-6-expected_version10-False]",
"tests/test_cli.py::test_cli_invalid_version[5.15]",
"tests/test_cli.py::test_cli_invalid_version[five-dot-fifteen]",
"tests/test_cli.py::test_cli_invalid_version[5]",
"tests/test_cli.py::test_cli_invalid_version[5.5.5.5]",
"tests/test_cli.py::test_cli_validate_version[1.2.3-False-False-False-True]",
"tests/test_cli.py::test_cli_validate_version[1.2.-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[latest-True-False-False-True]",
"tests/test_cli.py::test_cli_validate_version[latest-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[-False-True-False-True]",
"tests/test_cli.py::test_cli_validate_version[-False-False-False-False]",
"tests/test_cli.py::test_cli_validate_version[1.2.3-0-123-False-False-True-True]",
"tests/test_cli.py::test_cli_validate_version[1.2.3-0-123-False-False-False-False]",
"tests/test_cli.py::test_cli_check_mirror",
"tests/test_cli.py::test_set_arch[impossible_arch-windows-desktop-6.2.0-impossible_arch]",
"tests/test_cli.py::test_set_arch[-windows-desktop-6.2.0-None]",
"tests/test_cli.py::test_set_arch[None-windows-desktop-6.2.0-None]",
"tests/test_cli.py::test_set_arch[None-linux-desktop-6.2.0-gcc_64]",
"tests/test_cli.py::test_set_arch[None-mac-desktop-6.2.0-clang_64]",
"tests/test_cli.py::test_set_arch[None-mac-ios-6.2.0-ios]",
"tests/test_cli.py::test_set_arch[None-mac-android-6.2.0-android]",
"tests/test_cli.py::test_set_arch[None-mac-android-5.12.0-None]",
"tests/test_cli.py::test_set_arch[impossible_arch-windows-desktop-6.2-impossible_arch]",
"tests/test_cli.py::test_set_arch[-windows-desktop-6.2-None]",
"tests/test_cli.py::test_set_arch[None-windows-desktop-6.2-None]",
"tests/test_cli.py::test_set_arch[None-linux-desktop-6.2-gcc_64]",
"tests/test_cli.py::test_set_arch[None-mac-desktop-6.2-clang_64]",
"tests/test_cli.py::test_set_arch[None-mac-ios-6.2-ios]",
"tests/test_cli.py::test_set_arch[None-mac-android-6.2-None]",
"tests/test_cli.py::test_cli_input_errors[install-qt",
"tests/test_cli.py::test_cli_input_errors[install-src",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[install",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[src",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[doc",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[example",
"tests/test_cli.py::test_cli_legacy_commands_with_wrong_syntax[tool",
"tests/test_cli.py::test_cli_legacy_tool_new_syntax[tool",
"tests/test_cli.py::test_cli_list_qt_deprecated_flags[list-qt",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[install",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[src",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[doc",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[examples",
"tests/test_cli.py::test_cli_legacy_commands_with_correct_syntax[tool",
"tests/test_cli.py::test_cli_unexpected_error",
"tests/test_cli.py::test_cli_set_7zip",
"tests/test_cli.py::test_cli_choose_archive_dest[None-False-temp-temp-False]",
"tests/test_cli.py::test_cli_choose_archive_dest[None-True-temp-.-False]",
"tests/test_cli.py::test_cli_choose_archive_dest[my_archives-False-temp-my_archives-True]",
"tests/test_cli.py::test_cli_choose_archive_dest[my_archives-True-temp-my_archives-True]",
"tests/test_cli.py::test_get_autodesktop_dir_and_arch[windows-False-win64_mingw99-existing_arch_dirs0-expect0]",
"tests/test_cli.py::test_get_autodesktop_dir_and_arch[windows-False-win64_mingw99-existing_arch_dirs1-expect1]",
"tests/test_cli.py::test_get_autodesktop_dir_and_arch[linux-False-None-existing_arch_dirs2-expect2]",
"tests/test_cli.py::test_get_autodesktop_dir_and_arch[linux-False-None-existing_arch_dirs3-expect3]",
"tests/test_cli.py::test_get_autodesktop_dir_and_arch[windows-True-win64_mingw99-existing_arch_dirs4-expect4]",
"tests/test_cli.py::test_get_autodesktop_dir_and_arch[windows-True-win64_mingw99-existing_arch_dirs5-expect5]",
"tests/test_cli.py::test_get_autodesktop_dir_and_arch[linux-True-None-existing_arch_dirs6-expect6]",
"tests/test_cli.py::test_get_autodesktop_dir_and_arch[linux-True-None-existing_arch_dirs7-expect7]",
"tests/test_install.py::test_install[cmd0-linux-desktop-1.2.3-0-197001020304-arch0-arch_dir0-updates_url0-archives0-^INFO",
"tests/test_install.py::test_install[cmd1-linux-desktop-1.2.3-arch1-arch_dir1-updates_url1-archives1-^INFO",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.14.0-arch2-arch_dir2-updates_url2-archives2-^INFO",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.14.0-arch3-arch_dir3-updates_url3-archives3-^INFO",
"tests/test_install.py::test_install[cmd4-windows-desktop-5.14.2-arch4-arch_dir4-updates_url4-archives4-^INFO",
"tests/test_install.py::test_install[cmd5-windows-desktop-5.14.2-arch5-arch_dir5-updates_url5-archives5-^INFO",
"tests/test_install.py::test_install[cmd6-windows-desktop-5.9.0-arch6-arch_dir6-updates_url6-archives6-^INFO",
"tests/test_install.py::test_install[cmd7-windows-desktop-5.9.0-arch7-arch_dir7-updates_url7-archives7-^INFO",
"tests/test_install.py::test_install[cmd8-windows-desktop-5.14.0-arch8-arch_dir8-updates_url8-archives8-^INFO",
"tests/test_install.py::test_install[cmd9-windows-desktop-5.14.0-arch9-arch_dir9-updates_url9-archives9-^INFO",
"tests/test_install.py::test_install[cmd10-windows-desktop-6.2.0-arch10-arch_dir10-updates_url10-archives10-^INFO",
"tests/test_install.py::test_install[cmd11-windows-desktop-6.1.0-arch11-arch_dir11-updates_url11-archives11-^INFO",
"tests/test_install.py::test_install[cmd12-windows-desktop-6.1.0-arch12-arch_dir12-updates_url12-archives12-^INFO",
"tests/test_install.py::test_install[cmd13-windows-android-6.1.0-arch13-arch_dir13-updates_url13-archives13-^INFO",
"tests/test_install.py::test_install[cmd14-linux-android-6.4.1-arch14-arch_dir14-updates_url14-archives14-^INFO",
"tests/test_install.py::test_install[cmd15-linux-android-6.3.0-arch15-arch_dir15-updates_url15-archives15-^INFO",
"tests/test_install.py::test_install[cmd16-mac-ios-6.1.2-arch16-arch_dir16-updates_url16-archives16-^INFO",
"tests/test_install.py::test_install[cmd17-mac-ios-6.1.2-arch17-arch_dir17-updates_url17-archives17-^INFO",
"tests/test_install.py::test_install[cmd18-windows-desktop-6.2.4-arch18-arch_dir18-updates_url18-archives18-^INFO",
"tests/test_install.py::test_install_nonexistent_archives[install-doc",
"tests/test_install.py::test_install_nonexistent_archives[install-example",
"tests/test_install.py::test_install_pool_exception[RuntimeError-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_pool_exception[KeyboardInterrupt-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[MemoryError-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[MemoryError-data/settings_no_concurrency.ini-WARNING",
"tests/test_install.py::test_install_installer_archive_extraction_err",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd0-linux-desktop-1.2.3-0-197001020304---https://www.alt.qt.mirror.com-linux_x64/desktop/tools_qtcreator/Updates.xml-archives0-^INFO",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd1-windows-desktop-5.12.10-win32_mingw73-mingw73_32-https://www.alt.qt.mirror.com-windows_x86/desktop/qt5_51210/Updates.xml-archives1-^INFO"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-02-16 22:38:38+00:00
|
mit
| 3,984 |
|
miurahr__aqtinstall-657
|
diff --git a/aqt/exceptions.py b/aqt/exceptions.py
index 012a8c8..972488c 100644
--- a/aqt/exceptions.py
+++ b/aqt/exceptions.py
@@ -102,3 +102,11 @@ class UpdaterError(AqtException):
class OutOfMemory(AqtException):
pass
+
+
+class OutOfDiskSpace(AqtException):
+ pass
+
+
+class DiskAccessNotPermitted(AqtException):
+ pass
diff --git a/aqt/installer.py b/aqt/installer.py
index 4af89c8..a27fd2e 100644
--- a/aqt/installer.py
+++ b/aqt/installer.py
@@ -22,6 +22,7 @@
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import argparse
+import errno
import gc
import multiprocessing
import os
@@ -47,6 +48,8 @@ from aqt.exceptions import (
ArchiveListError,
CliInputError,
CliKeyboardInterrupt,
+ DiskAccessNotPermitted,
+ OutOfDiskSpace,
OutOfMemory,
)
from aqt.helper import (
@@ -1127,6 +1130,23 @@ def run_installer(archives: List[QtPackage], base_dir: str, sevenzip: Optional[s
pool.starmap(installer, tasks)
pool.close()
pool.join()
+ except PermissionError as e: # subclass of OSError
+ close_worker_pool_on_exception(e)
+ raise DiskAccessNotPermitted(
+ f"Failed to write to base directory at {base_dir}",
+ suggested_action=[
+ "Check that the destination is writable and does not already contain files owned by another user."
+ ],
+ ) from e
+ except OSError as e:
+ close_worker_pool_on_exception(e)
+ if e.errno == errno.ENOSPC:
+ raise OutOfDiskSpace(
+ "Insufficient disk space to complete installation.",
+ suggested_action=["Check available disk space.", "Check size requirements for installation."],
+ ) from e
+ else:
+ raise
except KeyboardInterrupt as e:
close_worker_pool_on_exception(e)
raise CliKeyboardInterrupt("Installer halted by keyboard interrupt.") from e
|
miurahr/aqtinstall
|
702a0246acacb6ab0ba56ef05b8ce4721f632e4e
|
diff --git a/tests/test_install.py b/tests/test_install.py
index 81a650a..45e4535 100644
--- a/tests/test_install.py
+++ b/tests/test_install.py
@@ -1,3 +1,4 @@
+import errno
import hashlib
import logging
import os
@@ -1156,10 +1157,10 @@ def test_install_nonexistent_archives(monkeypatch, capsys, cmd, xml_file: Option
@pytest.mark.parametrize(
- "exception_class, settings_file, expect_end_msg, expect_return",
+ "exception, settings_file, expect_end_msg, expect_return",
(
(
- RuntimeError,
+ RuntimeError(),
"../aqt/settings.ini",
"===========================PLEASE FILE A BUG REPORT===========================\n"
"You have discovered a bug in aqt.\n"
@@ -1168,14 +1169,14 @@ def test_install_nonexistent_archives(monkeypatch, capsys, cmd, xml_file: Option
Cli.UNHANDLED_EXCEPTION_CODE,
),
(
- KeyboardInterrupt,
+ KeyboardInterrupt(),
"../aqt/settings.ini",
"WARNING : Caught KeyboardInterrupt, terminating installer workers\n"
"ERROR : Installer halted by keyboard interrupt.",
1,
),
(
- MemoryError,
+ MemoryError(),
"../aqt/settings.ini",
"WARNING : Caught MemoryError, terminating installer workers\n"
"ERROR : Out of memory when downloading and extracting archives in parallel.\n"
@@ -1187,7 +1188,7 @@ def test_install_nonexistent_archives(monkeypatch, capsys, cmd, xml_file: Option
1,
),
(
- MemoryError,
+ MemoryError(),
"data/settings_no_concurrency.ini",
"WARNING : Caught MemoryError, terminating installer workers\n"
"ERROR : Out of memory when downloading and extracting archives.\n"
@@ -1197,11 +1198,39 @@ def test_install_nonexistent_archives(monkeypatch, capsys, cmd, xml_file: Option
"(see https://aqtinstall.readthedocs.io/en/latest/cli.html#cmdoption-list-tool-external)",
1,
),
+ (
+ OSError(errno.ENOSPC, "No space left on device"),
+ "../aqt/settings.ini",
+ "WARNING : Caught OSError, terminating installer workers\n"
+ "ERROR : Insufficient disk space to complete installation.\n"
+ "==============================Suggested follow-up:==============================\n"
+ "* Check available disk space.\n"
+ "* Check size requirements for installation.",
+ 1,
+ ),
+ (
+ OSError(),
+ "../aqt/settings.ini",
+ "===========================PLEASE FILE A BUG REPORT===========================\n"
+ "You have discovered a bug in aqt.\n"
+ "Please file a bug report at https://github.com/miurahr/aqtinstall/issues\n"
+ "Please remember to include a copy of this program's output in your report.",
+ Cli.UNHANDLED_EXCEPTION_CODE,
+ ),
+ (
+ PermissionError(),
+ "../aqt/settings.ini",
+ "WARNING : Caught PermissionError, terminating installer workers\n"
+ f"ERROR : Failed to write to base directory at {os.getcwd()}\n"
+ "==============================Suggested follow-up:==============================\n"
+ "* Check that the destination is writable and does not already contain files owned by another user.",
+ 1,
+ ),
),
)
-def test_install_pool_exception(monkeypatch, capsys, exception_class, settings_file, expect_end_msg, expect_return):
+def test_install_pool_exception(monkeypatch, capsys, exception, settings_file, expect_end_msg, expect_return):
def mock_installer_func(*args):
- raise exception_class()
+ raise exception
host, target, ver, arch = "windows", "desktop", "6.1.0", "win64_mingw81"
updates_url = "windows_x86/desktop/qt6_610/Updates.xml"
|
Installation of 6.4.0 win64_msvc2019_64 fails on azure devops pipeline runner on windows_2019 image
**Describe the bug**
when I execute
` aqt install-qt --outputdir $(Build.BinariesDirectory)\\Qt windows desktop 6.4.0 win64_msvc2019_64 -m all `
the script aborts with disk full exception
But this disk D drive has 12GByte free space before
windows-latest or windows-2022 image do not have MSVC2019 whereas windows-2019 image has.
So I choose windows-2019 image
**To Reproduce**
Steps to reproduce the behavior:
# 1
```
- script: |
cd $(Build.BinariesDirectory)
python -m pip install aqtinstall
echo "Installing Qt to $(Build.BinariesDirectory)"
echo "install qt 6.4.0"
aqt install-qt --outputdir $(Build.BinariesDirectory)\\Qt windows desktop 6.4.0 win64_msvc2019_64 -m all
```
**Expected behavior**
A clear and concise description of what you expected to happen.
**`aqt` output**
Add program output to help explain your problem.
```
INFO : aqtinstall(aqt) v3.0.1 on Python 3.10.7 [CPython MSC v.1933 64 bit (AMD64)]
INFO : Downloading qt3d...
INFO : Downloading qthttpserver...
INFO : Downloading qtnetworkauth...
INFO : Downloading qtquicktimeline...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of qtquicktimeline-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64.7z in 1.48560150
INFO : Downloading qtshadertools...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of qtshadertools-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64.7z in 1.48801890
INFO : Downloading qtbase...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of qtdeclarative-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64-debug-symbols.7z in 44.93251080
INFO : Downloading qttools...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of qtdeclarative-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64.7z in 35.35354360
INFO : Downloading qttools...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of qttools-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64-debug-symbols.7z in 14.13964240
INFO : Downloading qt5compat...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of qt5compat-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64-debug-symbols.7z in 2.23388360
INFO : Finished installation of qtbase-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64.7z in 24.40250470
INFO : Downloading qtsvg...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of qtsvg-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64.7z in 1.05774990
INFO : Finished installation of qttools-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64.7z in 8.52346590
INFO : Downloading qttranslations...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of qttranslations-Windows-Windows_10_21H2-MSVC2019-Windows-Windows_10_21H2-X86_64.7z in 1.42207410
INFO : Downloading d3dcompiler_47...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of d3dcompiler_47-x64.7z in 1.22245150
INFO : Downloading opengl32sw...
INFO : Redirected: qt.mirror.constant.com
INFO : Finished installation of opengl32sw-64-mesa_11_2_2-signed.7z in 1.74708810
WARNING : Caught OSError, terminating installer workers
ERROR : [Errno 28] No space left on device
Traceback (most recent call last):
File "C:\hostedtoolcache\windows\Python\3.10.7\x64\lib\site-packages\aqt\installer.py", line 108, in run
args.func(args)
File "C:\hostedtoolcache\windows\Python\3.10.7\x64\lib\site-packages\aqt\installer.py", line 348, in run_install_qt
run_installer(qt_archives.get_packages(), base_dir, sevenzip, keep, _archive_dest)
File "C:\hostedtoolcache\windows\Python\3.10.7\x64\lib\site-packages\aqt\installer.py", line 1055, in run_installer
raise e from e
File "C:\hostedtoolcache\windows\Python\3.10.7\x64\lib\site-packages\aqt\installer.py", line 1031, in run_installer
pool.starmap(installer, tasks)
File "C:\hostedtoolcache\windows\Python\3.10.7\x64\lib\multiprocessing\pool.py", line 375, in starmap
return self._map_async(func, iterable, starmapstar, chunksize).get()
File "C:\hostedtoolcache\windows\Python\3.10.7\x64\lib\multiprocessing\pool.py", line 774, in get
raise self._value
OSError: [Errno 28] No space left on device
ERROR : aqtinstall(aqt) v3.0.1 on Python 3.10.7 [CPython MSC v.1933 64 bit (AMD64)]
Working dir: `D:\a\1\b`
Arguments: `['C:\\hostedtoolcache\\windows\\Python\\3.10.7\\x64\\Scripts\\aqt', 'install-qt', '--outputdir', 'D:\\a\\1\\b\\\\Qt', 'windows', 'desktop', '6.4.0', 'win64_msvc2019_64', '-m', 'all']` Host: `uname_result(system='Windows', node='fv-az182-616', release='10', version='10.0.17763', machine='AMD64')`
===========================PLEASE FILE A BUG REPORT===========================
You have discovered a bug in aqt.
Please file a bug report at https://github.com/miurahr/aqtinstall/issues.
Please remember to include a copy of this program's output in your report.
##[error]Cmd.exe exited with code '254'.
```
**Desktop (please complete the following information):**
- windows-2019 image https://github.com/actions/runner-images/blob/main/images/win/Windows2019-Readme.md
- `aqt` version [paste the output from the command `aqt version` or `python -m aqt version`]
**Additional context**
Add any other context about the problem here.
|
0.0
|
702a0246acacb6ab0ba56ef05b8ce4721f632e4e
|
[
"tests/test_install.py::test_install_pool_exception[exception4-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[exception6-../aqt/settings.ini-WARNING"
] |
[
"tests/test_install.py::test_install[cmd0-linux-desktop-1.2.3-0-197001020304-arch0-arch_dir0-updates_url0-archives0-^INFO",
"tests/test_install.py::test_install[cmd1-linux-desktop-1.2.3-arch1-arch_dir1-updates_url1-archives1-^INFO",
"tests/test_install.py::test_install[cmd2-windows-desktop-5.14.0-arch2-arch_dir2-updates_url2-archives2-^INFO",
"tests/test_install.py::test_install[cmd3-windows-desktop-5.14.0-arch3-arch_dir3-updates_url3-archives3-^INFO",
"tests/test_install.py::test_install[cmd4-windows-desktop-5.14.2-arch4-arch_dir4-updates_url4-archives4-^INFO",
"tests/test_install.py::test_install[cmd5-windows-desktop-5.14.2-arch5-arch_dir5-updates_url5-archives5-^INFO",
"tests/test_install.py::test_install[cmd6-windows-desktop-5.9.0-arch6-arch_dir6-updates_url6-archives6-^INFO",
"tests/test_install.py::test_install[cmd7-windows-desktop-5.9.0-arch7-arch_dir7-updates_url7-archives7-^INFO",
"tests/test_install.py::test_install[cmd8-windows-desktop-5.14.0-arch8-arch_dir8-updates_url8-archives8-^INFO",
"tests/test_install.py::test_install[cmd9-windows-desktop-5.14.0-arch9-arch_dir9-updates_url9-archives9-^INFO",
"tests/test_install.py::test_install[cmd10-windows-desktop-6.2.0-arch10-arch_dir10-updates_url10-archives10-^INFO",
"tests/test_install.py::test_install[cmd11-windows-desktop-6.1.0-arch11-arch_dir11-updates_url11-archives11-^INFO",
"tests/test_install.py::test_install[cmd12-windows-desktop-6.1.0-arch12-arch_dir12-updates_url12-archives12-^INFO",
"tests/test_install.py::test_install[cmd13-windows-android-6.1.0-arch13-arch_dir13-updates_url13-archives13-^INFO",
"tests/test_install.py::test_install[cmd14-linux-android-6.4.1-arch14-arch_dir14-updates_url14-archives14-^INFO",
"tests/test_install.py::test_install[cmd15-linux-android-6.3.0-arch15-arch_dir15-updates_url15-archives15-^INFO",
"tests/test_install.py::test_install[cmd16-mac-ios-6.1.2-arch16-arch_dir16-updates_url16-archives16-^INFO",
"tests/test_install.py::test_install[cmd17-mac-ios-6.1.2-arch17-arch_dir17-updates_url17-archives17-^INFO",
"tests/test_install.py::test_install[cmd18-windows-desktop-6.2.4-arch18-arch_dir18-updates_url18-archives18-^INFO",
"tests/test_install.py::test_install_nonexistent_archives[install-qt",
"tests/test_install.py::test_install_nonexistent_archives[install-doc",
"tests/test_install.py::test_install_nonexistent_archives[install-example",
"tests/test_install.py::test_install_nonexistent_archives[install-tool",
"tests/test_install.py::test_install_pool_exception[exception0-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_pool_exception[exception1-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[exception2-../aqt/settings.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[exception3-data/settings_no_concurrency.ini-WARNING",
"tests/test_install.py::test_install_pool_exception[exception5-../aqt/settings.ini-===========================PLEASE",
"tests/test_install.py::test_install_installer_archive_extraction_err",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd0-linux-desktop-1.2.3-0-197001020304---https://www.alt.qt.mirror.com-linux_x64/desktop/tools_qtcreator/Updates.xml-archives0-^INFO",
"tests/test_install.py::test_installer_passes_base_to_metadatafactory[cmd1-windows-desktop-5.12.10-win32_mingw73-mingw73_32-https://www.alt.qt.mirror.com-windows_x86/desktop/qt5_51210/Updates.xml-archives1-^INFO"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-03-14 00:53:59+00:00
|
mit
| 3,985 |
|
mixkorshun__django-antispam-6
|
diff --git a/antispam/akismet/entities.py b/antispam/akismet/entities.py
index 91d766a..a620516 100644
--- a/antispam/akismet/entities.py
+++ b/antispam/akismet/entities.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from .utils import get_client_ip, get_timestamp
+from .utils import get_client_ip
class Request:
@@ -152,7 +152,7 @@ class Comment:
params = {
'comment_type': self.type,
'comment_content': self.content,
- 'comment_date': get_timestamp(self.created),
+ 'comment_date': self.created,
'permalink': self.permalink,
}
diff --git a/antispam/akismet/utils.py b/antispam/akismet/utils.py
index b6cdf72..c292c1a 100644
--- a/antispam/akismet/utils.py
+++ b/antispam/akismet/utils.py
@@ -18,11 +18,3 @@ def get_client_ip(request):
return x_forwarded_for.split(',')[0]
return request.META.get('REMOTE_ADDR')
-
-
-def get_timestamp(dt):
- try:
- return int(dt.timestamp())
- except AttributeError:
- import time
- return int(time.mktime(dt.timetuple()))
|
mixkorshun/django-antispam
|
af42b24ee4dd5d9607e5f8ac0cffb434f9a63e0a
|
diff --git a/tests/akismet/test_entities.py b/tests/akismet/test_entities.py
index 2f92116..c1e536d 100644
--- a/tests/akismet/test_entities.py
+++ b/tests/akismet/test_entities.py
@@ -70,7 +70,7 @@ class CommentTests(TestCase):
self.assertEqual({
'comment_content': '<my comment>',
- 'comment_date': int(time.mktime(comment.created.timetuple())),
+ 'comment_date': comment.created,
'comment_type': 'comment',
'permalink': 'http://mike.example.com/comment-1/',
}, comment.as_params())
|
Akismet: AssertionError on comment_date type
python-akismet expects comment_date to be `datetime`, not a timestamp:
https://github.com/Nekmo/python-akismet/blob/322cf3e9a9a1986434a20e01cabb6767e91a226b/akismet/__init__.py#L49
django-antispam provides a timestamp:
https://github.com/mixkorshun/django-antispam/blob/3b193a8360ff8171f0c6d7cc1891fab0b69d0e0a/antispam/akismet/entities.py#L155
So I get an `AssertionError` when calling `akismet.check`
|
0.0
|
af42b24ee4dd5d9607e5f8ac0cffb434f9a63e0a
|
[
"tests/akismet/test_entities.py::CommentTests::test_to_params"
] |
[
"tests/akismet/test_entities.py::AuthorTests::test_to_params",
"tests/akismet/test_entities.py::AuthorTests::test_from_django_user",
"tests/akismet/test_entities.py::SiteTests::test_to_params",
"tests/akismet/test_entities.py::RequestTests::test_to_params",
"tests/akismet/test_entities.py::RequestTests::test_from_django_request",
"tests/akismet/test_entities.py::CommentTests::test_to_params_related_resources"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-03-22 13:02:25+00:00
|
mit
| 3,986 |
|
miyuchina__mistletoe-57
|
diff --git a/mistletoe/block_token.py b/mistletoe/block_token.py
index 0a4c2c0..7eeb3f1 100644
--- a/mistletoe/block_token.py
+++ b/mistletoe/block_token.py
@@ -574,6 +574,9 @@ class ListItem(BlockToken):
if not cls.in_continuation(next_line, prepend):
# directly followed by another token
if cls.other_token(next_line):
+ if newline:
+ lines.backstep()
+ del line_buffer[-newline:]
break
# next_line is a new list item
marker_info = cls.parse_marker(next_line)
|
miyuchina/mistletoe
|
8cca7a53626e8c25039423dc9cd8db843447f813
|
diff --git a/test/test_block_token.py b/test/test_block_token.py
index b3c94b1..78fb0b2 100644
--- a/test/test_block_token.py
+++ b/test/test_block_token.py
@@ -191,6 +191,14 @@ class TestListItem(unittest.TestCase):
list_item = block_token.tokenize(lines)[0].children[0]
self.assertEqual(list_item.loose, False)
+ def test_tight_list(self):
+ lines = ['- foo\n',
+ '\n',
+ '# bar\n']
+ f = FileWrapper(lines)
+ list_item = block_token.tokenize(lines)[0].children[0]
+ self.assertEqual(list_item.loose, False)
+
class TestList(unittest.TestCase):
def test_different_markers(self):
|
lists should not contain <p>
Why do you use <p></p> in lists ? This is not the way Commonmark does it.
Other strange behavior: in the same document, some lists get the paragraphs, some others don't. Could you explain how it is supposed to work ?
|
0.0
|
8cca7a53626e8c25039423dc9cd8db843447f813
|
[
"test/test_block_token.py::TestListItem::test_tight_list"
] |
[
"test/test_block_token.py::TestATXHeading::test_children_with_enclosing_hashes",
"test/test_block_token.py::TestATXHeading::test_heading_in_paragraph",
"test/test_block_token.py::TestATXHeading::test_match",
"test/test_block_token.py::TestATXHeading::test_not_heading",
"test/test_block_token.py::TestSetextHeading::test_match",
"test/test_block_token.py::TestSetextHeading::test_next",
"test/test_block_token.py::TestQuote::test_lazy_continuation",
"test/test_block_token.py::TestQuote::test_match",
"test/test_block_token.py::TestCodeFence::test_fence_code_lazy_continuation",
"test/test_block_token.py::TestCodeFence::test_match_fenced_code",
"test/test_block_token.py::TestCodeFence::test_match_fenced_code_with_tilda",
"test/test_block_token.py::TestCodeFence::test_mixed_code_fence",
"test/test_block_token.py::TestCodeFence::test_no_wrapping_newlines_code_fence",
"test/test_block_token.py::TestCodeFence::test_unclosed_code_fence",
"test/test_block_token.py::TestBlockCode::test_parse_indented_code",
"test/test_block_token.py::TestParagraph::test_parse",
"test/test_block_token.py::TestParagraph::test_read",
"test/test_block_token.py::TestListItem::test_deep_list",
"test/test_block_token.py::TestListItem::test_loose_list",
"test/test_block_token.py::TestListItem::test_parse_marker",
"test/test_block_token.py::TestListItem::test_sublist",
"test/test_block_token.py::TestListItem::test_tokenize",
"test/test_block_token.py::TestList::test_different_markers",
"test/test_block_token.py::TestList::test_sublist",
"test/test_block_token.py::TestTable::test_easy_table",
"test/test_block_token.py::TestTable::test_match",
"test/test_block_token.py::TestTable::test_not_easy_table",
"test/test_block_token.py::TestTable::test_parse_align",
"test/test_block_token.py::TestTable::test_parse_delimiter",
"test/test_block_token.py::TestTableRow::test_easy_table_row",
"test/test_block_token.py::TestTableRow::test_match",
"test/test_block_token.py::TestTableCell::test_match",
"test/test_block_token.py::TestFootnote::test_store",
"test/test_block_token.py::TestDocument::test_auto_splitlines",
"test/test_block_token.py::TestDocument::test_store_footnote",
"test/test_block_token.py::TestThematicBreak::test_match",
"test/test_block_token.py::TestContains::test_contains"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2018-09-02 15:07:48+00:00
|
mit
| 3,987 |
|
mjs__imapclient-244
|
diff --git a/imapclient/response_types.py b/imapclient/response_types.py
index ea5d71d..c35dd00 100644
--- a/imapclient/response_types.py
+++ b/imapclient/response_types.py
@@ -80,9 +80,12 @@ class Address(namedtuple("Address", "name route mailbox host")):
"""
def __str__(self):
- return formataddr((
- to_unicode(self.name),
- to_unicode(self.mailbox) + '@' + to_unicode(self.host)))
+ if self.mailbox and self.host:
+ address = to_unicode(self.mailbox) + '@' + to_unicode(self.host)
+ else:
+ address = to_unicode(self.mailbox or self.host)
+
+ return formataddr((to_unicode(self.name), address))
class SearchIds(list):
|
mjs/imapclient
|
9e82aa8e7fe0a8cd3b9b6318579a873c9a1bdde6
|
diff --git a/imapclient/test/test_response_parser.py b/imapclient/test/test_response_parser.py
index 3c13534..111188b 100644
--- a/imapclient/test/test_response_parser.py
+++ b/imapclient/test/test_response_parser.py
@@ -491,6 +491,12 @@ class TestParseFetchResponse(unittest.TestCase):
self.assertEqual(str(Address("Mary Jane", None, "mary", "jane.org")),
"Mary Jane <[email protected]>")
+ self.assertEqual(str(Address("Anonymous", None, "undisclosed-recipients", None)),
+ "Anonymous <undisclosed-recipients>")
+
+ self.assertEqual(str(Address(None, None, None, "undisclosed-recipients")),
+ "undisclosed-recipients")
+
def add_crlf(text):
|
Avoid TypeError when using `str` on Address tuple
Some emails have no mailbox or host (e.g. `undisclosed-recipients` case), so when parsing the ENVELOPE of the message using imapclient, we can get something like this:
```
In [8]: from imapclient.response_types import *
In [9]: addr = Address('Anonymous', None, None, 'undisclosed-recipients')
In [10]: str(addr)
---------------------------------------------------------------------------
.../lib/python3.5/site-packages/imapclient/response_types.py in __str__(self)
57 return formataddr((
58 to_unicode(self.name),
---> 59 to_unicode(self.mailbox) + '@' + to_unicode(self.host)))
60
61
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
```
I think the `__str__` method should handle this and just returning `self.mailbox` or `self.host` if the other part is missing. I could write the PR but I prefer to have thoughs about this before.
|
0.0
|
9e82aa8e7fe0a8cd3b9b6318579a873c9a1bdde6
|
[
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_Address_str"
] |
[
"imapclient/test/test_response_parser.py::TestParseResponse::test_bad_literal",
"imapclient/test/test_response_parser.py::TestParseResponse::test_bad_quoting",
"imapclient/test/test_response_parser.py::TestParseResponse::test_complex_mixed",
"imapclient/test/test_response_parser.py::TestParseResponse::test_deeper_nest_tuple",
"imapclient/test/test_response_parser.py::TestParseResponse::test_empty_tuple",
"imapclient/test/test_response_parser.py::TestParseResponse::test_envelopey",
"imapclient/test/test_response_parser.py::TestParseResponse::test_envelopey_quoted",
"imapclient/test/test_response_parser.py::TestParseResponse::test_incomplete_tuple",
"imapclient/test/test_response_parser.py::TestParseResponse::test_int",
"imapclient/test/test_response_parser.py::TestParseResponse::test_int_and_tuple",
"imapclient/test/test_response_parser.py::TestParseResponse::test_literal",
"imapclient/test/test_response_parser.py::TestParseResponse::test_literal_with_more",
"imapclient/test/test_response_parser.py::TestParseResponse::test_nested_tuple",
"imapclient/test/test_response_parser.py::TestParseResponse::test_nil",
"imapclient/test/test_response_parser.py::TestParseResponse::test_quoted_specials",
"imapclient/test/test_response_parser.py::TestParseResponse::test_square_brackets",
"imapclient/test/test_response_parser.py::TestParseResponse::test_string",
"imapclient/test/test_response_parser.py::TestParseResponse::test_tuple",
"imapclient/test/test_response_parser.py::TestParseResponse::test_unquoted",
"imapclient/test/test_response_parser.py::TestParseMessageList::test_basic",
"imapclient/test/test_response_parser.py::TestParseMessageList::test_modseq",
"imapclient/test/test_response_parser.py::TestParseMessageList::test_modseq_interleaved",
"imapclient/test/test_response_parser.py::TestParseMessageList::test_modseq_no_space",
"imapclient/test/test_response_parser.py::TestParseMessageList::test_one_id",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_BODY",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_BODYSTRUCTURE",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_BODY_HEADER_FIELDS",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_empty_addresses",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_invalid_date",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_no_date",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_FLAGS",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE_normalised",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_UID",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_bad_UID",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_bad_data",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_bad_msgid",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_basic",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_literals",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_literals_and_keys_with_square_brackets",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_missing_data",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_mixed_types",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_multiple_messages",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_none_special_case",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_not_uid_is_key",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_odd_pairs",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_partial_fetch",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_same_message_appearing_multiple_times",
"imapclient/test/test_response_parser.py::TestParseFetchResponse::test_simple_pairs"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-06-26 19:38:01+00:00
|
bsd-3-clause
| 3,988 |
|
mjs__imapclient-277
|
diff --git a/doc/src/releases.rst b/doc/src/releases.rst
index 17c0f07..3e6c672 100644
--- a/doc/src/releases.rst
+++ b/doc/src/releases.rst
@@ -6,6 +6,7 @@
Changed
-------
+- Connections to servers use SSL/TLS by default (`ssl=True`)
- XXX Use built-in TLS when sensible.
- Logs are now handled by the Python logging module. `debug` and `log_file`
are not used anymore.
diff --git a/imapclient/config.py b/imapclient/config.py
index b6d243a..ebff841 100644
--- a/imapclient/config.py
+++ b/imapclient/config.py
@@ -28,7 +28,7 @@ def get_config_defaults():
return dict(
username=getenv("username", None),
password=getenv("password", None),
- ssl=False,
+ ssl=True,
ssl_check_hostname=True,
ssl_verify_cert=True,
ssl_ca_file=None,
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index 3776e18..3792a1f 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -85,16 +85,17 @@ class IMAPClient(object):
"""A connection to the IMAP server specified by *host* is made when
this class is instantiated.
- *port* defaults to 143, or 993 if *ssl* is ``True``.
+ *port* defaults to 993, or 143 if *ssl* is ``False``.
If *use_uid* is ``True`` unique message UIDs be used for all calls
that accept message ids (defaults to ``True``).
- If *ssl* is ``True`` an SSL connection will be made (defaults to
- ``False``).
+ If *ssl* is ``True`` (the default) a secure connection will be made.
+ Otherwise an insecure connection over plain text will be
+ established.
If *ssl* is ``True`` the optional *ssl_context* argument can be
- used to provide a ``backports.ssl.SSLContext`` instance used to
+ used to provide an ``ssl.SSLContext`` instance used to
control SSL/TLS connection parameters. If this is not provided a
sensible default context will be used.
@@ -122,7 +123,7 @@ class IMAPClient(object):
AbortError = imaplib.IMAP4.abort
ReadOnlyError = imaplib.IMAP4.readonly
- def __init__(self, host, port=None, use_uid=True, ssl=False, stream=False,
+ def __init__(self, host, port=None, use_uid=True, ssl=True, stream=False,
ssl_context=None, timeout=None):
if stream:
if port is not None:
@@ -132,6 +133,11 @@ class IMAPClient(object):
elif port is None:
port = ssl and 993 or 143
+ if ssl and port == 143:
+ logger.warning("Attempting to establish an encrypted connection "
+ "to a port (143) often used for unencrypted "
+ "connections")
+
self.host = host
self.port = port
self.ssl = ssl
@@ -146,7 +152,8 @@ class IMAPClient(object):
self._cached_capabilities = None
self._imap = self._create_IMAP4()
- logger.debug("Connected to host %s", self.host)
+ logger.debug("Connected to host %s over %s", self.host,
+ "SSL/TLS" if ssl else "plain text")
# Small hack to make imaplib log everything to its own logger
imaplib_logger = IMAPlibLoggerAdapter(
|
mjs/imapclient
|
f849e44f5cbcaf40433612875b5e84730b1fe358
|
diff --git a/tests/test_init.py b/tests/test_init.py
index 6dbb0b2..f99b238 100644
--- a/tests/test_init.py
+++ b/tests/test_init.py
@@ -25,7 +25,7 @@ class TestInit(unittest.TestCase):
fakeIMAP4 = Mock()
self.imap4.IMAP4WithTimeout.return_value = fakeIMAP4
- imap = IMAPClient('1.2.3.4', timeout=sentinel.timeout)
+ imap = IMAPClient('1.2.3.4', ssl=False, timeout=sentinel.timeout)
self.assertEqual(imap._imap, fakeIMAP4)
self.imap4.IMAP4WithTimeout.assert_called_with(
@@ -42,7 +42,7 @@ class TestInit(unittest.TestCase):
fakeIMAP4_TLS = Mock()
self.tls.IMAP4_TLS.return_value = fakeIMAP4_TLS
- imap = IMAPClient('1.2.3.4', ssl=True, ssl_context=sentinel.context,
+ imap = IMAPClient('1.2.3.4', ssl_context=sentinel.context,
timeout=sentinel.timeout)
self.assertEqual(imap._imap, fakeIMAP4_TLS)
@@ -58,7 +58,7 @@ class TestInit(unittest.TestCase):
def test_stream(self):
self.imaplib.IMAP4_stream.return_value = sentinel.IMAP4_stream
- imap = IMAPClient('command', stream=True)
+ imap = IMAPClient('command', stream=True, ssl=False)
self.assertEqual(imap._imap, sentinel.IMAP4_stream)
self.imaplib.IMAP4_stream.assert_called_with('command')
|
Make SSL connections the default
In 2017 there is little reasons to connect to a mailbox over plain text.
As this is a breaking change I propose to do it for 2.0.0.
|
0.0
|
f849e44f5cbcaf40433612875b5e84730b1fe358
|
[
"tests/test_init.py::TestInit::test_SSL"
] |
[
"tests/test_init.py::TestInit::test_plain",
"tests/test_init.py::TestInit::test_ssl_and_stream_is_error",
"tests/test_init.py::TestInit::test_stream",
"tests/test_init.py::TestInit::test_stream_and_port_is_error"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-08-22 11:35:54+00:00
|
bsd-3-clause
| 3,989 |
|
mjs__imapclient-279
|
diff --git a/doc/src/advanced.rst b/doc/src/advanced.rst
index a151e38..7356328 100644
--- a/doc/src/advanced.rst
+++ b/doc/src/advanced.rst
@@ -3,6 +3,33 @@ Advanced Usage
This document covers some more advanced features and tips for handling
specific usages.
+Cleaning Up Connections
+~~~~~~~~~~~~~~~~~~~~~~~
+
+To communicate with the server, IMAPClient establishes a TCP connection. It is
+important for long-lived processes to always close connections at some
+point to avoid leaking memory and file descriptors. This is usually done with
+the ``logout`` method::
+
+ import imapclient
+
+ c = imapclient.IMAPClient(host="imap.foo.org")
+ c.login("[email protected]", "passwd")
+ c.select_folder("INBOX")
+ c.logout()
+
+However if an error is raised when selecting the folder, the connection may be
+left open.
+
+IMAPClient may be used as a context manager that automatically closes
+connections when they are not needed anymore::
+
+ import imapclient
+
+ with imapclient.IMAPClient(host="imap.foo.org") as c:
+ c.login("[email protected]", "passwd")
+ c.select_folder("INBOX")
+
Watching a mailbox asynchronously using idle
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TODO
diff --git a/doc/src/index.rst b/doc/src/index.rst
index af62a24..3f08ce7 100644
--- a/doc/src/index.rst
+++ b/doc/src/index.rst
@@ -66,6 +66,8 @@ messages in the INBOX folder.
ID #44: "See that fun article about lobsters in Pacific ocean!" received 2017-06-09 09:49:47
ID #46: "Planning for our next vacations" received 2017-05-12 10:29:30
+ >>> server.logout()
+ b'Logging out'
User Guide
----------
diff --git a/doc/src/releases.rst b/doc/src/releases.rst
index 3e6c672..8199b24 100644
--- a/doc/src/releases.rst
+++ b/doc/src/releases.rst
@@ -10,6 +10,8 @@ Changed
- XXX Use built-in TLS when sensible.
- Logs are now handled by the Python logging module. `debug` and `log_file`
are not used anymore.
+- A context manager is introduced to automatically close connections to remote
+ servers.
Other
-----
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index 3792a1f..cff7b1b 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -117,6 +117,10 @@ class IMAPClient(object):
system time). This attribute can be changed between ``fetch()``
calls if required.
+ Can be used as a context manager to automatically close opened connections:
+ >>> with IMAPClient(host="imap.foo.org") as client:
+ ... client.login("[email protected]", "passwd")
+
"""
Error = imaplib.IMAP4.error
@@ -150,8 +154,11 @@ class IMAPClient(object):
self._timeout = timeout
self._starttls_done = False
self._cached_capabilities = None
+ self._idle_tag = None
self._imap = self._create_IMAP4()
+ self._set_timeout()
+
logger.debug("Connected to host %s over %s", self.host,
"SSL/TLS" if ssl else "plain text")
@@ -162,9 +169,22 @@ class IMAPClient(object):
self._imap.debug = 5
self._imap._mesg = imaplib_logger.debug
- self._idle_tag = None
+ def __enter__(self):
+ return self
- self._set_timeout()
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ """Logout and closes the connection when exiting the context manager.
+
+ All exceptions during logout and connection shutdown are caught because
+ an error here usually means the connection was already closed.
+ """
+ try:
+ self.logout()
+ except Exception:
+ try:
+ self.shutdown()
+ except Exception as e:
+ logger.info("Could not close the connection cleanly: %s", e)
def _create_IMAP4(self):
if self.stream:
|
mjs/imapclient
|
11700af6595fc3d92eadb54228fe3ddaa3c4b693
|
diff --git a/tests/test_imapclient.py b/tests/test_imapclient.py
index c03fce9..9597519 100644
--- a/tests/test_imapclient.py
+++ b/tests/test_imapclient.py
@@ -599,3 +599,32 @@ class TestShutdown(IMAPClientTest):
def test_shutdown(self):
self.client.shutdown()
self.client._imap.shutdown.assert_called_once_with()
+
+
+class TestContextManager(IMAPClientTest):
+
+ def test_context_manager(self):
+ with self.client as client:
+ self.assertIsInstance(client, IMAPClient)
+
+ self.client._imap.logout.assert_called_once_with()
+
+ @patch('imapclient.imapclient.logger')
+ def test_context_manager_fail_closing(self, mock_logger):
+ self.client._imap.logout.side_effect = RuntimeError("Error logout")
+ self.client._imap.shutdown.side_effect = RuntimeError("Error shutdown")
+
+ with self.client as client:
+ self.assertIsInstance(client, IMAPClient)
+
+ self.client._imap.logout.assert_called_once_with()
+ self.client._imap.shutdown.assert_called_once_with()
+ mock_logger.info.assert_called_once_with(
+ 'Could not close the connection cleanly: %s',
+ self.client._imap.shutdown.side_effect
+ )
+
+ def test_exception_inside_context_manager(self):
+ with self.assertRaises(ValueError):
+ with self.client as _:
+ raise ValueError("Error raised inside the context manager")
|
Introduce a context manager for IMAPClient instances
A context manager would prevent accidentally leaking sockets when the user forgets to call `logout()`.
|
0.0
|
11700af6595fc3d92eadb54228fe3ddaa3c4b693
|
[
"tests/test_imapclient.py::TestContextManager::test_context_manager",
"tests/test_imapclient.py::TestContextManager::test_context_manager_fail_closing",
"tests/test_imapclient.py::TestContextManager::test_exception_inside_context_manager"
] |
[
"tests/test_imapclient.py::TestListFolders::test_blanks",
"tests/test_imapclient.py::TestListFolders::test_empty_response",
"tests/test_imapclient.py::TestListFolders::test_folder_encode_off",
"tests/test_imapclient.py::TestListFolders::test_funky_characters",
"tests/test_imapclient.py::TestListFolders::test_list_folders",
"tests/test_imapclient.py::TestListFolders::test_list_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_mixed",
"tests/test_imapclient.py::TestListFolders::test_quoted_specials",
"tests/test_imapclient.py::TestListFolders::test_simple",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name_parsed_as_long",
"tests/test_imapclient.py::TestListFolders::test_utf7_decoding",
"tests/test_imapclient.py::TestListFolders::test_without_quotes",
"tests/test_imapclient.py::TestSelectFolder::test_normal",
"tests/test_imapclient.py::TestSelectFolder::test_unselect",
"tests/test_imapclient.py::TestAppend::test_with_msg_time",
"tests/test_imapclient.py::TestAppend::test_without_msg_time",
"tests/test_imapclient.py::TestAclMethods::test_getacl",
"tests/test_imapclient.py::TestAclMethods::test_setacl",
"tests/test_imapclient.py::TestIdleAndNoop::test_consume_until_tagged_response",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_blocking",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_timeout",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_with_data",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_done",
"tests/test_imapclient.py::TestIdleAndNoop::test_noop",
"tests/test_imapclient.py::TestTimeNormalisation::test_default",
"tests/test_imapclient.py::TestTimeNormalisation::test_pass_through",
"tests/test_imapclient.py::TestNamespace::test_complex",
"tests/test_imapclient.py::TestNamespace::test_folder_decoding",
"tests/test_imapclient.py::TestNamespace::test_other_only",
"tests/test_imapclient.py::TestNamespace::test_simple",
"tests/test_imapclient.py::TestNamespace::test_without_folder_decoding",
"tests/test_imapclient.py::TestCapabilities::test_caching",
"tests/test_imapclient.py::TestCapabilities::test_has_capability",
"tests/test_imapclient.py::TestCapabilities::test_post_auth_request",
"tests/test_imapclient.py::TestCapabilities::test_preauth",
"tests/test_imapclient.py::TestCapabilities::test_server_returned_capability_after_auth",
"tests/test_imapclient.py::TestCapabilities::test_with_starttls",
"tests/test_imapclient.py::TestId::test_id",
"tests/test_imapclient.py::TestId::test_invalid_parameters",
"tests/test_imapclient.py::TestId::test_no_support",
"tests/test_imapclient.py::TestRawCommand::test_complex",
"tests/test_imapclient.py::TestRawCommand::test_embedded_literal",
"tests/test_imapclient.py::TestRawCommand::test_failed_continuation_wait",
"tests/test_imapclient.py::TestRawCommand::test_invalid_input_type",
"tests/test_imapclient.py::TestRawCommand::test_literal_at_end",
"tests/test_imapclient.py::TestRawCommand::test_multiple_literals",
"tests/test_imapclient.py::TestRawCommand::test_not_uid",
"tests/test_imapclient.py::TestRawCommand::test_plain",
"tests/test_imapclient.py::TestShutdown::test_shutdown"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-08-23 13:20:00+00:00
|
bsd-3-clause
| 3,990 |
|
mjs__imapclient-291
|
diff --git a/doc/src/releases.rst b/doc/src/releases.rst
index e2a07dd..95d087c 100644
--- a/doc/src/releases.rst
+++ b/doc/src/releases.rst
@@ -21,6 +21,8 @@ Changed
are not used anymore.
- More precise exceptions available in `imapclient.exceptions` are raised when
an error happens
+- `imapclient.exceptions.ProtocolError` is now raised when the reply from a
+ remote server violates the IMAP protocol.
- GMail labels are now strings instead of bytes in Python 3.
Fixed
diff --git a/imapclient/exceptions.py b/imapclient/exceptions.py
index 1130da1..26fd51c 100644
--- a/imapclient/exceptions.py
+++ b/imapclient/exceptions.py
@@ -36,3 +36,7 @@ class InvalidCriteriaError(IMAPClientError):
A command using a search criteria failed, probably due to a syntax
error in the criteria string.
"""
+
+
+class ProtocolError(IMAPClientError):
+ """The server replied with a response that violates the IMAP protocol."""
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index 58fae81..fea196b 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -24,7 +24,7 @@ from . import tls
from .datetime_util import datetime_to_INTERNALDATE, format_criteria_date
from .imap_utf7 import encode as encode_utf7, decode as decode_utf7
from .response_parser import parse_response, parse_message_list, parse_fetch_response
-from .util import to_bytes, to_unicode
+from .util import to_bytes, to_unicode, assert_imap_protocol
xrange = moves.xrange
if PY3:
@@ -1526,7 +1526,7 @@ def _maybe_int_to_bytes(val):
def _parse_untagged_response(text):
- assert text.startswith(b'* ')
+ assert_imap_protocol(text.startswith(b'* '))
text = text[2:]
if text.startswith((b'OK ', b'NO ')):
return tuple(text.split(b' ', 1))
diff --git a/imapclient/response_lexer.py b/imapclient/response_lexer.py
index 88e09fb..2504c65 100644
--- a/imapclient/response_lexer.py
+++ b/imapclient/response_lexer.py
@@ -13,6 +13,8 @@ from __future__ import unicode_literals
import six
+from .util import assert_imap_protocol
+
__all__ = ["TokenSource"]
CTRL_CHARS = frozenset(c for c in range(32))
@@ -97,7 +99,7 @@ class Lexer(object):
if nextchar in whitespace:
yield token
elif nextchar == DOUBLE_QUOTE:
- assert not token
+ assert_imap_protocol(not token)
token.append(nextchar)
token.extend(read_until(stream_i, nextchar))
yield token
@@ -138,7 +140,7 @@ class LiteralHandlingIter:
# A 'record' with a string which includes a literal marker, and
# the literal itself.
self.src_text = resp_record[0]
- assert self.src_text.endswith(b"}"), self.src_text
+ assert_imap_protocol(self.src_text.endswith(b"}"), self.src_text)
self.literal = resp_record[1]
else:
# just a line with no literals.
diff --git a/imapclient/response_parser.py b/imapclient/response_parser.py
index 1b65ad4..4331be6 100644
--- a/imapclient/response_parser.py
+++ b/imapclient/response_parser.py
@@ -22,14 +22,11 @@ import six
from .datetime_util import parse_to_datetime
from .response_lexer import TokenSource
from .response_types import BodyData, Envelope, Address, SearchIds
+from .exceptions import ProtocolError
xrange = six.moves.xrange
-__all__ = ['parse_response', 'parse_message_list', 'ParseError']
-
-
-class ParseError(ValueError):
- pass
+__all__ = ['parse_response', 'parse_message_list']
def parse_response(data):
@@ -93,11 +90,11 @@ def gen_parsed_response(text):
try:
for token in src:
yield atom(src, token)
- except ParseError:
+ except ProtocolError:
raise
except ValueError:
_, err, _ = sys.exc_info()
- raise ParseError("%s: %s" % (str(err), token))
+ raise ProtocolError("%s: %s" % (str(err), token))
def parse_fetch_response(text, normalise_times=True, uid_is_key=True):
@@ -121,12 +118,12 @@ def parse_fetch_response(text, normalise_times=True, uid_is_key=True):
try:
msg_response = six.next(response)
except StopIteration:
- raise ParseError('unexpected EOF')
+ raise ProtocolError('unexpected EOF')
if not isinstance(msg_response, tuple):
- raise ParseError('bad response type: %s' % repr(msg_response))
+ raise ProtocolError('bad response type: %s' % repr(msg_response))
if len(msg_response) % 2:
- raise ParseError('uneven number of response items: %s' % repr(msg_response))
+ raise ProtocolError('uneven number of response items: %s' % repr(msg_response))
# always return the sequence of the message, so it is available
# even if we return keyed by UID.
@@ -159,7 +156,7 @@ def _int_or_error(value, error_text):
try:
return int(value)
except (TypeError, ValueError):
- raise ParseError('%s: %s' % (error_text, repr(value)))
+ raise ProtocolError('%s: %s' % (error_text, repr(value)))
def _convert_INTERNALDATE(date_string, normalise_times=True):
@@ -212,9 +209,9 @@ def atom(src, token):
literal_len = int(token[1:-1])
literal_text = src.current_literal
if literal_text is None:
- raise ParseError('No literal corresponds to %r' % token)
+ raise ProtocolError('No literal corresponds to %r' % token)
if len(literal_text) != literal_len:
- raise ParseError('Expecting literal of size %d, got %d' % (
+ raise ProtocolError('Expecting literal of size %d, got %d' % (
literal_len, len(literal_text)))
return literal_text
elif len(token) >= 2 and (token[:1] == token[-1:] == b'"'):
@@ -232,7 +229,7 @@ def parse_tuple(src):
return tuple(out)
out.append(atom(src, token))
# no terminator
- raise ParseError('Tuple incomplete before "(%s"' % _fmt_tuple(out))
+ raise ProtocolError('Tuple incomplete before "(%s"' % _fmt_tuple(out))
def _fmt_tuple(t):
diff --git a/imapclient/util.py b/imapclient/util.py
index 3314ea5..aa89115 100644
--- a/imapclient/util.py
+++ b/imapclient/util.py
@@ -7,6 +7,8 @@ from __future__ import unicode_literals
import logging
from six import binary_type, text_type
+from . import exceptions
+
logger = logging.getLogger(__name__)
@@ -27,3 +29,11 @@ def to_bytes(s, charset='ascii'):
if isinstance(s, text_type):
return s.encode(charset)
return s
+
+
+def assert_imap_protocol(condition, message=None):
+ if not condition:
+ msg = "Server replied with a response that violates the IMAP protocol"
+ if message:
+ msg += "{}: {}".format(msg, message)
+ raise exceptions.ProtocolError(msg)
|
mjs/imapclient
|
f02732d6a55f3f3b55ea20a5451693d7869cd419
|
diff --git a/tests/test_imapclient.py b/tests/test_imapclient.py
index f8f458f..f56ca5b 100644
--- a/tests/test_imapclient.py
+++ b/tests/test_imapclient.py
@@ -12,7 +12,9 @@ import logging
import six
-from imapclient.exceptions import CapabilityError, IMAPClientError
+from imapclient.exceptions import (
+ CapabilityError, IMAPClientError, ProtocolError
+)
from imapclient.imapclient import IMAPlibLoggerAdapter
from imapclient.fixed_offset import FixedOffset
from imapclient.testable_imapclient import TestableIMAPClient as IMAPClient
@@ -651,3 +653,14 @@ class TestContextManager(IMAPClientTest):
with self.assertRaises(ValueError):
with self.client as _:
raise ValueError("Error raised inside the context manager")
+
+
+class TestProtocolError(IMAPClientTest):
+
+ def test_tagged_response_with_parse_error(self):
+ client = self.client
+ client._imap.tagged_commands = {sentinel.tag: None}
+ client._imap._get_response = lambda: b'NOT-A-STAR 99 EXISTS'
+
+ with self.assertRaises(ProtocolError):
+ client._consume_until_tagged_response(sentinel.tag, b'IDLE')
\ No newline at end of file
diff --git a/tests/test_response_parser.py b/tests/test_response_parser.py
index 946cd16..04694fc 100644
--- a/tests/test_response_parser.py
+++ b/tests/test_response_parser.py
@@ -16,9 +16,9 @@ from imapclient.response_parser import (
parse_response,
parse_message_list,
parse_fetch_response,
- ParseError,
)
from imapclient.response_types import Envelope, Address
+from imapclient.exceptions import ProtocolError
from tests.util import unittest
from .util import patch
@@ -160,7 +160,7 @@ class TestParseResponse(unittest.TestCase):
def _test_parse_error(self, to_parse, expected_msg):
if not isinstance(to_parse, list):
to_parse = [to_parse]
- self.assertRaisesRegex(ParseError, expected_msg,
+ self.assertRaisesRegex(ProtocolError, expected_msg,
parse_response, to_parse)
@@ -200,13 +200,13 @@ class TestParseFetchResponse(unittest.TestCase):
self.assertEqual(parse_fetch_response([None]), {})
def test_bad_msgid(self):
- self.assertRaises(ParseError, parse_fetch_response, [b'abc ()'])
+ self.assertRaises(ProtocolError, parse_fetch_response, [b'abc ()'])
def test_bad_data(self):
- self.assertRaises(ParseError, parse_fetch_response, [b'2 WHAT'])
+ self.assertRaises(ProtocolError, parse_fetch_response, [b'2 WHAT'])
def test_missing_data(self):
- self.assertRaises(ParseError, parse_fetch_response, [b'2'])
+ self.assertRaises(ProtocolError, parse_fetch_response, [b'2'])
def test_simple_pairs(self):
self.assertEqual(parse_fetch_response([b'23 (ABC 123 StUfF "hello")']),
@@ -215,8 +215,8 @@ class TestParseFetchResponse(unittest.TestCase):
b'SEQ': 23}})
def test_odd_pairs(self):
- self.assertRaises(ParseError, parse_fetch_response, [b'(ONE)'])
- self.assertRaises(ParseError, parse_fetch_response, [b'(ONE TWO THREE)'])
+ self.assertRaises(ProtocolError, parse_fetch_response, [b'(ONE)'])
+ self.assertRaises(ProtocolError, parse_fetch_response, [b'(ONE TWO THREE)'])
def test_UID(self):
self.assertEqual(parse_fetch_response([b'23 (UID 76)']),
@@ -230,7 +230,7 @@ class TestParseFetchResponse(unittest.TestCase):
b'SEQ': 23}})
def test_bad_UID(self):
- self.assertRaises(ParseError, parse_fetch_response, [b'(UID X)'])
+ self.assertRaises(ProtocolError, parse_fetch_response, [b'(UID X)'])
def test_FLAGS(self):
self.assertEqual(parse_fetch_response([b'23 (FLAGS (\Seen Stuff))']),
diff --git a/tests/test_util_functions.py b/tests/test_util_functions.py
index b3becb8..ba3f271 100644
--- a/tests/test_util_functions.py
+++ b/tests/test_util_functions.py
@@ -4,15 +4,17 @@
from __future__ import unicode_literals
-from imapclient.exceptions import InvalidCriteriaError
+from imapclient.exceptions import InvalidCriteriaError, ProtocolError
from imapclient.imapclient import (
join_message_ids,
_normalise_search_criteria,
normalise_text_list,
seq_to_parenstr,
seq_to_parenstr_upper,
- _quoted
+ _quoted,
+ _parse_untagged_response
)
+from imapclient.util import assert_imap_protocol
from tests.util import unittest
@@ -166,3 +168,17 @@ class Test_normalise_search_criteria(unittest.TestCase):
def test_empty(self):
self.assertRaises(InvalidCriteriaError, _normalise_search_criteria, '', None)
+
+
+class TestAssertIMAPProtocol(unittest.TestCase):
+
+ def test_assert_imap_protocol(self):
+ assert_imap_protocol(True)
+ with self.assertRaises(ProtocolError):
+ assert_imap_protocol(False)
+
+
+ def test_assert_imap_protocol_with_message(self):
+ assert_imap_protocol(True, 'foo')
+ with self.assertRaises(ProtocolError):
+ assert_imap_protocol(False, 'foo')
|
Avoid using assert when parsing server response
Some servers are not totally compliant with the IMAP protocol or sometimes give buggy output like: `"TEXT" "PLAIN" ("charset " " "utf-8"")`.
I believe IMAPClient should not `assert` when parsing the response from a server. Assert makes it hard to recover from such errors. A custom IMAPClient exception would be more helpful to the user.
|
0.0
|
f02732d6a55f3f3b55ea20a5451693d7869cd419
|
[
"tests/test_imapclient.py::TestListFolders::test_blanks",
"tests/test_imapclient.py::TestListFolders::test_empty_response",
"tests/test_imapclient.py::TestListFolders::test_folder_encode_off",
"tests/test_imapclient.py::TestListFolders::test_funky_characters",
"tests/test_imapclient.py::TestListFolders::test_list_folders",
"tests/test_imapclient.py::TestListFolders::test_list_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_mixed",
"tests/test_imapclient.py::TestListFolders::test_quoted_specials",
"tests/test_imapclient.py::TestListFolders::test_simple",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name_parsed_as_long",
"tests/test_imapclient.py::TestListFolders::test_utf7_decoding",
"tests/test_imapclient.py::TestListFolders::test_without_quotes",
"tests/test_imapclient.py::TestSelectFolder::test_normal",
"tests/test_imapclient.py::TestSelectFolder::test_unselect",
"tests/test_imapclient.py::TestAppend::test_with_msg_time",
"tests/test_imapclient.py::TestAppend::test_without_msg_time",
"tests/test_imapclient.py::TestAclMethods::test_getacl",
"tests/test_imapclient.py::TestAclMethods::test_setacl",
"tests/test_imapclient.py::TestIdleAndNoop::test_consume_until_tagged_response",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_blocking",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_timeout",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_with_data",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_done",
"tests/test_imapclient.py::TestIdleAndNoop::test_noop",
"tests/test_imapclient.py::TestDebugLogging::test_IMAP_is_patched",
"tests/test_imapclient.py::TestTimeNormalisation::test_default",
"tests/test_imapclient.py::TestTimeNormalisation::test_pass_through",
"tests/test_imapclient.py::TestNamespace::test_complex",
"tests/test_imapclient.py::TestNamespace::test_folder_decoding",
"tests/test_imapclient.py::TestNamespace::test_other_only",
"tests/test_imapclient.py::TestNamespace::test_simple",
"tests/test_imapclient.py::TestNamespace::test_without_folder_decoding",
"tests/test_imapclient.py::TestCapabilities::test_caching",
"tests/test_imapclient.py::TestCapabilities::test_has_capability",
"tests/test_imapclient.py::TestCapabilities::test_post_auth_request",
"tests/test_imapclient.py::TestCapabilities::test_preauth",
"tests/test_imapclient.py::TestCapabilities::test_server_returned_capability_after_auth",
"tests/test_imapclient.py::TestCapabilities::test_with_starttls",
"tests/test_imapclient.py::TestId::test_id",
"tests/test_imapclient.py::TestId::test_invalid_parameters",
"tests/test_imapclient.py::TestId::test_no_support",
"tests/test_imapclient.py::TestRawCommand::test_complex",
"tests/test_imapclient.py::TestRawCommand::test_embedded_literal",
"tests/test_imapclient.py::TestRawCommand::test_failed_continuation_wait",
"tests/test_imapclient.py::TestRawCommand::test_invalid_input_type",
"tests/test_imapclient.py::TestRawCommand::test_literal_at_end",
"tests/test_imapclient.py::TestRawCommand::test_multiple_literals",
"tests/test_imapclient.py::TestRawCommand::test_not_uid",
"tests/test_imapclient.py::TestRawCommand::test_plain",
"tests/test_imapclient.py::TestExpunge::test_expunge",
"tests/test_imapclient.py::TestExpunge::test_id_expunge",
"tests/test_imapclient.py::TestShutdown::test_shutdown",
"tests/test_imapclient.py::TestContextManager::test_context_manager",
"tests/test_imapclient.py::TestContextManager::test_context_manager_fail_closing",
"tests/test_imapclient.py::TestContextManager::test_exception_inside_context_manager",
"tests/test_imapclient.py::TestProtocolError::test_tagged_response_with_parse_error",
"tests/test_response_parser.py::TestParseResponse::test_bad_literal",
"tests/test_response_parser.py::TestParseResponse::test_bad_quoting",
"tests/test_response_parser.py::TestParseResponse::test_complex_mixed",
"tests/test_response_parser.py::TestParseResponse::test_deeper_nest_tuple",
"tests/test_response_parser.py::TestParseResponse::test_empty_tuple",
"tests/test_response_parser.py::TestParseResponse::test_envelopey",
"tests/test_response_parser.py::TestParseResponse::test_envelopey_quoted",
"tests/test_response_parser.py::TestParseResponse::test_incomplete_tuple",
"tests/test_response_parser.py::TestParseResponse::test_int",
"tests/test_response_parser.py::TestParseResponse::test_int_and_tuple",
"tests/test_response_parser.py::TestParseResponse::test_literal",
"tests/test_response_parser.py::TestParseResponse::test_literal_with_more",
"tests/test_response_parser.py::TestParseResponse::test_nested_tuple",
"tests/test_response_parser.py::TestParseResponse::test_nil",
"tests/test_response_parser.py::TestParseResponse::test_quoted_specials",
"tests/test_response_parser.py::TestParseResponse::test_square_brackets",
"tests/test_response_parser.py::TestParseResponse::test_string",
"tests/test_response_parser.py::TestParseResponse::test_tuple",
"tests/test_response_parser.py::TestParseResponse::test_unquoted",
"tests/test_response_parser.py::TestParseMessageList::test_basic",
"tests/test_response_parser.py::TestParseMessageList::test_modseq",
"tests/test_response_parser.py::TestParseMessageList::test_modseq_interleaved",
"tests/test_response_parser.py::TestParseMessageList::test_modseq_no_space",
"tests/test_response_parser.py::TestParseMessageList::test_one_id",
"tests/test_response_parser.py::TestParseFetchResponse::test_Address_str",
"tests/test_response_parser.py::TestParseFetchResponse::test_Address_str_ignores_encoding_error",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODY",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODYSTRUCTURE",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODY_HEADER_FIELDS",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_empty_addresses",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_invalid_date",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_no_date",
"tests/test_response_parser.py::TestParseFetchResponse::test_FLAGS",
"tests/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE",
"tests/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE_normalised",
"tests/test_response_parser.py::TestParseFetchResponse::test_UID",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_UID",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_data",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_msgid",
"tests/test_response_parser.py::TestParseFetchResponse::test_basic",
"tests/test_response_parser.py::TestParseFetchResponse::test_literals",
"tests/test_response_parser.py::TestParseFetchResponse::test_literals_and_keys_with_square_brackets",
"tests/test_response_parser.py::TestParseFetchResponse::test_missing_data",
"tests/test_response_parser.py::TestParseFetchResponse::test_mixed_types",
"tests/test_response_parser.py::TestParseFetchResponse::test_multiple_messages",
"tests/test_response_parser.py::TestParseFetchResponse::test_none_special_case",
"tests/test_response_parser.py::TestParseFetchResponse::test_not_uid_is_key",
"tests/test_response_parser.py::TestParseFetchResponse::test_odd_pairs",
"tests/test_response_parser.py::TestParseFetchResponse::test_partial_fetch",
"tests/test_response_parser.py::TestParseFetchResponse::test_same_message_appearing_multiple_times",
"tests/test_response_parser.py::TestParseFetchResponse::test_simple_pairs",
"tests/test_util_functions.py::Test_normalise_text_list::test_binary",
"tests/test_util_functions.py::Test_normalise_text_list::test_iter",
"tests/test_util_functions.py::Test_normalise_text_list::test_list",
"tests/test_util_functions.py::Test_normalise_text_list::test_mixed_list",
"tests/test_util_functions.py::Test_normalise_text_list::test_tuple",
"tests/test_util_functions.py::Test_normalise_text_list::test_unicode",
"tests/test_util_functions.py::Test_seq_to_parenstr::test_binary",
"tests/test_util_functions.py::Test_seq_to_parenstr::test_iter",
"tests/test_util_functions.py::Test_seq_to_parenstr::test_list",
"tests/test_util_functions.py::Test_seq_to_parenstr::test_mixed_list",
"tests/test_util_functions.py::Test_seq_to_parenstr::test_tuple",
"tests/test_util_functions.py::Test_seq_to_parenstr::test_unicode",
"tests/test_util_functions.py::Test_seq_to_parenstr_upper::test_binary",
"tests/test_util_functions.py::Test_seq_to_parenstr_upper::test_iter",
"tests/test_util_functions.py::Test_seq_to_parenstr_upper::test_list",
"tests/test_util_functions.py::Test_seq_to_parenstr_upper::test_mixed_list",
"tests/test_util_functions.py::Test_seq_to_parenstr_upper::test_tuple",
"tests/test_util_functions.py::Test_seq_to_parenstr_upper::test_unicode",
"tests/test_util_functions.py::Test_join_message_ids::test_binary",
"tests/test_util_functions.py::Test_join_message_ids::test_binary_non_numeric",
"tests/test_util_functions.py::Test_join_message_ids::test_int",
"tests/test_util_functions.py::Test_join_message_ids::test_iter",
"tests/test_util_functions.py::Test_join_message_ids::test_mixed_list",
"tests/test_util_functions.py::Test_join_message_ids::test_tuple",
"tests/test_util_functions.py::Test_join_message_ids::test_unicode",
"tests/test_util_functions.py::Test_join_message_ids::test_unicode_non_numeric",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_None",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_binary",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_binary_with_charset",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_empty",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_ints",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_list",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_mixed_list",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_no_quoting_when_criteria_given_as_string",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_quoting",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_tuple",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_unicode",
"tests/test_util_functions.py::Test_normalise_search_criteria::test_unicode_with_charset",
"tests/test_util_functions.py::TestAssertIMAPProtocol::test_assert_imap_protocol",
"tests/test_util_functions.py::TestAssertIMAPProtocol::test_assert_imap_protocol_with_message"
] |
[] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-09-26 11:50:15+00:00
|
bsd-3-clause
| 3,991 |
|
mjs__imapclient-300
|
diff --git a/doc/src/releases.rst b/doc/src/releases.rst
index 29e3ef7..2bc6734 100644
--- a/doc/src/releases.rst
+++ b/doc/src/releases.rst
@@ -6,7 +6,7 @@
Added
-----
-- Connection and read/write operations timeout can now be distinct,
+- Connection and read/write operations timeout can now be distinct,
using `imapclient.SocketTimeout` namedtuple as `timeout` parameter.
- A context manager is introduced to automatically close connections to remote
servers.
@@ -20,6 +20,12 @@ Changed
- More precise exceptions available in `imapclient.exceptions` are raised when
an error happens
+Fixed
+-----
+- Modified UTF-7 encoding function had quirks in its original algorithm,
+ leading to incorrect encoded output in some cases. The algorithm, described
+ in RFC 3501, has been reimplemented to fix #187 and is better documented.
+
Other
-----
- Drop support of OAUTH(1)
diff --git a/imapclient/imap_utf7.py b/imapclient/imap_utf7.py
index c689055..eeb5668 100644
--- a/imapclient/imap_utf7.py
+++ b/imapclient/imap_utf7.py
@@ -1,37 +1,17 @@
-# The contents of this file has been derived code from the Twisted project
-# (http://twistedmatrix.com/). The original author is Jp Calderone.
-
-# Twisted project license follows:
-
-# Permission is hereby granted, free of charge, to any person obtaining
-# a copy of this software and associated documentation files (the
-# "Software"), to deal in the Software without restriction, including
-# without limitation the rights to use, copy, modify, merge, publish,
-# distribute, sublicense, and/or sell copies of the Software, and to
-# permit persons to whom the Software is furnished to do so, subject to
-# the following conditions:
+# This file contains two main methods used to encode and decode UTF-7
+# string, described in the RFC 3501. There are some variations specific
+# to IMAP4rev1, so the built-in Python UTF-7 codec can't be used instead.
#
-# The above copyright notice and this permission notice shall be
-# included in all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
+# The main difference is the shift character (used to switch from ASCII to
+# base64 encoding context), which is & in this modified UTF-7 convention,
+# since + is considered as mainly used in mailbox names.
+# Other variations and examples can be found in the RFC 3501, section 5.1.3.
from __future__ import unicode_literals
+import binascii
from six import binary_type, text_type, byte2int, iterbytes, unichr
-PRINTABLE = set(range(0x20, 0x26)) | set(range(0x27, 0x7f))
-
-# TODO: module needs refactoring (e.g. variable names suck)
-
-
def encode(s):
"""Encode a folder name using IMAP modified UTF-7 encoding.
@@ -41,27 +21,36 @@ def encode(s):
if not isinstance(s, text_type):
return s
- r = []
- _in = []
-
- def extend_result_if_chars_buffered():
- if _in:
- r.extend([b'&', modified_utf7(''.join(_in)), b'-'])
- del _in[:]
+ res = []
+ b64_buffer = []
+ def consume_b64_buffer(buf):
+ """
+ Consume the buffer by encoding it into a modified base 64 representation
+ and surround it with shift characters & and -
+ """
+ if b64_buffer:
+ res.extend([b'&', base64_utf7_encode(buf), b'-'])
+ del buf[:]
for c in s:
- if ord(c) in PRINTABLE:
- extend_result_if_chars_buffered()
- r.append(c.encode('latin-1'))
- elif c == '&':
- extend_result_if_chars_buffered()
- r.append(b'&-')
+ # printable ascii case should not be modified
+ if 0x20 <= ord(c) <= 0x7e:
+ consume_b64_buffer(b64_buffer)
+ # Special case: & is used as shift character so we need to escape it in ASCII
+ if c == '&':
+ res.append(b'&-')
+ else:
+ res.append(c.encode('ascii'))
+
+ # Bufferize characters that will be encoded in base64 and append them later
+ # in the result, when iterating over ASCII character or the end of string
else:
- _in.append(c)
+ b64_buffer.append(c)
- extend_result_if_chars_buffered()
+ # Consume the remaining buffer if the string finish with non-ASCII characters
+ consume_b64_buffer(b64_buffer)
- return b''.join(r)
+ return b''.join(res)
AMPERSAND_ORD = byte2int(b'&')
@@ -75,35 +64,43 @@ def decode(s):
unicode. If non-bytes/str input is provided, the input is returned
unchanged.
"""
-
if not isinstance(s, binary_type):
return s
- r = []
- _in = bytearray()
+ res = []
+ # Store base64 substring that will be decoded once stepping on end shift character
+ b64_buffer = bytearray()
for c in iterbytes(s):
- if c == AMPERSAND_ORD and not _in:
- _in.append(c)
- elif c == DASH_ORD and _in:
- if len(_in) == 1:
- r.append('&')
+ # Shift character without anything in buffer -> starts storing base64 substring
+ if c == AMPERSAND_ORD and not b64_buffer:
+ b64_buffer.append(c)
+ # End shift char. -> append the decoded buffer to the result and reset it
+ elif c == DASH_ORD and b64_buffer:
+ # Special case &-, representing "&" escaped
+ if len(b64_buffer) == 1:
+ res.append('&')
else:
- r.append(modified_deutf7(_in[1:]))
- _in = bytearray()
- elif _in:
- _in.append(c)
+ res.append(base64_utf7_decode(b64_buffer[1:]))
+ b64_buffer = bytearray()
+ # Still buffering between the shift character and the shift back to ASCII
+ elif b64_buffer:
+ b64_buffer.append(c)
+ # No buffer initialized yet, should be an ASCII printable char
else:
- r.append(unichr(c))
- if _in:
- r.append(modified_deutf7(_in[1:]))
- return ''.join(r)
+ res.append(unichr(c))
+
+ # Decode the remaining buffer if any
+ if b64_buffer:
+ res.append(base64_utf7_decode(b64_buffer[1:]))
+
+ return ''.join(res)
-def modified_utf7(s):
- s_utf7 = s.encode('utf-7')
- return s_utf7[1:-1].replace(b'/', b',')
+def base64_utf7_encode(buffer):
+ s = ''.join(buffer).encode('utf-16be')
+ return binascii.b2a_base64(s).rstrip(b'\n=').replace(b'/', b',')
-def modified_deutf7(s):
+def base64_utf7_decode(s):
s_utf7 = b'+' + s.replace(b',', b'/') + b'-'
return s_utf7.decode('utf-7')
|
mjs/imapclient
|
42e118739e0ccca49c372bab35574acc9ec7e502
|
diff --git a/tests/test_imap_utf7.py b/tests/test_imap_utf7.py
index 9fe64f1..29e7d0e 100644
--- a/tests/test_imap_utf7.py
+++ b/tests/test_imap_utf7.py
@@ -22,6 +22,7 @@ class IMAP4UTF7TestCase(unittest.TestCase):
['~peter/mail/\u65e5\u672c\u8a9e/\u53f0\u5317',
b'~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060
['\x00foo', b'&AAA-foo'],
+ ['foo\r\n\nbar\n', b'foo&AA0ACgAK-bar&AAo-'] # see imapclient/#187 issue
]
def test_encode(self):
|
Investigate claims that UTF-7 encoding/decoding doesn't always work
Originally reported by: **Menno Smits (Bitbucket: [mjs0](https://bitbucket.org/mjs0))**
---
See: https://github.com/MarechJ/py3_imap_utf7
If/when any problems are fixed, ask the author to update the page. Also add comments to SO where this is mentioned.
---
- Bitbucket: https://bitbucket.org/mjs0/imapclient/issue/190
|
0.0
|
42e118739e0ccca49c372bab35574acc9ec7e502
|
[
"tests/test_imap_utf7.py::IMAP4UTF7TestCase::test_encode"
] |
[
"tests/test_imap_utf7.py::IMAP4UTF7TestCase::test_decode",
"tests/test_imap_utf7.py::IMAP4UTF7TestCase::test_printable_singletons"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-10-09 21:32:17+00:00
|
bsd-3-clause
| 3,992 |
|
mjs__imapclient-307
|
diff --git a/imapclient/util.py b/imapclient/util.py
index 923961c..3314ea5 100644
--- a/imapclient/util.py
+++ b/imapclient/util.py
@@ -4,12 +4,22 @@
from __future__ import unicode_literals
+import logging
from six import binary_type, text_type
+logger = logging.getLogger(__name__)
+
def to_unicode(s):
if isinstance(s, binary_type):
- return s.decode('ascii')
+ try:
+ return s.decode('ascii')
+ except UnicodeDecodeError:
+ logger.warning(
+ "An error occurred while decoding %s in ASCII 'strict' mode. Fallback to "
+ "'ignore' errors handling, some characters might have been stripped", s
+ )
+ return s.decode('ascii', 'ignore')
return s
|
mjs/imapclient
|
f05d2e50197bf9f76c051399102d1125789b03b2
|
diff --git a/tests/test_response_parser.py b/tests/test_response_parser.py
index 82af1d3..01f2222 100644
--- a/tests/test_response_parser.py
+++ b/tests/test_response_parser.py
@@ -9,6 +9,7 @@ Unit tests for the FetchTokeniser and FetchParser classes
from __future__ import unicode_literals
from datetime import datetime
+from mock import patch
from imapclient.datetime_util import datetime_to_native
from imapclient.fixed_offset import FixedOffset
@@ -497,6 +498,14 @@ class TestParseFetchResponse(unittest.TestCase):
self.assertEqual(str(Address(None, None, None, "undisclosed-recipients")),
"undisclosed-recipients")
+ @patch('imapclient.util.logger')
+ def test_Address_str_ignores_encoding_error(self, mock_logger):
+ self.assertEqual(
+ str(Address(b'Russian \xc2\xeb\xe0\xe4\xe8\xec\xe8\xf0', None, b"g\xe9rard", "domain.org")),
+ "Russian <[email protected]>"
+ )
+ # Ensure warning has been triggered twice, for name and mailbox bytes
+ self.assertEqual(mock_logger.warning.call_count, 2)
def add_crlf(text):
|
`_convert_to_ENVELOPE` (and subcall to `util.to_unicode`) only support ascii data
When using `fetch(uids, ['ENVELOPE'])`, we get a `imapclient.response_types.Envelope` namedtuple. However, this object may result in subcomponent that call `imapclient.util.to_unicode`. However this methods, decode bytes data only with the ascii codec.
For some reasons, some senders does not encode the data before sending the e-mail, resulting in object like this...
```In [5]: addr = Address(b'Ren\xe9', None, 'rene', 'domain.com')
In [6]: str(addr)
---------------------------------------------------------------------------
/dir/to/imapclient/response_types.py in __str__(self)
56 def __str__(self):
57 return formataddr((
---> 58 to_unicode(self.name),
59 to_unicode(self.mailbox) + '@' + to_unicode(self.host)))
60
/dir/to/imapclient/util.py in to_unicode(s)
10 def to_unicode(s):
11 if isinstance(s, binary_type):
---> 12 return s.decode('ascii')
13 return s
14
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 3: ordinal not in range(128)
```
I think `imapclient` should handle this and either raise a proper custom exception which informs the developer why the data is incorrect or decode the data (using latin1 codec in this case), if possible...
|
0.0
|
f05d2e50197bf9f76c051399102d1125789b03b2
|
[
"tests/test_response_parser.py::TestParseFetchResponse::test_Address_str_ignores_encoding_error"
] |
[
"tests/test_response_parser.py::TestParseFetchResponse::test_mixed_types",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_invalid_date",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_UID",
"tests/test_response_parser.py::TestParseFetchResponse::test_not_uid_is_key",
"tests/test_response_parser.py::TestParseFetchResponse::test_literals_and_keys_with_square_brackets",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_no_date",
"tests/test_response_parser.py::TestParseFetchResponse::test_basic",
"tests/test_response_parser.py::TestParseFetchResponse::test_multiple_messages",
"tests/test_response_parser.py::TestParseFetchResponse::test_odd_pairs",
"tests/test_response_parser.py::TestParseFetchResponse::test_none_special_case",
"tests/test_response_parser.py::TestParseFetchResponse::test_FLAGS",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_msgid",
"tests/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODY",
"tests/test_response_parser.py::TestParseFetchResponse::test_simple_pairs",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODY_HEADER_FIELDS",
"tests/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE_normalised",
"tests/test_response_parser.py::TestParseFetchResponse::test_Address_str",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_empty_addresses",
"tests/test_response_parser.py::TestParseFetchResponse::test_literals",
"tests/test_response_parser.py::TestParseFetchResponse::test_same_message_appearing_multiple_times",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODYSTRUCTURE",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE",
"tests/test_response_parser.py::TestParseFetchResponse::test_UID",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_data",
"tests/test_response_parser.py::TestParseFetchResponse::test_partial_fetch",
"tests/test_response_parser.py::TestParseFetchResponse::test_missing_data",
"tests/test_response_parser.py::TestParseResponse::test_incomplete_tuple",
"tests/test_response_parser.py::TestParseResponse::test_nil",
"tests/test_response_parser.py::TestParseResponse::test_square_brackets",
"tests/test_response_parser.py::TestParseResponse::test_literal",
"tests/test_response_parser.py::TestParseResponse::test_string",
"tests/test_response_parser.py::TestParseResponse::test_quoted_specials",
"tests/test_response_parser.py::TestParseResponse::test_tuple",
"tests/test_response_parser.py::TestParseResponse::test_int",
"tests/test_response_parser.py::TestParseResponse::test_bad_quoting",
"tests/test_response_parser.py::TestParseResponse::test_nested_tuple",
"tests/test_response_parser.py::TestParseResponse::test_empty_tuple",
"tests/test_response_parser.py::TestParseResponse::test_bad_literal",
"tests/test_response_parser.py::TestParseResponse::test_envelopey",
"tests/test_response_parser.py::TestParseResponse::test_envelopey_quoted",
"tests/test_response_parser.py::TestParseResponse::test_int_and_tuple",
"tests/test_response_parser.py::TestParseResponse::test_complex_mixed",
"tests/test_response_parser.py::TestParseResponse::test_literal_with_more",
"tests/test_response_parser.py::TestParseResponse::test_deeper_nest_tuple",
"tests/test_response_parser.py::TestParseResponse::test_unquoted",
"tests/test_response_parser.py::TestParseMessageList::test_one_id",
"tests/test_response_parser.py::TestParseMessageList::test_modseq_interleaved",
"tests/test_response_parser.py::TestParseMessageList::test_modseq_no_space",
"tests/test_response_parser.py::TestParseMessageList::test_basic",
"tests/test_response_parser.py::TestParseMessageList::test_modseq"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2017-10-30 21:42:37+00:00
|
bsd-3-clause
| 3,993 |
|
mjs__imapclient-337
|
diff --git a/doc/src/concepts.rst b/doc/src/concepts.rst
index bacc41f..d67cf81 100644
--- a/doc/src/concepts.rst
+++ b/doc/src/concepts.rst
@@ -116,6 +116,14 @@ an up-to-date set of trusted CAs::
ssl_context = ssl.create_default_context(cafile=certifi.where())
+If the server supports it, you can also authenticate using a client
+certificate::
+
+ import ssl
+
+ ssl_context = ssl.create_default_context()
+ ssl_context.load_cert_chain("/path/to/client_certificate.crt")
+
The above examples show some of the most common TLS parameter
customisations but there are many other tweaks are possible. Consult
the Python 3 :py:mod:`ssl` package documentation for further options.
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index c383772..3613a5e 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -121,6 +121,27 @@ class SocketTimeout(namedtuple("SocketTimeout", "connect read")):
"""
+class MailboxQuotaRoots(namedtuple("MailboxQuotaRoots", "mailbox quota_roots")):
+ """Quota roots associated with a mailbox.
+
+ Represents the response of a GETQUOTAROOT command.
+
+ :ivar mailbox: the mailbox
+ :ivar quota_roots: list of quota roots associated with the mailbox
+ """
+
+class Quota(namedtuple("Quota", "quota_root resource usage limit")):
+ """Resource quota.
+
+ Represents the response of a GETQUOTA command.
+
+ :ivar quota_roots: the quota roots for which the limit apply
+ :ivar resource: the resource being limited (STORAGE, MESSAGES...)
+ :ivar usage: the current usage of the resource
+ :ivar limit: the maximum allowed usage of the resource
+ """
+
+
def require_capability(capability):
"""Decorator raising CapabilityError when a capability is not available."""
@@ -1321,6 +1342,84 @@ class IMAPClient(object):
who, what,
unpack=True)
+ @require_capability('QUOTA')
+ def get_quota(self, mailbox="INBOX"):
+ """Get the quotas associated with a mailbox.
+
+ Returns a list of Quota objects.
+ """
+ return self.get_quota_root(mailbox)[1]
+
+ @require_capability('QUOTA')
+ def _get_quota(self, quota_root=""):
+ """Get the quotas associated with a quota root.
+
+ This method is not private but put behind an underscore to show that
+ it is a low-level function. Users probably want to use `get_quota`
+ instead.
+
+ Returns a list of Quota objects.
+ """
+ return _parse_quota(
+ self._command_and_check('getquota', _quote(quota_root))
+ )
+
+ @require_capability('QUOTA')
+ def get_quota_root(self, mailbox):
+ """Get the quota roots for a mailbox.
+
+ The IMAP server responds with the quota root and the quotas associated
+ so there is usually no need to call `get_quota` after.
+
+ See :rfc:`2087` for more details.
+
+ Return a tuple of MailboxQuotaRoots and list of Quota associated
+ """
+ quota_root_rep = self._raw_command_untagged(
+ b'GETQUOTAROOT', to_bytes(mailbox), uid=False,
+ response_name='QUOTAROOT'
+ )
+ quota_rep = pop_with_default(self._imap.untagged_responses, 'QUOTA', [])
+ quota_root_rep = parse_response(quota_root_rep)
+ quota_root = MailboxQuotaRoots(
+ to_unicode(quota_root_rep[0]),
+ [to_unicode(q) for q in quota_root_rep[1:]]
+ )
+ return quota_root, _parse_quota(quota_rep)
+
+ @require_capability('QUOTA')
+ def set_quota(self, quotas):
+ """Set one or more quotas on resources.
+
+ :param quotas: list of Quota objects
+ """
+ if not quotas:
+ return
+
+ quota_root = None
+ set_quota_args = list()
+
+ for quota in quotas:
+ if quota_root is None:
+ quota_root = quota.quota_root
+ elif quota_root != quota.quota_root:
+ raise ValueError("set_quota only accepts a single quota root")
+
+ set_quota_args.append(
+ "{} {}".format(quota.resource, quota.limit)
+ )
+
+ set_quota_args = " ".join(set_quota_args)
+ args = [
+ to_bytes(_quote(quota_root)),
+ to_bytes("({})".format(set_quota_args))
+ ]
+
+ response = self._raw_command_untagged(
+ b'SETQUOTA', args, uid=False, response_name='QUOTA'
+ )
+ return _parse_quota(response)
+
def _check_resp(self, expected, command, typ, data):
"""Check command responses for errors.
@@ -1630,6 +1729,11 @@ def as_pairs(items):
i += 1
+def as_triplets(items):
+ a = iter(items)
+ return zip(a, a, a)
+
+
def _is8bit(data):
return any(b > 127 for b in iterbytes(data))
@@ -1703,6 +1807,20 @@ def utf7_decode_sequence(seq):
return [decode_utf7(s) for s in seq]
+def _parse_quota(quota_rep):
+ quota_rep = parse_response(quota_rep)
+ rv = list()
+ for quota_root, quota_resource_infos in as_pairs(quota_rep):
+ for quota_resource_info in as_triplets(quota_resource_infos):
+ rv.append(Quota(
+ quota_root=to_unicode(quota_root),
+ resource=to_unicode(quota_resource_info[0]),
+ usage=quota_resource_info[1],
+ limit=quota_resource_info[2]
+ ))
+ return rv
+
+
class IMAPlibLoggerAdapter(LoggerAdapter):
"""Adapter preventing IMAP secrets from going to the logging facility."""
diff --git a/imapclient/interact.py b/imapclient/interact.py
index 2afe589..8908406 100644
--- a/imapclient/interact.py
+++ b/imapclient/interact.py
@@ -25,9 +25,11 @@ def command_line():
help='Password to login with')
p.add_option('-P', '--port', dest='port', action='store', type=int,
default=None,
- help='IMAP port to use (default is 143, or 993 for SSL)')
- p.add_option('-s', '--ssl', dest='ssl', action='store_true', default=False,
- help='Use SSL connection')
+ help='IMAP port to use (default is 993 for TLS, or 143 otherwise)')
+ p.add_option('-s', '--ssl', dest='ssl', action='store_true', default=None,
+ help='Use SSL/TLS connection (default)')
+ p.add_option('', '--insecure', dest='insecure', action='store_true', default=False,
+ help='Use insecure connection (i.e. without SSL/TLS)')
p.add_option('-f', '--file', dest='file', action='store', default=None,
help='Config file (same as livetest)')
@@ -36,11 +38,16 @@ def command_line():
p.error('unexpected arguments %s' % ' '.join(args))
if opts.file:
- if opts.host or opts.username or opts.password or opts.port or opts.ssl:
+ if opts.host or opts.username or opts.password or opts.port or opts.ssl or opts.insecure:
p.error('If -f/--file is given no other options can be used')
# Use the options in the config file
opts = parse_config_file(opts.file)
else:
+ if opts.ssl and opts.insecure:
+ p.error("Can't use --ssl and --insecure at the same time")
+
+ opts.ssl = not opts.insecure
+
# Scan through options, filling in defaults and prompting when
# a compulsory option wasn't provided.
compulsory_opts = ('host', 'username', 'password')
diff --git a/imapclient/response_parser.py b/imapclient/response_parser.py
index 4331be6..6939fbb 100644
--- a/imapclient/response_parser.py
+++ b/imapclient/response_parser.py
@@ -160,8 +160,7 @@ def _int_or_error(value, error_text):
def _convert_INTERNALDATE(date_string, normalise_times=True):
- # Observed in https://sentry.nylas.com/sentry/sync-prod/group/5907/
- if date_string.upper() == b'NIL':
+ if date_string is None:
return None
try:
|
mjs/imapclient
|
88b7279eb2b969e8321fc6e6a96aa6f22708ffa2
|
diff --git a/tests/test_imapclient.py b/tests/test_imapclient.py
index f0bafa5..a2666b0 100644
--- a/tests/test_imapclient.py
+++ b/tests/test_imapclient.py
@@ -15,7 +15,10 @@ import six
from imapclient.exceptions import (
CapabilityError, IMAPClientError, ProtocolError
)
-from imapclient.imapclient import IMAPlibLoggerAdapter, require_capability
+from imapclient.imapclient import (
+ IMAPlibLoggerAdapter, _parse_quota, Quota, MailboxQuotaRoots,
+ require_capability
+)
from imapclient.fixed_offset import FixedOffset
from imapclient.testable_imapclient import TestableIMAPClient as IMAPClient
@@ -276,6 +279,87 @@ class TestAclMethods(IMAPClientTest):
self.assertEqual(response, b"SETACL done")
+class TestQuota(IMAPClientTest):
+
+ def setUp(self):
+ super(TestQuota, self).setUp()
+ self.client._cached_capabilities = [b'QUOTA']
+
+ def test_parse_quota(self):
+ self.assertEqual(_parse_quota([]), [])
+ self.assertEqual(
+ _parse_quota([b'"User quota" (STORAGE 586720 4882812)']),
+ [Quota('User quota', 'STORAGE', 586720, 4882812)]
+ )
+ self.assertEqual(
+ _parse_quota([
+ b'"User quota" (STORAGE 586720 4882812)',
+ b'"Global quota" (MESSAGES 42 1000)'
+ ]),
+ [
+ Quota('User quota', 'STORAGE', 586720, 4882812),
+ Quota('Global quota', 'MESSAGES', 42, 1000)
+ ]
+ )
+ self.assertEqual(
+ _parse_quota([
+ b'"User quota" (STORAGE 586720 4882812 MESSAGES 42 1000)',
+ ]),
+ [
+ Quota('User quota', 'STORAGE', 586720, 4882812),
+ Quota('User quota', 'MESSAGES', 42, 1000)
+ ]
+ )
+
+ def test__get_quota(self):
+ self.client._command_and_check = Mock()
+ self.client._command_and_check.return_value = (
+ [b'"User quota" (MESSAGES 42 1000)']
+ )
+
+ quotas = self.client._get_quota('foo')
+
+ self.client._command_and_check.assert_called_once_with(
+ 'getquota', '"foo"'
+ )
+ self.assertEqual(quotas, [Quota('User quota', 'MESSAGES', 42, 1000)])
+
+ def test_set_quota(self):
+ self.client._raw_command_untagged = Mock()
+ self.client._raw_command_untagged.return_value = (
+ [b'"User quota" (STORAGE 42 1000 MESSAGES 42 1000)']
+ )
+ quotas = [
+ Quota('User quota', 'STORAGE', 42, 1000),
+ Quota('User quota', 'MESSAGES', 42, 1000)
+ ]
+ resp = self.client.set_quota(quotas)
+
+ self.client._raw_command_untagged.assert_called_once_with(
+ b'SETQUOTA', [b'"User quota"', b'(STORAGE 1000 MESSAGES 1000)'],
+ uid=False, response_name='QUOTA'
+ )
+ self.assertListEqual(resp, quotas)
+
+ def test_get_quota_root(self):
+ self.client._raw_command_untagged = Mock()
+ self.client._raw_command_untagged.return_value = (
+ [b'"INBOX" "User quota"']
+ )
+ self.client._imap.untagged_responses = dict()
+
+ resp = self.client.get_quota_root("INBOX")
+
+ self.client._raw_command_untagged.assert_called_once_with(
+ b'GETQUOTAROOT', b'INBOX', uid=False, response_name='QUOTAROOT'
+ )
+ expected = (MailboxQuotaRoots("INBOX", ["User quota"]), list())
+ self.assertTupleEqual(resp, expected)
+
+ resp = self.client.get_quota("INBOX")
+ self.assertEqual(resp, [])
+
+
class TestIdleAndNoop(IMAPClientTest):
def setUp(self):
diff --git a/tests/test_response_parser.py b/tests/test_response_parser.py
index 04694fc..0e87381 100644
--- a/tests/test_response_parser.py
+++ b/tests/test_response_parser.py
@@ -473,6 +473,15 @@ class TestParseFetchResponse(unittest.TestCase):
datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4 * 60 - 30)))
self.assertEqual(dt, expected_dt)
+ def test_INTERNALDATE_NIL(self):
+ out = parse_fetch_response(
+ [b'1 (INTERNALDATE NIL)']
+ )
+ self.assertEqual(
+ out[1][b'INTERNALDATE'],
+ None
+ )
+
def test_mixed_types(self):
self.assertEqual(parse_fetch_response([(
b'1 (INTERNALDATE " 9-Feb-2007 17:08:08 +0100" RFC822 {21}',
|
quota support
Originally reported by: **Menno Smits (Bitbucket: [mjs0](https://bitbucket.org/mjs0))**
---
As per getquota, setquota and getquotaroot in imaplib
---
- Bitbucket: https://bitbucket.org/mjs0/imapclient/issue/70
|
0.0
|
88b7279eb2b969e8321fc6e6a96aa6f22708ffa2
|
[
"tests/test_imapclient.py::TestListFolders::test_blanks",
"tests/test_imapclient.py::TestListFolders::test_empty_response",
"tests/test_imapclient.py::TestListFolders::test_folder_encode_off",
"tests/test_imapclient.py::TestListFolders::test_funky_characters",
"tests/test_imapclient.py::TestListFolders::test_list_folders",
"tests/test_imapclient.py::TestListFolders::test_list_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_mixed",
"tests/test_imapclient.py::TestListFolders::test_quoted_specials",
"tests/test_imapclient.py::TestListFolders::test_simple",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name_parsed_as_long",
"tests/test_imapclient.py::TestListFolders::test_utf7_decoding",
"tests/test_imapclient.py::TestListFolders::test_without_quotes",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_with_special_use",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_without_special_use_nor_namespace",
"tests/test_imapclient.py::TestSelectFolder::test_normal",
"tests/test_imapclient.py::TestSelectFolder::test_unselect",
"tests/test_imapclient.py::TestAppend::test_with_msg_time",
"tests/test_imapclient.py::TestAppend::test_without_msg_time",
"tests/test_imapclient.py::TestAclMethods::test_getacl",
"tests/test_imapclient.py::TestAclMethods::test_setacl",
"tests/test_imapclient.py::TestQuota::test__get_quota",
"tests/test_imapclient.py::TestQuota::test_get_quota_root",
"tests/test_imapclient.py::TestQuota::test_parse_quota",
"tests/test_imapclient.py::TestQuota::test_set_quota",
"tests/test_imapclient.py::TestIdleAndNoop::test_consume_until_tagged_response",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_blocking",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_timeout",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_with_data",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_done",
"tests/test_imapclient.py::TestIdleAndNoop::test_noop",
"tests/test_imapclient.py::TestDebugLogging::test_IMAP_is_patched",
"tests/test_imapclient.py::TestTimeNormalisation::test_default",
"tests/test_imapclient.py::TestTimeNormalisation::test_pass_through",
"tests/test_imapclient.py::TestNamespace::test_complex",
"tests/test_imapclient.py::TestNamespace::test_folder_decoding",
"tests/test_imapclient.py::TestNamespace::test_other_only",
"tests/test_imapclient.py::TestNamespace::test_simple",
"tests/test_imapclient.py::TestNamespace::test_without_folder_decoding",
"tests/test_imapclient.py::TestCapabilities::test_caching",
"tests/test_imapclient.py::TestCapabilities::test_decorator",
"tests/test_imapclient.py::TestCapabilities::test_has_capability",
"tests/test_imapclient.py::TestCapabilities::test_post_auth_request",
"tests/test_imapclient.py::TestCapabilities::test_preauth",
"tests/test_imapclient.py::TestCapabilities::test_server_returned_capability_after_auth",
"tests/test_imapclient.py::TestCapabilities::test_with_starttls",
"tests/test_imapclient.py::TestId::test_id",
"tests/test_imapclient.py::TestId::test_invalid_parameters",
"tests/test_imapclient.py::TestId::test_no_support",
"tests/test_imapclient.py::TestRawCommand::test_complex",
"tests/test_imapclient.py::TestRawCommand::test_embedded_literal",
"tests/test_imapclient.py::TestRawCommand::test_failed_continuation_wait",
"tests/test_imapclient.py::TestRawCommand::test_invalid_input_type",
"tests/test_imapclient.py::TestRawCommand::test_literal_at_end",
"tests/test_imapclient.py::TestRawCommand::test_multiple_literals",
"tests/test_imapclient.py::TestRawCommand::test_not_uid",
"tests/test_imapclient.py::TestRawCommand::test_plain",
"tests/test_imapclient.py::TestExpunge::test_expunge",
"tests/test_imapclient.py::TestExpunge::test_id_expunge",
"tests/test_imapclient.py::TestShutdown::test_shutdown",
"tests/test_imapclient.py::TestContextManager::test_context_manager",
"tests/test_imapclient.py::TestContextManager::test_context_manager_fail_closing",
"tests/test_imapclient.py::TestContextManager::test_exception_inside_context_manager",
"tests/test_imapclient.py::TestProtocolError::test_tagged_response_with_parse_error",
"tests/test_response_parser.py::TestParseResponse::test_bad_literal",
"tests/test_response_parser.py::TestParseResponse::test_bad_quoting",
"tests/test_response_parser.py::TestParseResponse::test_complex_mixed",
"tests/test_response_parser.py::TestParseResponse::test_deeper_nest_tuple",
"tests/test_response_parser.py::TestParseResponse::test_empty_tuple",
"tests/test_response_parser.py::TestParseResponse::test_envelopey",
"tests/test_response_parser.py::TestParseResponse::test_envelopey_quoted",
"tests/test_response_parser.py::TestParseResponse::test_incomplete_tuple",
"tests/test_response_parser.py::TestParseResponse::test_int",
"tests/test_response_parser.py::TestParseResponse::test_int_and_tuple",
"tests/test_response_parser.py::TestParseResponse::test_literal",
"tests/test_response_parser.py::TestParseResponse::test_literal_with_more",
"tests/test_response_parser.py::TestParseResponse::test_nested_tuple",
"tests/test_response_parser.py::TestParseResponse::test_nil",
"tests/test_response_parser.py::TestParseResponse::test_quoted_specials",
"tests/test_response_parser.py::TestParseResponse::test_square_brackets",
"tests/test_response_parser.py::TestParseResponse::test_string",
"tests/test_response_parser.py::TestParseResponse::test_tuple",
"tests/test_response_parser.py::TestParseResponse::test_unquoted",
"tests/test_response_parser.py::TestParseMessageList::test_basic",
"tests/test_response_parser.py::TestParseMessageList::test_modseq",
"tests/test_response_parser.py::TestParseMessageList::test_modseq_interleaved",
"tests/test_response_parser.py::TestParseMessageList::test_modseq_no_space",
"tests/test_response_parser.py::TestParseMessageList::test_one_id",
"tests/test_response_parser.py::TestParseFetchResponse::test_Address_str",
"tests/test_response_parser.py::TestParseFetchResponse::test_Address_str_ignores_encoding_error",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODY",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODYSTRUCTURE",
"tests/test_response_parser.py::TestParseFetchResponse::test_BODY_HEADER_FIELDS",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_empty_addresses",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_invalid_date",
"tests/test_response_parser.py::TestParseFetchResponse::test_ENVELOPE_with_no_date",
"tests/test_response_parser.py::TestParseFetchResponse::test_FLAGS",
"tests/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE",
"tests/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE_NIL",
"tests/test_response_parser.py::TestParseFetchResponse::test_INTERNALDATE_normalised",
"tests/test_response_parser.py::TestParseFetchResponse::test_UID",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_UID",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_data",
"tests/test_response_parser.py::TestParseFetchResponse::test_bad_msgid",
"tests/test_response_parser.py::TestParseFetchResponse::test_basic",
"tests/test_response_parser.py::TestParseFetchResponse::test_literals",
"tests/test_response_parser.py::TestParseFetchResponse::test_literals_and_keys_with_square_brackets",
"tests/test_response_parser.py::TestParseFetchResponse::test_missing_data",
"tests/test_response_parser.py::TestParseFetchResponse::test_mixed_types",
"tests/test_response_parser.py::TestParseFetchResponse::test_multiple_messages",
"tests/test_response_parser.py::TestParseFetchResponse::test_none_special_case",
"tests/test_response_parser.py::TestParseFetchResponse::test_not_uid_is_key",
"tests/test_response_parser.py::TestParseFetchResponse::test_odd_pairs",
"tests/test_response_parser.py::TestParseFetchResponse::test_partial_fetch",
"tests/test_response_parser.py::TestParseFetchResponse::test_same_message_appearing_multiple_times",
"tests/test_response_parser.py::TestParseFetchResponse::test_simple_pairs"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-01-13 16:33:25+00:00
|
bsd-3-clause
| 3,994 |
|
mjs__imapclient-338
|
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index a15027c..c383772 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -4,6 +4,7 @@
from __future__ import unicode_literals
+import functools
import imaplib
import itertools
import select
@@ -120,6 +121,23 @@ class SocketTimeout(namedtuple("SocketTimeout", "connect read")):
"""
+def require_capability(capability):
+ """Decorator raising CapabilityError when a capability is not available."""
+
+ def actual_decorator(func):
+
+ @functools.wraps(func)
+ def wrapper(client, *args, **kwargs):
+ if not client.has_capability(capability):
+ raise exceptions.CapabilityError(
+ 'Server does not support {} capability'.format(capability)
+ )
+ return func(client, *args, **kwargs)
+
+ return wrapper
+ return actual_decorator
+
+
class IMAPClient(object):
"""A connection to the IMAP server specified by *host* is made when
this class is instantiated.
@@ -261,6 +279,7 @@ class IMAPClient(object):
# In the py3 version it's just sock.
return getattr(self._imap, 'sslobj', self._imap.sock)
+ @require_capability('STARTTLS')
def starttls(self, ssl_context=None):
"""Switch to an SSL encrypted connection by sending a STARTTLS command.
@@ -350,6 +369,7 @@ class IMAPClient(object):
self._imap.shutdown()
logger.info('Connection closed')
+ @require_capability('ENABLE')
def enable(self, *capabilities):
"""Activate one or more server side capability extensions.
@@ -381,6 +401,7 @@ class IMAPClient(object):
return []
return resp.split()
+ @require_capability('ID')
def id_(self, parameters=None):
"""Issue the ID command, returning a dict of server implementation
fields.
@@ -388,9 +409,6 @@ class IMAPClient(object):
*parameters* should be specified as a dictionary of field/value pairs,
for example: ``{"name": "IMAPClient", "version": "0.12"}``
"""
- if not self.has_capability('ID'):
- raise exceptions.CapabilityError('server does not support IMAP ID extension')
-
if parameters is None:
args = 'NIL'
else:
@@ -462,6 +480,7 @@ class IMAPClient(object):
# be detected by this method.
return to_bytes(capability).upper() in self.capabilities()
+ @require_capability('NAMESPACE')
def namespace(self):
"""Return the namespace for the account as a (personal, other,
shared) tuple.
@@ -512,6 +531,7 @@ class IMAPClient(object):
"""
return self._do_list('LIST', directory, pattern)
+ @require_capability('XLIST')
def xlist_folders(self, directory="", pattern="*"):
"""Execute the XLIST command, returning ``(flags, delimiter,
name)`` tuples.
@@ -536,9 +556,7 @@ class IMAPClient(object):
This is a *deprecated* Gmail-specific IMAP extension (See
https://developers.google.com/gmail/imap_extensions#xlist_is_deprecated
- for more information). It is the responsibility of the caller
- to either check for ``XLIST`` in the server capabilites, or to
- handle the error if the server doesn't support this extension.
+ for more information).
The *directory* and *pattern* arguments are as per
list_folders().
@@ -621,7 +639,6 @@ class IMAPClient(object):
return None
-
def select_folder(self, folder, readonly=False):
"""Set the current folder on the server.
@@ -643,6 +660,7 @@ class IMAPClient(object):
self._command_and_check('select', self._normalise_folder(folder), readonly)
return self._process_select_response(self._imap.untagged_responses)
+ @require_capability('UNSELECT')
def unselect_folder(self):
"""Unselect the current folder and release associated resources.
@@ -701,6 +719,7 @@ class IMAPClient(object):
tag = self._imap._command('NOOP')
return self._consume_until_tagged_response(tag, 'NOOP')
+ @require_capability('IDLE')
def idle(self):
"""Put the server into IDLE mode.
@@ -721,6 +740,7 @@ class IMAPClient(object):
if resp is not None:
raise exceptions.IMAPClientError('Unexpected IDLE response: %s' % resp)
+ @require_capability('IDLE')
def idle_check(self, timeout=None):
"""Check for any IDLE responses sent by the server.
@@ -769,6 +789,7 @@ class IMAPClient(object):
sock.setblocking(1)
self._set_read_timeout()
+ @require_capability('IDLE')
def idle_done(self):
"""Take the server out of IDLE mode.
@@ -913,6 +934,7 @@ class IMAPClient(object):
"""
return self._search(criteria, charset)
+ @require_capability('X-GM-EXT-1')
def gmail_search(self, query, charset='UTF-8'):
"""Search using Gmail's X-GM-RAW attribute.
@@ -958,6 +980,7 @@ class IMAPClient(object):
return parse_message_list(data)
+ @require_capability('SORT')
def sort(self, sort_criteria, criteria='ALL', charset='UTF-8'):
"""Return a list of message ids from the currently selected
folder, sorted by *sort_criteria* and optionally filtered by
@@ -980,9 +1003,6 @@ class IMAPClient(object):
Note that SORT is an extension to the IMAP4 standard so it may
not be supported by all IMAP servers.
"""
- if not self.has_capability('SORT'):
- raise exceptions.CapabilityError('The server does not support the SORT extension')
-
args = [
_normalise_sort_criteria(sort_criteria),
to_bytes(charset),
@@ -1228,6 +1248,7 @@ class IMAPClient(object):
self._normalise_folder(folder),
uid=True, unpack=True)
+ @require_capability('MOVE')
def move(self, messages, folder):
"""Atomically move messages to another folder.
@@ -1278,6 +1299,7 @@ class IMAPClient(object):
tag = self._imap._command('EXPUNGE')
return self._consume_until_tagged_response(tag, 'EXPUNGE')
+ @require_capability('ACL')
def getacl(self, folder):
"""Returns a list of ``(who, acl)`` tuples describing the
access controls for *folder*.
@@ -1287,6 +1309,7 @@ class IMAPClient(object):
parts = parts[1:] # First item is folder name
return [(parts[i], parts[i + 1]) for i in xrange(0, len(parts), 2)]
+ @require_capability('ACL')
def setacl(self, folder, who, what):
"""Set an ACL (*what*) for user (*who*) for a folder.
|
mjs/imapclient
|
ad4c23a73b5e36e82c1d60975030c5d0549a593f
|
diff --git a/tests/test_enable.py b/tests/test_enable.py
index 2831e83..eaecaf4 100644
--- a/tests/test_enable.py
+++ b/tests/test_enable.py
@@ -18,6 +18,7 @@ class TestEnable(IMAPClientTest):
self.command = Mock()
self.client._raw_command_untagged = self.command
self.client._imap.state = 'AUTH'
+ self.client._cached_capabilities = [b'ENABLE']
def test_success(self):
self.command.return_value = b'CONDSTORE'
diff --git a/tests/test_imapclient.py b/tests/test_imapclient.py
index d3580bb..f0bafa5 100644
--- a/tests/test_imapclient.py
+++ b/tests/test_imapclient.py
@@ -15,7 +15,7 @@ import six
from imapclient.exceptions import (
CapabilityError, IMAPClientError, ProtocolError
)
-from imapclient.imapclient import IMAPlibLoggerAdapter
+from imapclient.imapclient import IMAPlibLoggerAdapter, require_capability
from imapclient.fixed_offset import FixedOffset
from imapclient.testable_imapclient import TestableIMAPClient as IMAPClient
@@ -219,6 +219,7 @@ class TestSelectFolder(IMAPClientTest):
})
def test_unselect(self):
+ self.client._cached_capabilities = [b'UNSELECT']
self.client._imap._simple_command.return_value = ('OK', ['Unselect completed.'])
#self.client._imap._untagged_response.return_value = (
# b'OK', [b'("name" "GImap" "vendor" "Google, Inc.")'])
@@ -255,6 +256,10 @@ class TestAppend(IMAPClientTest):
class TestAclMethods(IMAPClientTest):
+ def setUp(self):
+ super(TestAclMethods, self).setUp()
+ self.client._cached_capabilities = [b'ACL']
+
def test_getacl(self):
self.client._imap.getacl.return_value = ('OK', [b'INBOX Fred rwipslda Sally rwip'])
acl = self.client.getacl('INBOX')
@@ -273,6 +278,10 @@ class TestAclMethods(IMAPClientTest):
class TestIdleAndNoop(IMAPClientTest):
+ def setUp(self):
+ super(TestIdleAndNoop, self).setUp()
+ self.client._cached_capabilities = [b'IDLE']
+
def assert_sock_calls(self, sock):
self.assertListEqual(sock.method_calls, [
('settimeout', (None,), {}),
@@ -452,6 +461,10 @@ class TestTimeNormalisation(IMAPClientTest):
class TestNamespace(IMAPClientTest):
+ def setUp(self):
+ super(TestNamespace, self).setUp()
+ self.client._cached_capabilities = [b'NAMESPACE']
+
def set_return(self, value):
self.client._imap.namespace.return_value = ('OK', [value])
@@ -544,11 +557,35 @@ class TestCapabilities(IMAPClientTest):
self.assertTrue(self.client.has_capability('foo'))
self.assertFalse(self.client.has_capability('BAR'))
+ def test_decorator(self):
+
+ class Foo(object):
+
+ def has_capability(self, capability):
+ if capability == 'TRUE':
+ return True
+ return False
+
+ @require_capability('TRUE')
+ def yes(self):
+ return True
+
+ @require_capability('FALSE')
+ def no(self):
+ return False
+
+ foo = Foo()
+ self.assertTrue(foo.yes())
+ self.assertRaises(CapabilityError, foo.no)
+
class TestId(IMAPClientTest):
+ def setUp(self):
+ super(TestId, self).setUp()
+ self.client._cached_capabilities = [b'ID']
+
def test_id(self):
- self.client._cached_capabilities = (b'ID',)
self.client._imap._simple_command.return_value = ('OK', [b'Success'])
self.client._imap._untagged_response.return_value = (
b'OK', [b'("name" "GImap" "vendor" "Google, Inc.")'])
diff --git a/tests/test_search.py b/tests/test_search.py
index 9aadf34..4b0efa6 100644
--- a/tests/test_search.py
+++ b/tests/test_search.py
@@ -135,6 +135,10 @@ class TestSearch(TestSearchBase):
class TestGmailSearch(TestSearchBase):
+ def setUp(self):
+ super(TestGmailSearch, self).setUp()
+ self.client._cached_capabilities = [b'X-GM-EXT-1']
+
def test_bytes_query(self):
result = self.client.gmail_search(b'foo bar')
diff --git a/tests/test_starttls.py b/tests/test_starttls.py
index 483729d..edd3a59 100644
--- a/tests/test_starttls.py
+++ b/tests/test_starttls.py
@@ -30,6 +30,7 @@ class TestStarttls(IMAPClientTest):
self.client.ssl = False
self.client._starttls_done = False
self.client._imap._simple_command.return_value = "OK", [b'start TLS negotiation']
+ self.client._cached_capabilities = [b'STARTTLS']
def test_works(self):
resp = self.client.starttls(sentinel.ssl_context)
|
Clarify who is responsible for checking for capability
It is not clear who is responsible for checking if a capability is supported by a server prior to using it. Currently `ID` and `SORT` are checked by IMAPClient, but `IDLE` or `UNSELECT` are not.
It could be:
1. IMAPClient, checking before each call to a non-standard command
2. Let the user call `has_capability` himself
3. No check at all, execute the command and let the server throw an error
|
0.0
|
ad4c23a73b5e36e82c1d60975030c5d0549a593f
|
[
"tests/test_enable.py::TestEnable::test_failed1",
"tests/test_enable.py::TestEnable::test_failed2",
"tests/test_enable.py::TestEnable::test_multiple",
"tests/test_enable.py::TestEnable::test_success",
"tests/test_enable.py::TestEnable::test_wrong_state",
"tests/test_imapclient.py::TestListFolders::test_blanks",
"tests/test_imapclient.py::TestListFolders::test_empty_response",
"tests/test_imapclient.py::TestListFolders::test_folder_encode_off",
"tests/test_imapclient.py::TestListFolders::test_funky_characters",
"tests/test_imapclient.py::TestListFolders::test_list_folders",
"tests/test_imapclient.py::TestListFolders::test_list_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_mixed",
"tests/test_imapclient.py::TestListFolders::test_quoted_specials",
"tests/test_imapclient.py::TestListFolders::test_simple",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name_parsed_as_long",
"tests/test_imapclient.py::TestListFolders::test_utf7_decoding",
"tests/test_imapclient.py::TestListFolders::test_without_quotes",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_with_special_use",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_without_special_use_nor_namespace",
"tests/test_imapclient.py::TestSelectFolder::test_normal",
"tests/test_imapclient.py::TestSelectFolder::test_unselect",
"tests/test_imapclient.py::TestAppend::test_with_msg_time",
"tests/test_imapclient.py::TestAppend::test_without_msg_time",
"tests/test_imapclient.py::TestAclMethods::test_getacl",
"tests/test_imapclient.py::TestAclMethods::test_setacl",
"tests/test_imapclient.py::TestIdleAndNoop::test_consume_until_tagged_response",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_blocking",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_timeout",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_with_data",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_done",
"tests/test_imapclient.py::TestIdleAndNoop::test_noop",
"tests/test_imapclient.py::TestDebugLogging::test_IMAP_is_patched",
"tests/test_imapclient.py::TestTimeNormalisation::test_default",
"tests/test_imapclient.py::TestTimeNormalisation::test_pass_through",
"tests/test_imapclient.py::TestNamespace::test_complex",
"tests/test_imapclient.py::TestNamespace::test_folder_decoding",
"tests/test_imapclient.py::TestNamespace::test_other_only",
"tests/test_imapclient.py::TestNamespace::test_simple",
"tests/test_imapclient.py::TestNamespace::test_without_folder_decoding",
"tests/test_imapclient.py::TestCapabilities::test_caching",
"tests/test_imapclient.py::TestCapabilities::test_decorator",
"tests/test_imapclient.py::TestCapabilities::test_has_capability",
"tests/test_imapclient.py::TestCapabilities::test_post_auth_request",
"tests/test_imapclient.py::TestCapabilities::test_preauth",
"tests/test_imapclient.py::TestCapabilities::test_server_returned_capability_after_auth",
"tests/test_imapclient.py::TestCapabilities::test_with_starttls",
"tests/test_imapclient.py::TestId::test_id",
"tests/test_imapclient.py::TestId::test_invalid_parameters",
"tests/test_imapclient.py::TestId::test_no_support",
"tests/test_imapclient.py::TestRawCommand::test_complex",
"tests/test_imapclient.py::TestRawCommand::test_embedded_literal",
"tests/test_imapclient.py::TestRawCommand::test_failed_continuation_wait",
"tests/test_imapclient.py::TestRawCommand::test_invalid_input_type",
"tests/test_imapclient.py::TestRawCommand::test_literal_at_end",
"tests/test_imapclient.py::TestRawCommand::test_multiple_literals",
"tests/test_imapclient.py::TestRawCommand::test_not_uid",
"tests/test_imapclient.py::TestRawCommand::test_plain",
"tests/test_imapclient.py::TestExpunge::test_expunge",
"tests/test_imapclient.py::TestExpunge::test_id_expunge",
"tests/test_imapclient.py::TestShutdown::test_shutdown",
"tests/test_imapclient.py::TestContextManager::test_context_manager",
"tests/test_imapclient.py::TestContextManager::test_context_manager_fail_closing",
"tests/test_imapclient.py::TestContextManager::test_exception_inside_context_manager",
"tests/test_imapclient.py::TestProtocolError::test_tagged_response_with_parse_error",
"tests/test_search.py::TestSearch::test_bytes_criteria",
"tests/test_search.py::TestSearch::test_bytes_criteria_with_charset",
"tests/test_search.py::TestSearch::test_modseq",
"tests/test_search.py::TestSearch::test_nested",
"tests/test_search.py::TestSearch::test_nested_empty",
"tests/test_search.py::TestSearch::test_nested_multiple",
"tests/test_search.py::TestSearch::test_nested_tuple",
"tests/test_search.py::TestSearch::test_no_results",
"tests/test_search.py::TestSearch::test_quoting",
"tests/test_search.py::TestSearch::test_search_custom_exception_with_invalid_list",
"tests/test_search.py::TestSearch::test_search_custom_exception_with_invalid_text",
"tests/test_search.py::TestSearch::test_single",
"tests/test_search.py::TestSearch::test_unicode_criteria",
"tests/test_search.py::TestSearch::test_unicode_criteria_with_charset",
"tests/test_search.py::TestSearch::test_with_date",
"tests/test_search.py::TestSearch::test_with_datetime",
"tests/test_search.py::TestSearch::test_zero_length_quoting",
"tests/test_search.py::TestGmailSearch::test_bytes_query",
"tests/test_search.py::TestGmailSearch::test_bytes_query_with_charset",
"tests/test_search.py::TestGmailSearch::test_unicode_criteria_with_charset",
"tests/test_starttls.py::TestStarttls::test_command_fails",
"tests/test_starttls.py::TestStarttls::test_fails_if_called_twice",
"tests/test_starttls.py::TestStarttls::test_fails_if_ssl_true",
"tests/test_starttls.py::TestStarttls::test_works"
] |
[] |
{
"failed_lite_validators": [
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-01-16 20:53:47+00:00
|
bsd-3-clause
| 3,995 |
|
mjs__imapclient-399
|
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index ac89622..46e9257 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -1288,6 +1288,23 @@ class IMAPClient(object):
to_bytes(msg),
unpack=True)
+ @require_capability('MULTIAPPEND')
+ def multiappend(self, folder, msgs):
+ """Append messages to *folder* using the MULTIAPPEND feature from :rfc:`3502`.
+
+ *msgs* should be a list of strings containing the full message including
+ headers.
+
+ Returns the APPEND response from the server.
+ """
+ msgs = [_literal(to_bytes(m)) for m in msgs]
+
+ return self._raw_command(
+ b'APPEND',
+ [self._normalise_folder(folder)] + msgs,
+ uid=False,
+ )
+
def copy(self, messages, folder):
"""Copy one or more messages from the current folder to
*folder*. Returns the COPY response string returned by the
@@ -1538,8 +1555,14 @@ class IMAPClient(object):
def _send_literal(self, tag, item):
"""Send a single literal for the command with *tag*.
"""
+ if b'LITERAL+' in self._cached_capabilities:
+ out = b' {' + str(len(item)).encode('ascii') + b'+}\r\n' + item
+ logger.debug('> %s', debug_trunc(out, 64))
+ self._imap.send(out)
+ return
+
out = b' {' + str(len(item)).encode('ascii') + b'}\r\n'
- logger.debug(out)
+ logger.debug('> %s', out)
self._imap.send(out)
# Wait for continuation response
@@ -1666,6 +1689,9 @@ def _normalise_sort_criteria(criteria, charset=None):
criteria = [criteria]
return b'(' + b' '.join(to_bytes(item).upper() for item in criteria) + b')'
+class _literal(bytes):
+ """Hold message data that should always be sent as a literal."""
+ pass
class _quoted(binary_type):
"""
@@ -1764,7 +1790,7 @@ def as_triplets(items):
def _is8bit(data):
- return any(b > 127 for b in iterbytes(data))
+ return isinstance(data, _literal) or any(b > 127 for b in iterbytes(data))
def _iter_with_last(items):
|
mjs/imapclient
|
dd4812b2494ae20f10f1a8737732925db8baa10d
|
diff --git a/tests/test_imapclient.py b/tests/test_imapclient.py
index 3d6dd74..13afd05 100644
--- a/tests/test_imapclient.py
+++ b/tests/test_imapclient.py
@@ -18,7 +18,7 @@ from imapclient.exceptions import (
)
from imapclient.imapclient import (
IMAPlibLoggerAdapter, _parse_quota, Quota, MailboxQuotaRoots,
- require_capability
+ require_capability, _literal
)
from imapclient.fixed_offset import FixedOffset
from imapclient.testable_imapclient import TestableIMAPClient as IMAPClient
@@ -270,6 +270,14 @@ class TestAppend(IMAPClientTest):
self.client._imap.append.assert_called_with(
b'"foobar"', '(FLAG WAVE)', '"somedate"', msg)
+ def test_multiappend(self):
+ self.client._cached_capabilities = (b'MULTIAPPEND',)
+ self.client._raw_command = Mock()
+ self.client.multiappend('foobar', ['msg1', 'msg2'])
+
+ self.client._raw_command.assert_called_once_with(
+ b'APPEND', [b'"foobar"', b'msg1', b'msg2'], uid=False
+ )
class TestAclMethods(IMAPClientTest):
@@ -805,6 +813,7 @@ class TestRawCommand(IMAPClientTest):
super(TestRawCommand, self).setUp()
self.client._imap._get_response.return_value = None
self.client._imap._command_complete.return_value = ('OK', ['done'])
+ self.client._cached_capabilities = ()
def check(self, command, args, expected):
typ, data = self.client._raw_command(command, args)
@@ -842,6 +851,17 @@ class TestRawCommand(IMAPClientTest):
b'\xcc\r\n'
)
+ def test_literal_plus(self):
+ self.client._cached_capabilities = (b'LITERAL+',)
+
+ typ, data = self.client._raw_command(b'APPEND', [b'\xff', _literal(b'hello')], uid=False)
+ self.assertEqual(typ, 'OK')
+ self.assertEqual(data, ['done'])
+ self.assertEqual(self.client._imap.sent,
+ b'tag APPEND {1+}\r\n'
+ b'\xff {5+}\r\n'
+ b'hello\r\n')
+
def test_complex(self):
self.check(b'search', [b'FLAGGED', b'TEXT', b'\xfe\xff', b'TEXT', b'\xcc', b'TEXT', b'foo'],
b'tag UID SEARCH FLAGGED TEXT {2}\r\n'
|
MULTIAPPEND support
Originally reported by: **Erik Quaeghebeur (Bitbucket: [equaeghe](https://bitbucket.org/equaeghe))**
---
See https://tools.ietf.org/html/rfc3502 (and perhaps updates).
It would seem impossible to do this by extending the append method without breaking backwards compatability, so perhaps an option is to add a multiappend method taking an iterator over {'msg': ...[, 'flags': ...][, 'date': ...]}-dicts that can fall-back to multiple appends.
This kind of functionality may be useful for clients also working in disconnected mode.
---
- Bitbucket: https://bitbucket.org/mjs0/imapclient/issue/198
|
0.0
|
dd4812b2494ae20f10f1a8737732925db8baa10d
|
[
"tests/test_imapclient.py::TestListFolders::test_blanks",
"tests/test_imapclient.py::TestListFolders::test_empty_response",
"tests/test_imapclient.py::TestListFolders::test_folder_encode_off",
"tests/test_imapclient.py::TestListFolders::test_funky_characters",
"tests/test_imapclient.py::TestListFolders::test_list_folders",
"tests/test_imapclient.py::TestListFolders::test_list_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_mixed",
"tests/test_imapclient.py::TestListFolders::test_quoted_specials",
"tests/test_imapclient.py::TestListFolders::test_simple",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name_parsed_as_long",
"tests/test_imapclient.py::TestListFolders::test_utf7_decoding",
"tests/test_imapclient.py::TestListFolders::test_without_quotes",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_with_special_use",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_with_special_use_single_flag",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_without_special_use_nor_namespace",
"tests/test_imapclient.py::TestSelectFolder::test_normal",
"tests/test_imapclient.py::TestSelectFolder::test_unselect",
"tests/test_imapclient.py::TestAppend::test_multiappend",
"tests/test_imapclient.py::TestAppend::test_with_msg_time",
"tests/test_imapclient.py::TestAppend::test_without_msg_time",
"tests/test_imapclient.py::TestAclMethods::test_getacl",
"tests/test_imapclient.py::TestAclMethods::test_setacl",
"tests/test_imapclient.py::TestQuota::test__get_quota",
"tests/test_imapclient.py::TestQuota::test_get_quota_root",
"tests/test_imapclient.py::TestQuota::test_parse_quota",
"tests/test_imapclient.py::TestQuota::test_set_quota",
"tests/test_imapclient.py::TestIdleAndNoop::test_consume_until_tagged_response",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_blocking",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_timeout",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_with_data",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_done",
"tests/test_imapclient.py::TestIdleAndNoop::test_noop",
"tests/test_imapclient.py::TestDebugLogging::test_IMAP_is_patched",
"tests/test_imapclient.py::TestDebugLogging::test_redacted_password",
"tests/test_imapclient.py::TestTimeNormalisation::test_default",
"tests/test_imapclient.py::TestTimeNormalisation::test_pass_through",
"tests/test_imapclient.py::TestNamespace::test_complex",
"tests/test_imapclient.py::TestNamespace::test_folder_decoding",
"tests/test_imapclient.py::TestNamespace::test_other_only",
"tests/test_imapclient.py::TestNamespace::test_simple",
"tests/test_imapclient.py::TestNamespace::test_without_folder_decoding",
"tests/test_imapclient.py::TestCapabilities::test_caching",
"tests/test_imapclient.py::TestCapabilities::test_decorator",
"tests/test_imapclient.py::TestCapabilities::test_has_capability",
"tests/test_imapclient.py::TestCapabilities::test_post_auth_request",
"tests/test_imapclient.py::TestCapabilities::test_preauth",
"tests/test_imapclient.py::TestCapabilities::test_server_returned_capability_after_auth",
"tests/test_imapclient.py::TestCapabilities::test_with_starttls",
"tests/test_imapclient.py::TestId::test_id",
"tests/test_imapclient.py::TestId::test_invalid_parameters",
"tests/test_imapclient.py::TestId::test_no_support",
"tests/test_imapclient.py::TestRawCommand::test_complex",
"tests/test_imapclient.py::TestRawCommand::test_embedded_literal",
"tests/test_imapclient.py::TestRawCommand::test_failed_continuation_wait",
"tests/test_imapclient.py::TestRawCommand::test_invalid_input_type",
"tests/test_imapclient.py::TestRawCommand::test_literal_at_end",
"tests/test_imapclient.py::TestRawCommand::test_literal_plus",
"tests/test_imapclient.py::TestRawCommand::test_multiple_literals",
"tests/test_imapclient.py::TestRawCommand::test_not_uid",
"tests/test_imapclient.py::TestRawCommand::test_plain",
"tests/test_imapclient.py::TestExpunge::test_expunge",
"tests/test_imapclient.py::TestExpunge::test_id_expunge",
"tests/test_imapclient.py::TestShutdown::test_shutdown",
"tests/test_imapclient.py::TestContextManager::test_context_manager",
"tests/test_imapclient.py::TestContextManager::test_context_manager_fail_closing",
"tests/test_imapclient.py::TestContextManager::test_exception_inside_context_manager",
"tests/test_imapclient.py::TestProtocolError::test_tagged_response_with_parse_error"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-18 17:12:56+00:00
|
bsd-3-clause
| 3,996 |
|
mjs__imapclient-451
|
diff --git a/examples/idle_selector_example.py b/examples/idle_selector_example.py
new file mode 100644
index 0000000..e8ff729
--- /dev/null
+++ b/examples/idle_selector_example.py
@@ -0,0 +1,36 @@
+from datetime import datetime, timedelta
+from selectors import DefaultSelector, EVENT_READ
+
+from imapclient import IMAPClient
+
+HOST = "localhost"
+USERNAME = "user"
+PASSWORD = "Tr0ub4dor&3"
+RESPONSE_TIMEOUT_SECONDS = 15
+IDLE_SECONDS = 60 * 24
+
+with IMAPClient(HOST, timeout=RESPONSE_TIMEOUT_SECONDS) as server:
+ server.login(USERNAME, PASSWORD)
+ server.select_folder("INBOX", readonly=True)
+ server.idle()
+ print(
+ "Connection is now in IDLE mode,"
+ " send yourself an email or quit with ^c"
+ )
+ try:
+ with DefaultSelector() as selector:
+ selector.register(server.socket(), EVENT_READ, None)
+ now = datetime.now
+ end_at = now() + timedelta(seconds=IDLE_SECONDS)
+ while selector.select((end_at - now()).total_seconds()):
+ responses = server.idle_check(timeout=0)
+ if not responses:
+ raise ConnectionError(
+ "Socket readable without data. Likely closed."
+ )
+ print("Server sent:", responses)
+ print("IDLE time out.")
+ except KeyboardInterrupt:
+ print("") # Newline after the typically echoed ^C.
+ server.idle_done()
+ print("IDLE mode done")
diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py
index 8d58693..a7bc703 100644
--- a/imapclient/imapclient.py
+++ b/imapclient/imapclient.py
@@ -11,6 +11,7 @@ import select
import socket
import sys
import re
+import warnings
from collections import namedtuple
from datetime import datetime, date
from operator import itemgetter
@@ -329,10 +330,26 @@ class IMAPClient(object):
def _set_read_timeout(self):
if self._timeout is not None:
- self._sock.settimeout(self._timeout.read)
+ self.socket().settimeout(self._timeout.read)
@property
def _sock(self):
+ warnings.warn("_sock is deprecated. Use socket().", DeprecationWarning)
+ return self.socket()
+
+ def socket(self):
+ """Returns socket used to connect to server.
+
+ The socket is provided for polling purposes only.
+ It can be used in,
+ for example, :py:meth:`selectors.BaseSelector.register`
+ and :py:meth:`asyncio.loop.add_reader` to wait for data.
+
+ .. WARNING::
+ All other uses of the returned socket are unsupported.
+ This includes reading from and writing to the socket,
+ as they are likely to break internal bookkeeping of messages.
+ """
# In py2, imaplib has sslobj (for SSL connections), and sock for non-SSL.
# In the py3 version it's just sock.
return getattr(self._imap, "sslobj", self._imap.sock)
@@ -919,7 +936,7 @@ class IMAPClient(object):
(1, b'EXISTS'),
(1, b'FETCH', (b'FLAGS', (b'\\NotJunk',)))]
"""
- sock = self._sock
+ sock = self.socket()
# make the socket non-blocking so the timeout can be
# implemented for this call
|
mjs/imapclient
|
8ececac1c7aa4d7eb5c8846c88e8c41ce08c6340
|
diff --git a/tests/test_imapclient.py b/tests/test_imapclient.py
index 4a065de..d42db68 100644
--- a/tests/test_imapclient.py
+++ b/tests/test_imapclient.py
@@ -7,6 +7,7 @@ from __future__ import unicode_literals
import itertools
import socket
import sys
+import warnings
from datetime import datetime
import logging
@@ -1055,3 +1056,12 @@ class TestProtocolError(IMAPClientTest):
with self.assertRaises(ProtocolError):
client._consume_until_tagged_response(sentinel.tag, b"IDLE")
+
+class TestSocket(IMAPClientTest):
+ def test_issues_warning_for_deprecating_sock_property(self):
+ mock_sock = Mock()
+ self.client._imap.sock = self.client._imap.sslobj = mock_sock
+ with warnings.catch_warnings(record=True) as warnings_caught:
+ warnings.simplefilter("always", DeprecationWarning)
+ assert self.client._sock == self.client.socket()
+ assert len(warnings_caught) == 1
|
Accessing the socket used by `IMAPClient`
To watch a mailbox using IDLE, the current documentation suggests [using a busyloop](https://imapclient.readthedocs.io/en/2.2.0/advanced.html#watching-a-mailbox-using-idle) with a relatively small timeout to check for responses. A small timeout because `IMAPClient.idle_check` uses a [blocking poll](https://github.com/mjs/imapclient/blob/master/imapclient/imapclient.py#L936) with this timeout and handling `KeyboardInterrup` is not possible while it blocks. An alternative to the busy loop was suggested in <https://github.com/mjs/imapclient/issues/322>, using `select.select` to poll both the connecting socket and a separate socket.
However, in order to poll the socket, access to the underlying socket is required, available as `IMAPClient._sock`. My understanding is that this attribute is an implementation detail. Can this be relied upon? If not, is it possible to make the socket available as part of the API?
|
0.0
|
8ececac1c7aa4d7eb5c8846c88e8c41ce08c6340
|
[
"tests/test_imapclient.py::TestSocket::test_issues_warning_for_deprecating_sock_property"
] |
[
"tests/test_imapclient.py::TestListFolders::test_blanks",
"tests/test_imapclient.py::TestListFolders::test_empty_response",
"tests/test_imapclient.py::TestListFolders::test_folder_encode_off",
"tests/test_imapclient.py::TestListFolders::test_funky_characters",
"tests/test_imapclient.py::TestListFolders::test_list_folders",
"tests/test_imapclient.py::TestListFolders::test_list_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders",
"tests/test_imapclient.py::TestListFolders::test_list_sub_folders_NO",
"tests/test_imapclient.py::TestListFolders::test_mixed",
"tests/test_imapclient.py::TestListFolders::test_quoted_specials",
"tests/test_imapclient.py::TestListFolders::test_simple",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name",
"tests/test_imapclient.py::TestListFolders::test_unquoted_numeric_folder_name_parsed_as_long",
"tests/test_imapclient.py::TestListFolders::test_utf7_decoding",
"tests/test_imapclient.py::TestListFolders::test_without_quotes",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_with_special_use",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_with_special_use_single_flag",
"tests/test_imapclient.py::TestFindSpecialFolder::test_find_special_folder_without_special_use_nor_namespace",
"tests/test_imapclient.py::TestSelectFolder::test_normal",
"tests/test_imapclient.py::TestSelectFolder::test_unselect",
"tests/test_imapclient.py::TestAppend::test_multiappend",
"tests/test_imapclient.py::TestAppend::test_with_msg_time",
"tests/test_imapclient.py::TestAppend::test_without_msg_time",
"tests/test_imapclient.py::TestAclMethods::test_getacl",
"tests/test_imapclient.py::TestAclMethods::test_setacl",
"tests/test_imapclient.py::TestQuota::test__get_quota",
"tests/test_imapclient.py::TestQuota::test_get_quota_root",
"tests/test_imapclient.py::TestQuota::test_parse_quota",
"tests/test_imapclient.py::TestQuota::test_set_quota",
"tests/test_imapclient.py::TestIdleAndNoop::test_consume_until_tagged_response",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_blocking",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_blocking_poll",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_timeout",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_timeout_poll",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_with_data",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_check_with_data_poll",
"tests/test_imapclient.py::TestIdleAndNoop::test_idle_done",
"tests/test_imapclient.py::TestIdleAndNoop::test_noop",
"tests/test_imapclient.py::TestDebugLogging::test_IMAP_is_patched",
"tests/test_imapclient.py::TestDebugLogging::test_redacted_password",
"tests/test_imapclient.py::TestTimeNormalisation::test_default",
"tests/test_imapclient.py::TestTimeNormalisation::test_pass_through",
"tests/test_imapclient.py::TestNamespace::test_complex",
"tests/test_imapclient.py::TestNamespace::test_folder_decoding",
"tests/test_imapclient.py::TestNamespace::test_other_only",
"tests/test_imapclient.py::TestNamespace::test_simple",
"tests/test_imapclient.py::TestNamespace::test_without_folder_decoding",
"tests/test_imapclient.py::TestCapabilities::test_caching",
"tests/test_imapclient.py::TestCapabilities::test_decorator",
"tests/test_imapclient.py::TestCapabilities::test_has_capability",
"tests/test_imapclient.py::TestCapabilities::test_post_auth_request",
"tests/test_imapclient.py::TestCapabilities::test_preauth",
"tests/test_imapclient.py::TestCapabilities::test_server_returned_capability_after_auth",
"tests/test_imapclient.py::TestCapabilities::test_with_starttls",
"tests/test_imapclient.py::TestId::test_id",
"tests/test_imapclient.py::TestId::test_invalid_parameters",
"tests/test_imapclient.py::TestId::test_no_support",
"tests/test_imapclient.py::TestRawCommand::test_complex",
"tests/test_imapclient.py::TestRawCommand::test_embedded_literal",
"tests/test_imapclient.py::TestRawCommand::test_failed_continuation_wait",
"tests/test_imapclient.py::TestRawCommand::test_invalid_input_type",
"tests/test_imapclient.py::TestRawCommand::test_literal_at_end",
"tests/test_imapclient.py::TestRawCommand::test_literal_plus",
"tests/test_imapclient.py::TestRawCommand::test_multiple_literals",
"tests/test_imapclient.py::TestRawCommand::test_not_uid",
"tests/test_imapclient.py::TestRawCommand::test_plain",
"tests/test_imapclient.py::TestExpunge::test_expunge",
"tests/test_imapclient.py::TestExpunge::test_id_expunge",
"tests/test_imapclient.py::TestShutdown::test_shutdown",
"tests/test_imapclient.py::TestContextManager::test_context_manager",
"tests/test_imapclient.py::TestContextManager::test_context_manager_fail_closing",
"tests/test_imapclient.py::TestContextManager::test_exception_inside_context_manager",
"tests/test_imapclient.py::TestProtocolError::test_tagged_response_with_parse_error"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-11-25 18:41:54+00:00
|
bsd-3-clause
| 3,997 |
|
mkaz__termgraph-40
|
diff --git a/setup.py b/setup.py
index 7b9e577..69f91a8 100644
--- a/setup.py
+++ b/setup.py
@@ -19,7 +19,7 @@ setup(
name='termgraph',
packages=['termgraph'],
entry_points={'console_scripts': ['termgraph=termgraph.termgraph:main']},
- version='0.1.4',
+ version='0.1.5',
author="mkaz",
author_email="[email protected]",
url='https://github.com/mkaz/termgraph',
@@ -28,6 +28,7 @@ setup(
description='a python command-line tool which draws basic graphs in the terminal',
platforms='any',
keywords='python CLI tool drawing graphs shell terminal',
+ python_requires='>=3.6',
install_requires=['colorama'],
classifiers=[
'Development Status :: 5 - Production/Stable',
diff --git a/termgraph/termgraph.py b/termgraph/termgraph.py
index 520a12a..ae3a90e 100755
--- a/termgraph/termgraph.py
+++ b/termgraph/termgraph.py
@@ -13,7 +13,7 @@ from itertools import zip_longest
from colorama import init
-VERSION = '0.1.4'
+VERSION = '0.1.5'
init()
@@ -267,7 +267,8 @@ def stacked_graph(labels, data, normal_data, len_categories, args, colors):
# Hide the labels.
label = ''
else:
- label = "{}: ".format(labels[i])
+ label = "{:<{x}}: ".format(labels[i],
+ x=find_max_label_length(labels))
print(label, end="")
values = data[i]
|
mkaz/termgraph
|
ca79e57b02f321a2f23c44677014e9e7013c0436
|
diff --git a/tests/test_termgraph.py b/tests/test_termgraph.py
index 441c0a5..aef7b4c 100644
--- a/tests/test_termgraph.py
+++ b/tests/test_termgraph.py
@@ -168,6 +168,24 @@ class TermgraphTest(unittest.TestCase):
output = output.getvalue().strip()
assert output == '2007: [91m▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇[0m[94m▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇[0m 373.84\n2008: [91m▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇[0m[94m▏[0m 236.23\n2009: [91m▇▇▇[0m[94m▇▇▇▇▇▇▇▇▇▇▇▇[0m 69.53\n2010: [91m▇▇▇▇▇▇▇▇▇▇▇▇[0m[94m▏[0m 57.21\n2011: [91m▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇[0m[94m▇[0m 519.42\n2012: [91m▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇[0m[94m▇▇▇▇[0m 232.25\n2014: [91m▇▇▇▇▇▇[0m[94m▇▇▇▇[0m 50.00'
+ def test_stacked_graph_different_label_length_prints_correct_graph(self):
+ with patch('sys.stdout', new=StringIO()) as output:
+ labels = ['LOOOOOOOOOOOOOOOOOOOOOOOOONG LINE', 'SHORT LINE']
+ data = [[10.0, 20.0], [10.0, 20.0]]
+ normal_data = [[10.0, 20.0], [10.0, 20.0]]
+ len_categories = 2
+ args = {'filename': '-', 'title': 'BEAUTIFUL', 'width': 50,
+ 'format': '{:<5.2f}', 'suffix': '',
+ 'no_labels': False, 'color': ['blue', 'red'],
+ 'vertical': False, 'stacked': True,
+ 'different_scale': False, 'calendar': False,
+ 'start_dt': None, 'custom_tick': '', 'delim': '',
+ 'verbose': False, 'version': False}
+ colors = [94, 91]
+ tg.chart(colors, data, args, labels)
+ output = output.getvalue().strip()
+ assert output == 'LOOOOOOOOOOOOOOOOOOOOOOOOONG LINE: \x1b[94m▇▇▇▇▇▇▇▇▇▇\x1b[0m\x1b[91m▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇\x1b[0m 30.00\nSHORT LINE : \x1b[94m▇▇▇▇▇▇▇▇▇▇\x1b[0m\x1b[91m▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇\x1b[0m 30.00'
+
def test_stacked_graph_no_label_prints_no_labels(self):
with patch('sys.stdout', new=StringIO()) as output:
labels = ['2007', '2008', '2009', '2010', '2011', '2012', '2014']
|
Bad display with --stacked
The display in column doesn't work properly with the --stacked option.
```
Example1: ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 22.00
Longertext example : ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 36.00
```
I have to use `column -t -s ':'` to clean it up.
|
0.0
|
ca79e57b02f321a2f23c44677014e9e7013c0436
|
[
"tests/test_termgraph.py::TermgraphTest::test_stacked_graph_different_label_length_prints_correct_graph"
] |
[
"tests/test_termgraph.py::TermgraphTest::test_calendar_heatmap_color_prints_correctly",
"tests/test_termgraph.py::TermgraphTest::test_calendar_heatmap_custom_tick_prints_correctly",
"tests/test_termgraph.py::TermgraphTest::test_calendar_heatmap_prints_correct_heatmap",
"tests/test_termgraph.py::TermgraphTest::test_chart_multiple_series_different_scale_prints_correctly",
"tests/test_termgraph.py::TermgraphTest::test_chart_multiple_series_no_colors_prints_correctly",
"tests/test_termgraph.py::TermgraphTest::test_chart_multiple_series_prints_correctly",
"tests/test_termgraph.py::TermgraphTest::test_chart_prints_correct_chart",
"tests/test_termgraph.py::TermgraphTest::test_chart_stacked_prints_correctly",
"tests/test_termgraph.py::TermgraphTest::test_check_data_mismatching_color_and_category_count_exits_with_one",
"tests/test_termgraph.py::TermgraphTest::test_check_data_mismatching_data_and_labels_count_exits_with_one",
"tests/test_termgraph.py::TermgraphTest::test_check_data_missing_data_for_categories_count_exits_with_one",
"tests/test_termgraph.py::TermgraphTest::test_check_data_returns_correct_result",
"tests/test_termgraph.py::TermgraphTest::test_check_data_stacked_with_no_color_returns_correct_result",
"tests/test_termgraph.py::TermgraphTest::test_check_data_vertical_multiple_series_same_scale_exits_with_one",
"tests/test_termgraph.py::TermgraphTest::test_check_data_with_color_returns_correct_result",
"tests/test_termgraph.py::TermgraphTest::test_find_max_label_length_returns_correct_length",
"tests/test_termgraph.py::TermgraphTest::test_find_max_returns_highest_value",
"tests/test_termgraph.py::TermgraphTest::test_find_min_returns_lowest_value",
"tests/test_termgraph.py::TermgraphTest::test_horiz_rows_multiple_series_only_has_label_at_beginning",
"tests/test_termgraph.py::TermgraphTest::test_horiz_rows_no_labels_yields_no_labels",
"tests/test_termgraph.py::TermgraphTest::test_horiz_rows_yields_correct_values",
"tests/test_termgraph.py::TermgraphTest::test_main",
"tests/test_termgraph.py::TermgraphTest::test_normalize_returns_correct_results",
"tests/test_termgraph.py::TermgraphTest::test_normalize_with_larger_width_does_not_normalize",
"tests/test_termgraph.py::TermgraphTest::test_normalize_with_negative_datapoint_returns_correct_results",
"tests/test_termgraph.py::TermgraphTest::test_print_categories_prints_correct_categories",
"tests/test_termgraph.py::TermgraphTest::test_print_row_prints_correct_block_count",
"tests/test_termgraph.py::TermgraphTest::test_print_vertical",
"tests/test_termgraph.py::TermgraphTest::test_read_data_returns_correct_results",
"tests/test_termgraph.py::TermgraphTest::test_read_data_verbose",
"tests/test_termgraph.py::TermgraphTest::test_read_data_with_title_prints_title",
"tests/test_termgraph.py::TermgraphTest::test_stacked_graph_no_label_prints_no_labels",
"tests/test_termgraph.py::TermgraphTest::test_stacked_graph_prints_correct_graph",
"tests/test_termgraph.py::TermgraphTest::test_vertically_returns_correct_result"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-10-18 12:05:51+00:00
|
mit
| 3,998 |
|
mkaz__termgraph-87
|
diff --git a/termgraph/termgraph.py b/termgraph/termgraph.py
index bacc4c0..ee2c796 100755
--- a/termgraph/termgraph.py
+++ b/termgraph/termgraph.py
@@ -165,6 +165,9 @@ def normalize(data: List, width: int) -> List:
min_datum = find_min(data_offset)
max_datum = find_max(data_offset)
+ if min_datum == max_datum:
+ return data_offset
+
# max_dat / width is the value for a single tick. norm_factor is the
# inverse of this value
# If you divide a number to the value of single tick, you will find how
|
mkaz/termgraph
|
e8c211bcb0c4f403fe86c9290c24262fd5d334e7
|
diff --git a/tests/test_termgraph.py b/tests/test_termgraph.py
index 79d9a9a..bc3b8a8 100644
--- a/tests/test_termgraph.py
+++ b/tests/test_termgraph.py
@@ -47,6 +47,20 @@ def test_normalize_returns_correct_results():
assert results == expected
+def test_normalize_with_all_zeros_returns_correct_results():
+ expected = [
+ [0],
+ [0],
+ [0],
+ [0],
+ [0],
+ [0],
+ [0],
+ ]
+ results = tg.normalize([[0], [0], [0], [0], [0], [0], [0]], 50)
+ assert results == expected
+
+
def test_normalize_with_negative_datapoint_returns_correct_results():
expected = [
[18.625354066709058],
|
ZeroDivisionError on empty data
# Background
When passing in data containing all 0's termgraph will return a ZeroDivisionError. Ideally termgraph should accept this value and return an empty graph.
## Example Code
```
termgraph.chart(
colors=None,
data=[0, 0]
args={'width': 100, 'format': '{:,}', 'suffix': '', 'no_labels': False, 'no_values': False, 'vertical': False, 'stacked': False, 'histogram': False, 'different_scale': False},
labels=['iOS', 'Android']
)
```
## Error Message
```
ERROR: Problem running script: Traceback (most recent call last):
File "/../main.py", line 523, in <module>
cli_handler()
File "/.../lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/.../lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/.../lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/.../lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/../main.py", line 194, in cli_handler
main(
File "/.../main.py", line 449, in main
termgraph.chart(
File "/.../lib/python3.8/site-packages/termgraph/termgraph.py", line 485, in chart
normal_dat = normalize(data, args["width"])
File "/.../lib/python3.8/site-packages/termgraph/termgraph.py", line 162, in normalize
norm_factor = width / float(max_datum)
ZeroDivisionError: float division by zero
```
|
0.0
|
e8c211bcb0c4f403fe86c9290c24262fd5d334e7
|
[
"tests/test_termgraph.py::test_normalize_with_all_zeros_returns_correct_results"
] |
[
"tests/test_termgraph.py::test_find_min_returns_lowest_value",
"tests/test_termgraph.py::test_find_max_returns_highest_value",
"tests/test_termgraph.py::test_find_max_label_length_returns_correct_length",
"tests/test_termgraph.py::test_normalize_returns_correct_results",
"tests/test_termgraph.py::test_normalize_with_negative_datapoint_returns_correct_results",
"tests/test_termgraph.py::test_normalize_with_larger_width_does_not_normalize",
"tests/test_termgraph.py::test_horiz_rows_yields_correct_values",
"tests/test_termgraph.py::test_vertically_returns_correct_result",
"tests/test_termgraph.py::test_check_data_returns_correct_result",
"tests/test_termgraph.py::test_check_data_with_color_returns_correct_result",
"tests/test_termgraph.py::test_check_data_stacked_with_no_color_returns_correct_result",
"tests/test_termgraph.py::test_check_data_vertical_multiple_series_same_scale_exits_with_one",
"tests/test_termgraph.py::test_check_data_mismatching_color_and_category_count",
"tests/test_termgraph.py::test_check_data_mismatching_data_and_labels_count_exits_with_one",
"tests/test_termgraph.py::test_check_data_missing_data_for_categories_count_exits_with_one",
"tests/test_termgraph.py::test_read_data_returns_correct_results",
"tests/test_termgraph.py::test_read_data_with_title_prints_title",
"tests/test_termgraph.py::test_read_data_verbose"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-07-26 13:02:29+00:00
|
mit
| 3,999 |
|
mkdocs__mkdocs-1009
|
diff --git a/docs/about/release-notes.md b/docs/about/release-notes.md
index c8e491f8..426ef3c8 100644
--- a/docs/about/release-notes.md
+++ b/docs/about/release-notes.md
@@ -138,6 +138,8 @@ pages.
* Change "Edit on..." links to point directly to the file in the source
repository, rather than to the root of the repository (#975), configurable
via the new [`edit_uri`](../user-guide/configuration.md#edit_uri) setting.
+* Bugfix: Don't override config value for strict mode if not specified on CLI
+ (#738).
## Version 0.15.3 (2016-02-18)
diff --git a/mkdocs/__main__.py b/mkdocs/__main__.py
index 9417c3ad..c9d519fc 100644
--- a/mkdocs/__main__.py
+++ b/mkdocs/__main__.py
@@ -9,7 +9,7 @@ import socket
from mkdocs import __version__
from mkdocs import utils
from mkdocs import exceptions
-from mkdocs.config import load_config
+from mkdocs import config
from mkdocs.commands import build, gh_deploy, new, serve
log = logging.getLogger(__name__)
@@ -112,6 +112,10 @@ def serve_command(dev_addr, config_file, strict, theme, theme_dir, livereload):
logging.getLogger('tornado').setLevel(logging.WARNING)
+ # Don't override config value if user did not specify --strict flag
+ # Conveniently, load_config drops None values
+ strict = strict or None
+
try:
serve.serve(
config_file=config_file,
@@ -136,8 +140,13 @@ def serve_command(dev_addr, config_file, strict, theme, theme_dir, livereload):
@common_options
def build_command(clean, config_file, strict, theme, theme_dir, site_dir):
"""Build the MkDocs documentation"""
+
+ # Don't override config value if user did not specify --strict flag
+ # Conveniently, load_config drops None values
+ strict = strict or None
+
try:
- build.build(load_config(
+ build.build(config.load_config(
config_file=config_file,
strict=strict,
theme=theme,
@@ -168,8 +177,12 @@ def json_command(clean, config_file, strict, site_dir):
"future MkDocs release. For details on updating: "
"http://www.mkdocs.org/about/release-notes/")
+ # Don't override config value if user did not specify --strict flag
+ # Conveniently, load_config drops None values
+ strict = strict or None
+
try:
- build.build(load_config(
+ build.build(config.load_config(
config_file=config_file,
strict=strict,
site_dir=site_dir
@@ -189,13 +202,13 @@ def json_command(clean, config_file, strict, site_dir):
def gh_deploy_command(config_file, clean, message, remote_branch, remote_name):
"""Deploy your documentation to GitHub Pages"""
try:
- config = load_config(
+ cfg = config.load_config(
config_file=config_file,
remote_branch=remote_branch,
remote_name=remote_name
)
- build.build(config, dirty=not clean)
- gh_deploy.gh_deploy(config, message=message)
+ build.build(cfg, dirty=not clean)
+ gh_deploy.gh_deploy(cfg, message=message)
except exceptions.ConfigurationError as e:
# Avoid ugly, unhelpful traceback
raise SystemExit('\n' + str(e))
|
mkdocs/mkdocs
|
2e4c2afca10cfd697ba5ca820dd5212c4b1e9089
|
diff --git a/mkdocs/tests/cli_tests.py b/mkdocs/tests/cli_tests.py
index b070afee..a4da76e8 100644
--- a/mkdocs/tests/cli_tests.py
+++ b/mkdocs/tests/cli_tests.py
@@ -22,16 +22,31 @@ class CLITests(unittest.TestCase):
cli.cli, ["serve", ], catch_exceptions=False)
self.assertEqual(result.exit_code, 0)
- self.assertEqual(mock_serve.call_count, 1)
-
+ mock_serve.assert_called_once_with(
+ config_file=None,
+ dev_addr=None,
+ strict=None,
+ theme=None,
+ theme_dir=None,
+ livereload=None
+ )
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
@mock.patch('mkdocs.commands.build.build', autospec=True)
- def test_build(self, mock_build):
+ def test_build(self, mock_build, mock_load_config):
result = self.runner.invoke(
cli.cli, ["build", ], catch_exceptions=False)
self.assertEqual(result.exit_code, 0)
self.assertEqual(mock_build.call_count, 1)
+ mock_load_config.assert_called_once_with(
+ config_file=None,
+ strict=None,
+ theme=None,
+ theme_dir=None,
+ site_dir=None
+ )
@mock.patch('mkdocs.commands.build.build', autospec=True)
def test_build_verbose(self, mock_build):
|
Configuration strict option not checking broken links
I was testing mkdocs earlier this year and was using "strict: true" in my mkdocs.yml. If I recall correctly, it was working then and building would break if there was a broken link in the .md.
However I am now using v0.14.0 and this config option seems to have no effect on the build - I get no warnings or errors when building regardless of the value of strict.
|
0.0
|
2e4c2afca10cfd697ba5ca820dd5212c4b1e9089
|
[
"mkdocs/tests/cli_tests.py::CLITests::test_build",
"mkdocs/tests/cli_tests.py::CLITests::test_serve"
] |
[
"mkdocs/tests/cli_tests.py::CLITests::test_new"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-08-03 20:25:59+00:00
|
bsd-2-clause
| 4,000 |
|
mkdocs__mkdocs-1018
|
diff --git a/mkdocs/__main__.py b/mkdocs/__main__.py
index c9d519fc..016564b3 100644
--- a/mkdocs/__main__.py
+++ b/mkdocs/__main__.py
@@ -67,7 +67,7 @@ def common_options(f):
return f
-clean_help = "Remove old files from the site_dir before building"
+clean_help = "Remove old files from the site_dir before building (the default)."
config_help = "Provide a specific MkDocs config"
dev_addr_help = ("IP address and port to serve documentation locally (default: "
"localhost:8000)")
@@ -103,7 +103,7 @@ def cli():
@click.option('-s', '--strict', is_flag=True, help=strict_help)
@click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help)
@click.option('-e', '--theme-dir', type=click.Path(), help=theme_dir_help)
[email protected]('--livereload', 'livereload', flag_value='livereload', help=reload_help)
[email protected]('--livereload', 'livereload', flag_value='livereload', help=reload_help, default=True)
@click.option('--no-livereload', 'livereload', flag_value='no-livereload', help=no_reload_help)
@click.option('-d', '--dirtyreload', 'livereload', flag_value='dirty', help=dirty_reload_help)
@common_options
@@ -125,13 +125,13 @@ def serve_command(dev_addr, config_file, strict, theme, theme_dir, livereload):
theme_dir=theme_dir,
livereload=livereload
)
- except (exceptions.ConfigurationError, socket.error) as e:
+ except (exceptions.ConfigurationError, socket.error) as e: # pragma: no cover
# Avoid ugly, unhelpful traceback
raise SystemExit('\n' + str(e))
@cli.command(name="build")
[email protected]('-c', '--clean/--dirty', is_flag=True, help=clean_help)
[email protected]('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)
@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)
@click.option('-s', '--strict', is_flag=True, help=strict_help)
@click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help)
@@ -153,13 +153,13 @@ def build_command(clean, config_file, strict, theme, theme_dir, site_dir):
theme_dir=theme_dir,
site_dir=site_dir
), dirty=not clean)
- except exceptions.ConfigurationError as e:
+ except exceptions.ConfigurationError as e: # pragma: no cover
# Avoid ugly, unhelpful traceback
raise SystemExit('\n' + str(e))
@cli.command(name="json")
[email protected]('-c', '--clean', is_flag=True, help=clean_help)
[email protected]('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)
@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)
@click.option('-s', '--strict', is_flag=True, help=strict_help)
@click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help)
@@ -187,13 +187,13 @@ def json_command(clean, config_file, strict, site_dir):
strict=strict,
site_dir=site_dir
), dump_json=True, dirty=not clean)
- except exceptions.ConfigurationError as e:
+ except exceptions.ConfigurationError as e: # pragma: no cover
# Avoid ugly, unhelpful traceback
raise SystemExit('\n' + str(e))
@cli.command(name="gh-deploy")
[email protected]('-c', '--clean', is_flag=True, help=clean_help)
[email protected]('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help)
@click.option('-f', '--config-file', type=click.File('rb'), help=config_help)
@click.option('-m', '--message', help=commit_message_help)
@click.option('-b', '--remote-branch', help=remote_branch_help)
@@ -209,7 +209,7 @@ def gh_deploy_command(config_file, clean, message, remote_branch, remote_name):
)
build.build(cfg, dirty=not clean)
gh_deploy.gh_deploy(cfg, message=message)
- except exceptions.ConfigurationError as e:
+ except exceptions.ConfigurationError as e: # pragma: no cover
# Avoid ugly, unhelpful traceback
raise SystemExit('\n' + str(e))
@@ -221,5 +221,5 @@ def new_command(project_directory):
"""Create a new MkDocs project"""
new.new(project_directory)
-if __name__ == '__main__':
+if __name__ == '__main__': # pragma: no cover
cli()
|
mkdocs/mkdocs
|
63558bffe33ccb59d10b939641ed546e48c95144
|
diff --git a/mkdocs/tests/cli_tests.py b/mkdocs/tests/cli_tests.py
index a4da76e8..0014dc2a 100644
--- a/mkdocs/tests/cli_tests.py
+++ b/mkdocs/tests/cli_tests.py
@@ -4,11 +4,16 @@
from __future__ import unicode_literals
import unittest
import mock
+import logging
+import sys
+import io
from click.testing import CliRunner
from mkdocs import __main__ as cli
+PY3 = sys.version_info[0] == 3
+
class CLITests(unittest.TestCase):
@@ -16,10 +21,10 @@ class CLITests(unittest.TestCase):
self.runner = CliRunner()
@mock.patch('mkdocs.commands.serve.serve', autospec=True)
- def test_serve(self, mock_serve):
+ def test_serve_default(self, mock_serve):
result = self.runner.invoke(
- cli.cli, ["serve", ], catch_exceptions=False)
+ cli.cli, ["serve"], catch_exceptions=False)
self.assertEqual(result.exit_code, 0)
mock_serve.assert_called_once_with(
@@ -28,18 +33,149 @@ class CLITests(unittest.TestCase):
strict=None,
theme=None,
theme_dir=None,
- livereload=None
+ livereload='livereload'
+ )
+
+ @mock.patch('mkdocs.commands.serve.serve', autospec=True)
+ def test_serve_config_file(self, mock_serve):
+
+ result = self.runner.invoke(
+ cli.cli, ["serve", "--config-file", "mkdocs.yml"], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_serve.call_count, 1)
+ args, kwargs = mock_serve.call_args
+ self.assertTrue('config_file' in kwargs)
+ if PY3:
+ self.assertIsInstance(kwargs['config_file'], io.BufferedReader)
+ else:
+ self.assertTrue(isinstance(kwargs['config_file'], file))
+ self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml')
+
+ @mock.patch('mkdocs.commands.serve.serve', autospec=True)
+ def test_serve_dev_addr(self, mock_serve):
+
+ result = self.runner.invoke(
+ cli.cli, ["serve", '--dev-addr', '0.0.0.0:80'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ mock_serve.assert_called_once_with(
+ config_file=None,
+ dev_addr='0.0.0.0:80',
+ strict=None,
+ theme=None,
+ theme_dir=None,
+ livereload='livereload'
+ )
+
+ @mock.patch('mkdocs.commands.serve.serve', autospec=True)
+ def test_serve_strict(self, mock_serve):
+
+ result = self.runner.invoke(
+ cli.cli, ["serve", '--strict'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ mock_serve.assert_called_once_with(
+ config_file=None,
+ dev_addr=None,
+ strict=True,
+ theme=None,
+ theme_dir=None,
+ livereload='livereload'
+ )
+
+ @mock.patch('mkdocs.commands.serve.serve', autospec=True)
+ def test_serve_theme(self, mock_serve):
+
+ result = self.runner.invoke(
+ cli.cli, ["serve", '--theme', 'readthedocs'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ mock_serve.assert_called_once_with(
+ config_file=None,
+ dev_addr=None,
+ strict=None,
+ theme='readthedocs',
+ theme_dir=None,
+ livereload='livereload'
+ )
+
+ @mock.patch('mkdocs.commands.serve.serve', autospec=True)
+ def test_serve_theme_dir(self, mock_serve):
+
+ result = self.runner.invoke(
+ cli.cli, ["serve", '--theme-dir', 'custom'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ mock_serve.assert_called_once_with(
+ config_file=None,
+ dev_addr=None,
+ strict=None,
+ theme=None,
+ theme_dir='custom',
+ livereload='livereload'
+ )
+
+ @mock.patch('mkdocs.commands.serve.serve', autospec=True)
+ def test_serve_livereload(self, mock_serve):
+
+ result = self.runner.invoke(
+ cli.cli, ["serve", '--livereload'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ mock_serve.assert_called_once_with(
+ config_file=None,
+ dev_addr=None,
+ strict=None,
+ theme=None,
+ theme_dir=None,
+ livereload='livereload'
+ )
+
+ @mock.patch('mkdocs.commands.serve.serve', autospec=True)
+ def test_serve_no_livereload(self, mock_serve):
+
+ result = self.runner.invoke(
+ cli.cli, ["serve", '--no-livereload'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ mock_serve.assert_called_once_with(
+ config_file=None,
+ dev_addr=None,
+ strict=None,
+ theme=None,
+ theme_dir=None,
+ livereload='no-livereload'
+ )
+
+ @mock.patch('mkdocs.commands.serve.serve', autospec=True)
+ def test_serve_dirtyreload(self, mock_serve):
+
+ result = self.runner.invoke(
+ cli.cli, ["serve", '--dirtyreload'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ mock_serve.assert_called_once_with(
+ config_file=None,
+ dev_addr=None,
+ strict=None,
+ theme=None,
+ theme_dir=None,
+ livereload='dirty'
)
@mock.patch('mkdocs.config.load_config', autospec=True)
@mock.patch('mkdocs.commands.build.build', autospec=True)
- def test_build(self, mock_build, mock_load_config):
+ def test_build_defaults(self, mock_build, mock_load_config):
result = self.runner.invoke(
- cli.cli, ["build", ], catch_exceptions=False)
+ cli.cli, ['build'], catch_exceptions=False)
self.assertEqual(result.exit_code, 0)
self.assertEqual(mock_build.call_count, 1)
+ args, kwargs = mock_build.call_args
+ self.assertTrue('dirty' in kwargs)
+ self.assertFalse(kwargs['dirty'])
mock_load_config.assert_called_once_with(
config_file=None,
strict=None,
@@ -47,15 +183,140 @@ class CLITests(unittest.TestCase):
theme_dir=None,
site_dir=None
)
+ logger = logging.getLogger('mkdocs')
+ self.assertEqual(logger.level, logging.INFO)
+
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ def test_build_clean(self, mock_build):
+
+ result = self.runner.invoke(
+ cli.cli, ['build', '--clean'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_build.call_count, 1)
+ args, kwargs = mock_build.call_args
+ self.assertTrue('dirty' in kwargs)
+ self.assertFalse(kwargs['dirty'])
+
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ def test_build_dirty(self, mock_build):
+
+ result = self.runner.invoke(
+ cli.cli, ['build', '--dirty'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_build.call_count, 1)
+ args, kwargs = mock_build.call_args
+ self.assertTrue('dirty' in kwargs)
+ self.assertTrue(kwargs['dirty'])
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ def test_build_config_file(self, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['build', '--config-file', 'mkdocs.yml'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_build.call_count, 1)
+ self.assertEqual(mock_load_config.call_count, 1)
+ args, kwargs = mock_load_config.call_args
+ self.assertTrue('config_file' in kwargs)
+ if PY3:
+ self.assertIsInstance(kwargs['config_file'], io.BufferedReader)
+ else:
+ self.assertTrue(isinstance(kwargs['config_file'], file))
+ self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml')
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ def test_build_strict(self, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['build', '--strict'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_build.call_count, 1)
+ mock_load_config.assert_called_once_with(
+ config_file=None,
+ strict=True,
+ theme=None,
+ theme_dir=None,
+ site_dir=None
+ )
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ def test_build_theme(self, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['build', '--theme', 'readthedocs'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_build.call_count, 1)
+ mock_load_config.assert_called_once_with(
+ config_file=None,
+ strict=None,
+ theme='readthedocs',
+ theme_dir=None,
+ site_dir=None
+ )
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ def test_build_theme_dir(self, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['build', '--theme-dir', 'custom'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_build.call_count, 1)
+ mock_load_config.assert_called_once_with(
+ config_file=None,
+ strict=None,
+ theme=None,
+ theme_dir='custom',
+ site_dir=None
+ )
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ def test_build_site_dir(self, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['build', '--site-dir', 'custom'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_build.call_count, 1)
+ mock_load_config.assert_called_once_with(
+ config_file=None,
+ strict=None,
+ theme=None,
+ theme_dir=None,
+ site_dir='custom'
+ )
@mock.patch('mkdocs.commands.build.build', autospec=True)
def test_build_verbose(self, mock_build):
result = self.runner.invoke(
- cli.cli, ["--verbose", "build"], catch_exceptions=False)
+ cli.cli, ['build', '--verbose'], catch_exceptions=False)
self.assertEqual(result.exit_code, 0)
self.assertEqual(mock_build.call_count, 1)
+ logger = logging.getLogger('mkdocs')
+ self.assertEqual(logger.level, logging.DEBUG)
+
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ def test_build_quiet(self, mock_build):
+
+ result = self.runner.invoke(
+ cli.cli, ['build', '--quiet'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_build.call_count, 1)
+ logger = logging.getLogger('mkdocs')
+ self.assertEqual(logger.level, logging.ERROR)
@mock.patch('mkdocs.commands.build.build', autospec=True)
def test_json(self, mock_build):
@@ -73,13 +334,125 @@ class CLITests(unittest.TestCase):
cli.cli, ["new", "project"], catch_exceptions=False)
self.assertEqual(result.exit_code, 0)
- self.assertEqual(mock_new.call_count, 1)
+ mock_new.assert_called_once_with('project')
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True)
+ def test_gh_deploy_defaults(self, mock_gh_deploy, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['gh-deploy'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_gh_deploy.call_count, 1)
+ g_args, g_kwargs = mock_gh_deploy.call_args
+ self.assertTrue('message' in g_kwargs)
+ self.assertEqual(g_kwargs['message'], None)
+ self.assertEqual(mock_build.call_count, 1)
+ b_args, b_kwargs = mock_build.call_args
+ self.assertTrue('dirty' in b_kwargs)
+ self.assertFalse(b_kwargs['dirty'])
+ mock_load_config.assert_called_once_with(
+ config_file=None,
+ remote_branch=None,
+ remote_name=None
+ )
+
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True)
+ def test_gh_deploy_clean(self, mock_gh_deploy, mock_build):
+
+ result = self.runner.invoke(
+ cli.cli, ['gh-deploy', '--clean'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_gh_deploy.call_count, 1)
+ self.assertEqual(mock_build.call_count, 1)
+ args, kwargs = mock_build.call_args
+ self.assertTrue('dirty' in kwargs)
+ self.assertFalse(kwargs['dirty'])
+
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True)
+ def test_gh_deploy_dirty(self, mock_gh_deploy, mock_build):
+
+ result = self.runner.invoke(
+ cli.cli, ['gh-deploy', '--dirty'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_gh_deploy.call_count, 1)
+ self.assertEqual(mock_build.call_count, 1)
+ args, kwargs = mock_build.call_args
+ self.assertTrue('dirty' in kwargs)
+ self.assertTrue(kwargs['dirty'])
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True)
+ def test_gh_deploy_config_file(self, mock_gh_deploy, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['gh-deploy', '--config-file', 'mkdocs.yml'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_gh_deploy.call_count, 1)
+ self.assertEqual(mock_build.call_count, 1)
+ self.assertEqual(mock_load_config.call_count, 1)
+ args, kwargs = mock_load_config.call_args
+ self.assertTrue('config_file' in kwargs)
+ if PY3:
+ self.assertIsInstance(kwargs['config_file'], io.BufferedReader)
+ else:
+ self.assertTrue(isinstance(kwargs['config_file'], file))
+ self.assertEqual(kwargs['config_file'].name, 'mkdocs.yml')
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True)
+ def test_gh_deploy_message(self, mock_gh_deploy, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['gh-deploy', '--message', 'A commit message'], catch_exceptions=False)
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_gh_deploy.call_count, 1)
+ g_args, g_kwargs = mock_gh_deploy.call_args
+ self.assertTrue('message' in g_kwargs)
+ self.assertEqual(g_kwargs['message'], 'A commit message')
+ self.assertEqual(mock_build.call_count, 1)
+ self.assertEqual(mock_load_config.call_count, 1)
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
@mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True)
- def test_gh_deploy(self, mock_gh_deploy):
+ def test_gh_deploy_remote_branch(self, mock_gh_deploy, mock_build, mock_load_config):
result = self.runner.invoke(
- cli.cli, ["gh-deploy"], catch_exceptions=False)
+ cli.cli, ['gh-deploy', '--remote-branch', 'foo'], catch_exceptions=False)
self.assertEqual(result.exit_code, 0)
self.assertEqual(mock_gh_deploy.call_count, 1)
+ self.assertEqual(mock_build.call_count, 1)
+ mock_load_config.assert_called_once_with(
+ config_file=None,
+ remote_branch='foo',
+ remote_name=None
+ )
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True)
+ def test_gh_deploy_remote_name(self, mock_gh_deploy, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['gh-deploy', '--remote-name', 'foo'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_gh_deploy.call_count, 1)
+ self.assertEqual(mock_build.call_count, 1)
+ mock_load_config.assert_called_once_with(
+ config_file=None,
+ remote_branch=None,
+ remote_name='foo'
+ )
|
Improve CLI tests.
The CLI tests use Mock objects (as they should), but all they do is confirm that the proper function was called once. There is no testing of the CLI options and what values are passed in (either the default values or custom values defined by the user). For example, when working on #997, both @aeslaughter and I missed that the default server was changed (see #1014). Also while working on #1009, I noticed that perhaps the default for `--clean` may not be what we think it is (we intended to change the default in #997, but I'm not sure we did).
We need tests for all the different options for each command to ensure the values passed from the CLI match expectations/documentation. Basically, we need more tests like the one I added in #1009.
|
0.0
|
63558bffe33ccb59d10b939641ed546e48c95144
|
[
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_defaults",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_dev_addr",
"mkdocs/tests/cli_tests.py::CLITests::test_build_defaults",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_strict",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_theme",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_theme_dir",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_default"
] |
[
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_remote_branch",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_livereload",
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_message",
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_remote_name",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_dirtyreload",
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_config_file",
"mkdocs/tests/cli_tests.py::CLITests::test_build_theme_dir",
"mkdocs/tests/cli_tests.py::CLITests::test_build_config_file",
"mkdocs/tests/cli_tests.py::CLITests::test_build_theme",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_config_file",
"mkdocs/tests/cli_tests.py::CLITests::test_build_site_dir",
"mkdocs/tests/cli_tests.py::CLITests::test_new",
"mkdocs/tests/cli_tests.py::CLITests::test_build_strict",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_no_livereload"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-08-08 02:49:00+00:00
|
bsd-2-clause
| 4,001 |
|
mkdocs__mkdocs-1023
|
diff --git a/docs/about/release-notes.md b/docs/about/release-notes.md
index fdb21e46..e52abf87 100644
--- a/docs/about/release-notes.md
+++ b/docs/about/release-notes.md
@@ -164,6 +164,8 @@ better conform with the documented [layout].
via the new [`edit_uri`](../user-guide/configuration.md#edit_uri) setting.
* Bugfix: Don't override config value for strict mode if not specified on CLI
(#738).
+* Add a `--force` flag to the `gh-deploy` command to force the push to the
+ repository (#973).
## Version 0.15.3 (2016-02-18)
diff --git a/mkdocs/__main__.py b/mkdocs/__main__.py
index 016564b3..de26cde9 100644
--- a/mkdocs/__main__.py
+++ b/mkdocs/__main__.py
@@ -86,6 +86,7 @@ remote_branch_help = ("The remote branch to commit to for Github Pages. This "
"overrides the value specified in config")
remote_name_help = ("The remote name to commit to for Github Pages. This "
"overrides the value specified in config")
+force_help = "Force the push to the repository."
@click.group(context_settings={'help_option_names': ['-h', '--help']})
@@ -198,8 +199,9 @@ def json_command(clean, config_file, strict, site_dir):
@click.option('-m', '--message', help=commit_message_help)
@click.option('-b', '--remote-branch', help=remote_branch_help)
@click.option('-r', '--remote-name', help=remote_name_help)
[email protected]('--force', is_flag=True, help=force_help)
@common_options
-def gh_deploy_command(config_file, clean, message, remote_branch, remote_name):
+def gh_deploy_command(config_file, clean, message, remote_branch, remote_name, force):
"""Deploy your documentation to GitHub Pages"""
try:
cfg = config.load_config(
@@ -208,7 +210,7 @@ def gh_deploy_command(config_file, clean, message, remote_branch, remote_name):
remote_name=remote_name
)
build.build(cfg, dirty=not clean)
- gh_deploy.gh_deploy(cfg, message=message)
+ gh_deploy.gh_deploy(cfg, message=message, force=force)
except exceptions.ConfigurationError as e: # pragma: no cover
# Avoid ugly, unhelpful traceback
raise SystemExit('\n' + str(e))
diff --git a/mkdocs/commands/gh_deploy.py b/mkdocs/commands/gh_deploy.py
index 9a240006..0f504c7a 100644
--- a/mkdocs/commands/gh_deploy.py
+++ b/mkdocs/commands/gh_deploy.py
@@ -49,7 +49,7 @@ def _get_remote_url(remote_name):
return host, path
-def gh_deploy(config, message=None):
+def gh_deploy(config, message=None, force=False):
if not _is_cwd_git_repo():
log.error('Cannot deploy - this directory does not appear to be a git '
@@ -66,7 +66,7 @@ def gh_deploy(config, message=None):
config['site_dir'], config['remote_branch'])
result, error = ghp_import.ghp_import(config['site_dir'], message, remote_name,
- remote_branch)
+ remote_branch, force)
if not result:
log.error("Failed to deploy to GitHub with error: \n%s", error)
raise SystemExit(1)
diff --git a/mkdocs/utils/ghp_import.py b/mkdocs/utils/ghp_import.py
index 5339b216..62ef8c5c 100644
--- a/mkdocs/utils/ghp_import.py
+++ b/mkdocs/utils/ghp_import.py
@@ -158,7 +158,7 @@ def run_import(srcdir, branch, message, nojekyll):
sys.stdout.write(enc("Failed to process commit.\n"))
-def ghp_import(directory, message, remote='origin', branch='gh-pages'):
+def ghp_import(directory, message, remote='origin', branch='gh-pages', force=False):
if not try_rebase(remote, branch):
log.error("Failed to rebase %s branch.", branch)
@@ -167,8 +167,12 @@ def ghp_import(directory, message, remote='origin', branch='gh-pages'):
run_import(directory, branch, message, nojekyll)
- proc = sp.Popen(['git', 'push', remote, branch],
- stdout=sp.PIPE, stderr=sp.PIPE)
+ cmd = ['git', 'push', remote, branch]
+
+ if force:
+ cmd.insert(2, '--force')
+
+ proc = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
out, err = proc.communicate()
result = proc.wait() == 0
|
mkdocs/mkdocs
|
582523bcd362cc689d5a229c304055fcb3c65a69
|
diff --git a/mkdocs/tests/cli_tests.py b/mkdocs/tests/cli_tests.py
index 0014dc2a..56b01e20 100644
--- a/mkdocs/tests/cli_tests.py
+++ b/mkdocs/tests/cli_tests.py
@@ -349,6 +349,8 @@ class CLITests(unittest.TestCase):
g_args, g_kwargs = mock_gh_deploy.call_args
self.assertTrue('message' in g_kwargs)
self.assertEqual(g_kwargs['message'], None)
+ self.assertTrue('force' in g_kwargs)
+ self.assertEqual(g_kwargs['force'], False)
self.assertEqual(mock_build.call_count, 1)
b_args, b_kwargs = mock_build.call_args
self.assertTrue('dirty' in b_kwargs)
@@ -456,3 +458,19 @@ class CLITests(unittest.TestCase):
remote_branch=None,
remote_name='foo'
)
+
+ @mock.patch('mkdocs.config.load_config', autospec=True)
+ @mock.patch('mkdocs.commands.build.build', autospec=True)
+ @mock.patch('mkdocs.commands.gh_deploy.gh_deploy', autospec=True)
+ def test_gh_deploy_force(self, mock_gh_deploy, mock_build, mock_load_config):
+
+ result = self.runner.invoke(
+ cli.cli, ['gh-deploy', '--force'], catch_exceptions=False)
+
+ self.assertEqual(result.exit_code, 0)
+ self.assertEqual(mock_gh_deploy.call_count, 1)
+ g_args, g_kwargs = mock_gh_deploy.call_args
+ self.assertTrue('force' in g_kwargs)
+ self.assertEqual(g_kwargs['force'], True)
+ self.assertEqual(mock_build.call_count, 1)
+ self.assertEqual(mock_load_config.call_count, 1)
|
Sometimes deploy to gh-pages fails
Encountered while fixing #966. Originally added `--force` in #967, but it makes more sense to do some more research on the root cause.
Possibly:
- GH token permissions
- Same GH token used on multiple machines(?)
- Some git call is failing silently
Will investigate repro steps and update here.
|
0.0
|
582523bcd362cc689d5a229c304055fcb3c65a69
|
[
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_defaults",
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_force"
] |
[
"mkdocs/tests/cli_tests.py::CLITests::test_serve_theme_dir",
"mkdocs/tests/cli_tests.py::CLITests::test_new",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_livereload",
"mkdocs/tests/cli_tests.py::CLITests::test_build_strict",
"mkdocs/tests/cli_tests.py::CLITests::test_build_theme",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_theme",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_strict",
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_config_file",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_no_livereload",
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_remote_branch",
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_remote_name",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_default",
"mkdocs/tests/cli_tests.py::CLITests::test_build_defaults",
"mkdocs/tests/cli_tests.py::CLITests::test_gh_deploy_message",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_config_file",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_dirtyreload",
"mkdocs/tests/cli_tests.py::CLITests::test_build_site_dir",
"mkdocs/tests/cli_tests.py::CLITests::test_serve_dev_addr",
"mkdocs/tests/cli_tests.py::CLITests::test_build_theme_dir",
"mkdocs/tests/cli_tests.py::CLITests::test_build_config_file"
] |
{
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2016-08-11 14:22:36+00:00
|
bsd-2-clause
| 4,002 |
|
mkdocs__mkdocs-2290
|
diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py
index 5e654295..aea40dd0 100644
--- a/mkdocs/config/config_options.py
+++ b/mkdocs/config/config_options.py
@@ -623,7 +623,6 @@ class MarkdownExtensions(OptionallyRequired):
super().__init__(**kwargs)
self.builtins = builtins or []
self.configkey = configkey
- self.configdata = {}
def validate_ext_cfg(self, ext, cfg):
if not isinstance(ext, str):
@@ -635,6 +634,7 @@ class MarkdownExtensions(OptionallyRequired):
self.configdata[ext] = cfg
def run_validation(self, value):
+ self.configdata = {}
if not isinstance(value, (list, tuple, dict)):
raise ValidationError('Invalid Markdown Extensions configuration')
extensions = []
|
mkdocs/mkdocs
|
d6bfb1bc6f63d122556865aeee4ded17c536cb03
|
diff --git a/mkdocs/tests/config/config_tests.py b/mkdocs/tests/config/config_tests.py
index fe24fd3a..eceef26e 100644
--- a/mkdocs/tests/config/config_tests.py
+++ b/mkdocs/tests/config/config_tests.py
@@ -283,18 +283,24 @@ class ConfigTests(unittest.TestCase):
self.assertEqual(len(errors), 1)
self.assertEqual(warnings, [])
- def testConfigInstancesUnique(self):
- conf = mkdocs.config.Config(mkdocs.config.defaults.get_schema())
- conf.load_dict({'site_name': 'foo'})
- conf.validate()
- self.assertIsNone(conf['mdx_configs'].get('toc'))
+ def test_multiple_markdown_config_instances(self):
+ # This had a bug where an extension config would persist to separate
+ # config instances that didn't specify extensions.
+ schema = config.defaults.get_schema()
- conf = mkdocs.config.Config(mkdocs.config.defaults.get_schema())
- conf.load_dict({'site_name': 'foo', 'markdown_extensions': [{"toc": {"permalink": "aaa"}}]})
+ conf = config.Config(schema=schema)
+ conf.load_dict(
+ {
+ 'site_name': 'Example',
+ 'markdown_extensions': [{'toc': {'permalink': '##'}}],
+ }
+ )
conf.validate()
- self.assertEqual(conf['mdx_configs'].get('toc'), {'permalink': 'aaa'})
+ self.assertEqual(conf['mdx_configs'].get('toc'), {'permalink': '##'})
- conf = mkdocs.config.Config(mkdocs.config.defaults.get_schema())
- conf.load_dict({'site_name': 'foo'})
+ conf = config.Config(schema=schema)
+ conf.load_dict(
+ {'site_name': 'Example'},
+ )
conf.validate()
self.assertIsNone(conf['mdx_configs'].get('toc'))
|
Config.validate keeps 'mdx_configs' values across different instances
```python
import mkdocs.config
# 1. OK
conf = mkdocs.config.Config(mkdocs.config.DEFAULT_SCHEMA)
conf.load_dict({'site_name': 'foo'})
conf.validate()
assert conf['mdx_configs'].get('toc') == None
# 2. OK
conf = mkdocs.config.Config(mkdocs.config.DEFAULT_SCHEMA)
conf.load_dict({'site_name': 'foo', 'markdown_extensions': [{"toc": {"permalink": "aaa"}}]})
conf.validate()
assert conf['mdx_configs'].get('toc') == {'permalink': 'aaa'}
# 3. Identical to 1 but not OK.
conf = mkdocs.config.Config(mkdocs.config.DEFAULT_SCHEMA)
conf.load_dict({'site_name': 'foo'})
conf.validate()
assert conf['mdx_configs'].get('toc') == None
# fails, actually is {'permalink': 'aaa'}
```
|
0.0
|
d6bfb1bc6f63d122556865aeee4ded17c536cb03
|
[
"mkdocs/tests/config/config_tests.py::ConfigTests::test_multiple_markdown_config_instances"
] |
[
"mkdocs/tests/config/config_tests.py::ConfigTests::test_config_option",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_doc_dir_in_site_dir",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_empty_config",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_empty_nav",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_error_on_pages",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_invalid_config",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_missing_config_file",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_missing_site_name",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_nonexistant_config",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_theme"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-01-19 23:04:35+00:00
|
bsd-2-clause
| 4,003 |
|
mkdocs__mkdocs-2507
|
diff --git a/mkdocs/livereload/__init__.py b/mkdocs/livereload/__init__.py
index 83803e0a..c9f7afa8 100644
--- a/mkdocs/livereload/__init__.py
+++ b/mkdocs/livereload/__init__.py
@@ -183,10 +183,10 @@ class LiveReloadServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGISe
if path == "/js/livereload.js":
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "livereload.js")
elif path.startswith(self.mount_path):
+ rel_file_path = path[len(self.mount_path):].lstrip("/")
if path.endswith("/"):
- path += "index.html"
- path = path[len(self.mount_path):]
- file_path = os.path.join(self.root, path.lstrip("/"))
+ rel_file_path += "index.html"
+ file_path = os.path.join(self.root, rel_file_path)
elif path == "/":
start_response("302 Found", [("Location", self.mount_path)])
return []
@@ -201,9 +201,12 @@ class LiveReloadServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGISe
try:
file = open(file_path, "rb")
except OSError:
+ if not path.endswith("/") and os.path.isfile(os.path.join(file_path, "index.html")):
+ start_response("302 Found", [("Location", path + "/")])
+ return []
return None # Not found
- if path.endswith(".html"):
+ if file_path.endswith(".html"):
with file:
content = file.read()
content = self._inject_js_into_html(content, epoch)
|
mkdocs/mkdocs
|
e0ba6d7bd970123e73f70f06ef76ed48e8e56a27
|
diff --git a/mkdocs/tests/livereload_tests.py b/mkdocs/tests/livereload_tests.py
index cafa21dc..6ec81fda 100644
--- a/mkdocs/tests/livereload_tests.py
+++ b/mkdocs/tests/livereload_tests.py
@@ -293,7 +293,7 @@ class BuildTests(unittest.TestCase):
self.assertRegex(output, fr"^<body>foo</body><body>bar{SCRIPT_REGEX}</body>$")
@tempdir({"index.html": "<body>aaa</body>", "foo/index.html": "<body>bbb</body>"})
- def test_serves_modified_index(self, site_dir):
+ def test_serves_directory_index(self, site_dir):
with testing_server(site_dir) as server:
headers, output = do_request(server, "GET /")
self.assertRegex(output, fr"^<body>aaa{SCRIPT_REGEX}</body>$")
@@ -301,8 +301,21 @@ class BuildTests(unittest.TestCase):
self.assertEqual(headers.get("content-type"), "text/html")
self.assertEqual(headers.get("content-length"), str(len(output)))
- _, output = do_request(server, "GET /foo/")
- self.assertRegex(output, fr"^<body>bbb{SCRIPT_REGEX}</body>$")
+ for path in "/foo/", "/foo/index.html":
+ _, output = do_request(server, "GET /foo/")
+ self.assertRegex(output, fr"^<body>bbb{SCRIPT_REGEX}</body>$")
+
+ with self.assertLogs("mkdocs.livereload"):
+ headers, _ = do_request(server, "GET /foo/index.html/")
+ self.assertEqual(headers["_status"], "404 Not Found")
+
+ @tempdir({"foo/bar/index.html": "<body>aaa</body>"})
+ def test_redirects_to_directory(self, site_dir):
+ with testing_server(site_dir, mount_path="/sub") as server:
+ with self.assertLogs("mkdocs.livereload"):
+ headers, _ = do_request(server, "GET /sub/foo/bar")
+ self.assertEqual(headers["_status"], "302 Found")
+ self.assertEqual(headers.get("location"), "/sub/foo/bar/")
@tempdir({"я.html": "<body>aaa</body>", "测试2/index.html": "<body>bbb</body>"})
def test_serves_with_unicode_characters(self, site_dir):
|
V.1.2: Markdown links earlier processed as html files, are now processed as directories
The new version brings a curious issue. With versions < 1.2, I used internal links in this way, to make a call to page `bar.md`, from page `foo.md`:
```markdown
[linking to content in bar](../bar#content)
```
Which was transformed correctly into:
```html
<a href="../bar/#content">linking to content in bar</a>
```
Since version 1.2, the `bar` is intepreted differently by `mkdocs serve`, which breaks all such links. I realize this is highly irregular and correct call should have been:
```markdown
[linking to content in bar](bar.md#content)
```
So please dont throw rotten tomatoes at me 🍅 .
But just to help me fix this: why this change of behavior? Has some part been reimplemented? Or has this been intentional, to prevent that kind of error in the future?
|
0.0
|
e0ba6d7bd970123e73f70f06ef76ed48e8e56a27
|
[
"mkdocs/tests/livereload_tests.py::BuildTests::test_redirects_to_directory"
] |
[
"mkdocs/tests/livereload_tests.py::BuildTests::test_bad_error_handler",
"mkdocs/tests/livereload_tests.py::BuildTests::test_basic_rebuild",
"mkdocs/tests/livereload_tests.py::BuildTests::test_change_is_detected_while_building",
"mkdocs/tests/livereload_tests.py::BuildTests::test_custom_action_warns",
"mkdocs/tests/livereload_tests.py::BuildTests::test_error_handler",
"mkdocs/tests/livereload_tests.py::BuildTests::test_mime_types",
"mkdocs/tests/livereload_tests.py::BuildTests::test_multiple_dirs_can_cause_rebuild",
"mkdocs/tests/livereload_tests.py::BuildTests::test_multiple_dirs_changes_rebuild_only_once",
"mkdocs/tests/livereload_tests.py::BuildTests::test_rebuild_after_delete",
"mkdocs/tests/livereload_tests.py::BuildTests::test_rebuild_after_rename",
"mkdocs/tests/livereload_tests.py::BuildTests::test_rebuild_on_edit",
"mkdocs/tests/livereload_tests.py::BuildTests::test_redirects_to_mount_path",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_directory_index",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_from_mount_path",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_js",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_modified_html",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_normal_file",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_polling_after_event",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_polling_instantly",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_polling_with_timeout",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_with_unicode_characters",
"mkdocs/tests/livereload_tests.py::BuildTests::test_watches_direct_symlinks",
"mkdocs/tests/livereload_tests.py::BuildTests::test_watches_through_relative_symlinks",
"mkdocs/tests/livereload_tests.py::BuildTests::test_watches_through_symlinks"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-07-17 13:40:49+00:00
|
bsd-2-clause
| 4,004 |
|
mkdocs__mkdocs-2740
|
diff --git a/mkdocs/livereload/__init__.py b/mkdocs/livereload/__init__.py
index deef55ba..37f4acc7 100644
--- a/mkdocs/livereload/__init__.py
+++ b/mkdocs/livereload/__init__.py
@@ -8,6 +8,7 @@ import pathlib
import posixpath
import re
import socketserver
+import string
import threading
import time
import warnings
@@ -16,6 +17,30 @@ import wsgiref.simple_server
import watchdog.events
import watchdog.observers.polling
+_SCRIPT_TEMPLATE = """
+var livereload = function(epoch, requestId) {
+ var req = new XMLHttpRequest();
+ req.onloadend = function() {
+ if (parseFloat(this.responseText) > epoch) {
+ location.reload();
+ return;
+ }
+ var launchNext = livereload.bind(this, epoch, requestId);
+ if (this.status === 200) {
+ launchNext();
+ } else {
+ setTimeout(launchNext, 3000);
+ }
+ };
+ req.open("GET", "${mount_path}livereload/" + epoch + "/" + requestId);
+ req.send();
+
+ console.log('Enabled live reload');
+}
+livereload(${epoch}, ${request_id});
+"""
+_SCRIPT_TEMPLATE = string.Template(_SCRIPT_TEMPLATE)
+
class _LoggerAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
@@ -176,26 +201,25 @@ class LiveReloadServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGISe
# https://github.com/bottlepy/bottle/blob/f9b1849db4/bottle.py#L984
path = environ["PATH_INFO"].encode("latin-1").decode("utf-8", "ignore")
- m = re.fullmatch(r"/livereload/([0-9]+)/[0-9]+", path)
- if m:
- epoch = int(m[1])
- start_response("200 OK", [("Content-Type", "text/plain")])
+ if path.startswith(self.mount_path):
+ rel_file_path = path[len(self.mount_path):]
- def condition():
- return self._visible_epoch > epoch
+ m = re.fullmatch(r"livereload/([0-9]+)/[0-9]+", rel_file_path)
+ if m:
+ epoch = int(m[1])
+ start_response("200 OK", [("Content-Type", "text/plain")])
+
+ def condition():
+ return self._visible_epoch > epoch
+
+ with self._epoch_cond:
+ if not condition():
+ # Stall the browser, respond as soon as there's something new.
+ # If there's not, respond anyway after a minute.
+ self._log_poll_request(environ.get("HTTP_REFERER"), request_id=path)
+ self._epoch_cond.wait_for(condition, timeout=self.poll_response_timeout)
+ return [b"%d" % self._visible_epoch]
- with self._epoch_cond:
- if not condition():
- # Stall the browser, respond as soon as there's something new.
- # If there's not, respond anyway after a minute.
- self._log_poll_request(environ.get("HTTP_REFERER"), request_id=path)
- self._epoch_cond.wait_for(condition, timeout=self.poll_response_timeout)
- return [b"%d" % self._visible_epoch]
-
- if path == "/js/livereload.js":
- file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "livereload.js")
- elif path.startswith(self.mount_path):
- rel_file_path = path[len(self.mount_path):]
if path.endswith("/"):
rel_file_path += "index.html"
# Prevent directory traversal - normalize the path.
@@ -235,17 +259,20 @@ class LiveReloadServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGISe
)
return wsgiref.util.FileWrapper(file)
- @classmethod
- def _inject_js_into_html(cls, content, epoch):
+ def _inject_js_into_html(self, content, epoch):
try:
body_end = content.rindex(b"</body>")
except ValueError:
body_end = len(content)
# The page will reload if the livereload poller returns a newer epoch than what it knows.
# The other timestamp becomes just a unique identifier for the initiating page.
- return (
- b'%b<script src="/js/livereload.js"></script><script>livereload(%d, %d);</script>%b'
- % (content[:body_end], epoch, _timestamp(), content[body_end:])
+ script = _SCRIPT_TEMPLATE.substitute(
+ mount_path=self.mount_path, epoch=epoch, request_id=_timestamp()
+ )
+ return b"%b<script>%b</script>%b" % (
+ content[:body_end],
+ script.encode(),
+ content[body_end:],
)
@classmethod
diff --git a/mkdocs/livereload/livereload.js b/mkdocs/livereload/livereload.js
deleted file mode 100644
index a0f74365..00000000
--- a/mkdocs/livereload/livereload.js
+++ /dev/null
@@ -1,19 +0,0 @@
-function livereload(epoch, requestId) {
- var req = new XMLHttpRequest();
- req.onloadend = function() {
- if (parseFloat(this.responseText) > epoch) {
- location.reload();
- return;
- }
- var launchNext = livereload.bind(this, epoch, requestId);
- if (this.status === 200) {
- launchNext();
- } else {
- setTimeout(launchNext, 3000);
- }
- };
- req.open("GET", "/livereload/" + epoch + "/" + requestId);
- req.send();
-
- console.log('Enabled live reload');
-}
|
mkdocs/mkdocs
|
dc35569ade5e101c8c48b78bbed8708dd0b1b49a
|
diff --git a/mkdocs/tests/livereload_tests.py b/mkdocs/tests/livereload_tests.py
index 6ec81fda..7fca958d 100644
--- a/mkdocs/tests/livereload_tests.py
+++ b/mkdocs/tests/livereload_tests.py
@@ -65,7 +65,7 @@ def do_request(server, content):
SCRIPT_REGEX = (
- r'<script src="/js/livereload.js"></script><script>livereload\([0-9]+, [0-9]+\);</script>'
+ r'<script>[\S\s]+?livereload\([0-9]+, [0-9]+\);\s*</script>'
)
@@ -334,23 +334,18 @@ class BuildTests(unittest.TestCase):
_, output = do_request(server, "GET /%E6%B5%8B%E8%AF%952/index.html")
self.assertRegex(output, fr"^<body>bbb{SCRIPT_REGEX}</body>$")
- @tempdir()
- def test_serves_js(self, site_dir):
- with testing_server(site_dir) as server:
- for mount_path in "/", "/sub/":
- server.mount_path = mount_path
-
- headers, output = do_request(server, "GET /js/livereload.js")
- self.assertIn("function livereload", output)
- self.assertEqual(headers["_status"], "200 OK")
- self.assertEqual(headers.get("content-type"), "application/javascript")
-
@tempdir()
def test_serves_polling_instantly(self, site_dir):
with testing_server(site_dir) as server:
_, output = do_request(server, "GET /livereload/0/0")
self.assertTrue(output.isdigit())
+ @tempdir()
+ def test_serves_polling_from_mount_path(self, site_dir):
+ with testing_server(site_dir, mount_path="/test/f*o") as server:
+ _, output = do_request(server, "GET /test/f*o/livereload/0/0")
+ self.assertTrue(output.isdigit())
+
@tempdir()
@tempdir()
def test_serves_polling_after_event(self, site_dir, docs_dir):
|
Custom subpath isn't applied for `livereload` feature
If using a `site_url` including a subpath for development (we're using it behind a proxy), this isn't applied when loading the `livereload.js` script, causing the whole auto-reload feature to break.
I expect it to be loaded from `https://test.local/my/subpath/js/livereload.js` if using `https://test.local/my/subpath` as `site_url`.
|
0.0
|
dc35569ade5e101c8c48b78bbed8708dd0b1b49a
|
[
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_directory_index",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_from_mount_path",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_modified_html",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_polling_from_mount_path",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_with_unicode_characters"
] |
[
"mkdocs/tests/livereload_tests.py::BuildTests::test_bad_error_handler",
"mkdocs/tests/livereload_tests.py::BuildTests::test_basic_rebuild",
"mkdocs/tests/livereload_tests.py::BuildTests::test_change_is_detected_while_building",
"mkdocs/tests/livereload_tests.py::BuildTests::test_custom_action_warns",
"mkdocs/tests/livereload_tests.py::BuildTests::test_error_handler",
"mkdocs/tests/livereload_tests.py::BuildTests::test_mime_types",
"mkdocs/tests/livereload_tests.py::BuildTests::test_multiple_dirs_can_cause_rebuild",
"mkdocs/tests/livereload_tests.py::BuildTests::test_multiple_dirs_changes_rebuild_only_once",
"mkdocs/tests/livereload_tests.py::BuildTests::test_rebuild_after_delete",
"mkdocs/tests/livereload_tests.py::BuildTests::test_rebuild_after_rename",
"mkdocs/tests/livereload_tests.py::BuildTests::test_rebuild_on_edit",
"mkdocs/tests/livereload_tests.py::BuildTests::test_redirects_to_directory",
"mkdocs/tests/livereload_tests.py::BuildTests::test_redirects_to_mount_path",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_normal_file",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_polling_after_event",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_polling_instantly",
"mkdocs/tests/livereload_tests.py::BuildTests::test_serves_polling_with_timeout",
"mkdocs/tests/livereload_tests.py::BuildTests::test_watch_with_broken_symlinks",
"mkdocs/tests/livereload_tests.py::BuildTests::test_watches_direct_symlinks",
"mkdocs/tests/livereload_tests.py::BuildTests::test_watches_through_relative_symlinks",
"mkdocs/tests/livereload_tests.py::BuildTests::test_watches_through_symlinks"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_removed_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-01-04 09:58:34+00:00
|
bsd-2-clause
| 4,005 |
|
mkdocs__mkdocs-2852
|
diff --git a/mkdocs/structure/files.py b/mkdocs/structure/files.py
index 80aa8c3d..ada0c95a 100644
--- a/mkdocs/structure/files.py
+++ b/mkdocs/structure/files.py
@@ -243,8 +243,8 @@ def get_files(config):
if _filter_paths(basename=filename, path=path, is_dir=False, exclude=exclude):
continue
# Skip README.md if an index file also exists in dir
- if filename.lower() == 'readme.md' and 'index.md' in filenames:
- log.warning(f"Both index.md and readme.md found. Skipping readme.md from {source_dir}")
+ if filename == 'README.md' and 'index.md' in filenames:
+ log.warning(f"Both index.md and README.md found. Skipping README.md from {source_dir}")
continue
files.append(File(path, config['docs_dir'], config['site_dir'], config['use_directory_urls']))
|
mkdocs/mkdocs
|
82bd8ba5ff177347d094b095bd623a85aaa4c80f
|
diff --git a/mkdocs/tests/structure/file_tests.py b/mkdocs/tests/structure/file_tests.py
index 6ecc2587..d3d3cfad 100644
--- a/mkdocs/tests/structure/file_tests.py
+++ b/mkdocs/tests/structure/file_tests.py
@@ -592,6 +592,7 @@ class TestFiles(PathAssertionMixin, unittest.TestCase):
@tempdir(files=[
'index.md',
+ 'readme.md',
'bar.css',
'bar.html',
'bar.jpg',
@@ -603,7 +604,7 @@ class TestFiles(PathAssertionMixin, unittest.TestCase):
def test_get_files(self, tdir):
config = load_config(docs_dir=tdir, extra_css=['bar.css'], extra_javascript=['bar.js'])
files = get_files(config)
- expected = ['index.md', 'bar.css', 'bar.html', 'bar.jpg', 'bar.js', 'bar.md']
+ expected = ['index.md', 'bar.css', 'bar.html', 'bar.jpg', 'bar.js', 'bar.md', 'readme.md']
self.assertIsInstance(files, Files)
self.assertEqual(len(files), len(expected))
self.assertEqual([f.src_path for f in files], expected)
|
What is the expected behavior of `readme.md`?
According to the docs, [Writing-your-docs:Index-pages](https://www.mkdocs.org/user-guide/writing-your-docs/#index-pages), `README.md` will render into `index.html`. There is no mention of `readme.md`. The implementation reflects this behavior: https://github.com/mkdocs/mkdocs/blob/dc35569ade5e101c8c48b78bbed8708dd0b1b49a/mkdocs/structure/files.py#L151
But the check in [get_files()](https://github.com/mkdocs/mkdocs/blob/dc35569ade5e101c8c48b78bbed8708dd0b1b49a/mkdocs/structure/files.py#L225) ignores casing:
https://github.com/mkdocs/mkdocs/blob/dc35569ade5e101c8c48b78bbed8708dd0b1b49a/mkdocs/structure/files.py#L246-L247
I believe it should be:
```python
if filename == 'README.md' and 'index.md' in filenames:
```
|
0.0
|
82bd8ba5ff177347d094b095bd623a85aaa4c80f
|
[
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_files"
] |
[
"mkdocs/tests/structure/file_tests.py::TestFiles::test_add_files_from_theme",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file_clean_modified",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file_dirty_modified",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file_dirty_not_modified",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_css_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_css_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_file_eq",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_file_name_with_space",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_file_ne",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_files",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_files_append_remove_src_paths",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_filter_paths",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_files_exclude_readme_with_index",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_files_include_readme_without_index",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_relative_url",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_relative_url_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_javascript_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_javascript_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_file_nested",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_file_nested_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_index_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_index_file_nested",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_index_file_nested_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_index_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_readme_index_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_readme_index_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_media_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_media_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_sort_files",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_static_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_static_file_use_directory_urls"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-05-23 07:47:45+00:00
|
bsd-2-clause
| 4,006 |
|
mkdocs__mkdocs-2916
|
diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py
index aea40dd0..8bec5b42 100644
--- a/mkdocs/config/config_options.py
+++ b/mkdocs/config/config_options.py
@@ -49,19 +49,17 @@ class BaseConfigOption:
"""
-class SubConfig(BaseConfigOption, Config):
+class SubConfig(BaseConfigOption):
def __init__(self, *config_options):
- BaseConfigOption.__init__(self)
- Config.__init__(self, config_options)
+ super().__init__()
self.default = {}
-
- def validate(self, value):
- self.load_dict(value)
- return self.run_validation(value)
+ self.config_options = config_options
def run_validation(self, value):
- Config.validate(self)
- return self
+ config = Config(self.config_options)
+ config.load_dict(value)
+ config.validate()
+ return config
class ConfigItems(BaseConfigOption):
|
mkdocs/mkdocs
|
98672b85f60c66cb8479860d5e074a612b7764b2
|
diff --git a/mkdocs/tests/config/config_tests.py b/mkdocs/tests/config/config_tests.py
index eceef26e..908e6da6 100644
--- a/mkdocs/tests/config/config_tests.py
+++ b/mkdocs/tests/config/config_tests.py
@@ -283,6 +283,26 @@ class ConfigTests(unittest.TestCase):
self.assertEqual(len(errors), 1)
self.assertEqual(warnings, [])
+ SUBCONFIG_TEST_SCHEMA = {
+ "items": mkdocs.config.config_options.ConfigItems(
+ ("value", mkdocs.config.config_options.Type(str)),
+ ),
+ }.items()
+
+ def test_subconfig_with_multiple_items(self):
+ # This had a bug where subsequent items would get merged into the same dict.
+ conf = config.Config(schema=self.SUBCONFIG_TEST_SCHEMA)
+ conf.load_dict(
+ {
+ 'items': [
+ {'value': 'a'},
+ {'value': 'b'},
+ ]
+ }
+ )
+ conf.validate()
+ self.assertEqual(conf['items'], [{'value': 'a'}, {'value': 'b'}])
+
def test_multiple_markdown_config_instances(self):
# This had a bug where an extension config would persist to separate
# config instances that didn't specify extensions.
|
ConfigItems overwrites all data with last entry in the list of config items
`ConfigItems` does not work as expected and results in a list of items that contains only the same values.
### Reproduciton
`plugin.py`
```python
class TestPlugin(BasePlugin):
config_scheme = (
(
"items", mkdocs.config.config_options.ConfigItems(
("value", mkdocs.config.config_options.Type(str)),
),
),
)
def on_config(self, config):
print(self.config)
```
`mkdocs.yml`
```yaml
site_name: Test Site
plugins:
- test:
items:
- value: a
- value: b
```
This results in:
```
INFO - Building documentation...
{'items': [{'value': 'b'}, {'value': 'b'}]}
INFO - Cleaning site directory
INFO - Documentation built in 0.05 seconds
INFO - [12:21:39] Watching paths for changes: 'docs', 'mkdocs.yml'
INFO - [12:21:39] Serving on http://127.0.0.1:8000/
```
Note that both "value" values are `b` rather than the first one being `a`.
### Cause
`ConfigItems` creates a single `SubConfig` instance when it is instantiated:
https://github.com/mkdocs/mkdocs/blob/a17a25c60eb6622556bd74735fab84403f319dd5/mkdocs/config/config_options.py#L77
It then uses this instance to do validation:
https://github.com/mkdocs/mkdocs/blob/a17a25c60eb6622556bd74735fab84403f319dd5/mkdocs/config/config_options.py#L94
The `SubConfig` instance uses `load_dict` to populate `self.data` before validation.
https://github.com/mkdocs/mkdocs/blob/a17a25c60eb6622556bd74735fab84403f319dd5/mkdocs/config/config_options.py#L60
The `load_dict` function uses `update` to make changes to `self.data` on the `SubConfig` instance:
https://github.com/mkdocs/mkdocs/blob/a17a25c60eb6622556bd74735fab84403f319dd5/mkdocs/config/base.py#L132
Since there is only one `SubConfig` instance, when this dictionary gets updated it gets updated across all references to it.
### Fix
A number of popular plugins already create their own `ConfigItems` to address this by making `item_config` a property that returns a separate `SubConfig` instance each time it is used. This seems like a reasonable approach.
https://github.com/pieterdavid/mkdocs-doxygen-plugin/blob/49b841b649acf58b668c0b805ab27f9e454920f4/mkdocsdoxygen/configitems.py#L24-L26
|
0.0
|
98672b85f60c66cb8479860d5e074a612b7764b2
|
[
"mkdocs/tests/config/config_tests.py::ConfigTests::test_subconfig_with_multiple_items"
] |
[
"mkdocs/tests/config/config_tests.py::ConfigTests::test_config_option",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_doc_dir_in_site_dir",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_empty_config",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_empty_nav",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_error_on_pages",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_invalid_config",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_missing_config_file",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_missing_site_name",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_multiple_markdown_config_instances",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_nonexistant_config",
"mkdocs/tests/config/config_tests.py::ConfigTests::test_theme"
] |
{
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-08-07 22:54:37+00:00
|
bsd-2-clause
| 4,007 |
|
mkdocs__mkdocs-3016
|
diff --git a/mkdocs/config/base.py b/mkdocs/config/base.py
index 25631c33..9c99018f 100644
--- a/mkdocs/config/base.py
+++ b/mkdocs/config/base.py
@@ -363,13 +363,13 @@ def load_config(config_file: Optional[Union[str, IO]] = None, **kwargs) -> MkDoc
errors, warnings = cfg.validate()
for config_name, warning in warnings:
- log.warning(f"Config value: '{config_name}'. Warning: {warning}")
+ log.warning(f"Config value '{config_name}': {warning}")
for config_name, error in errors:
- log.error(f"Config value: '{config_name}'. Error: {error}")
+ log.error(f"Config value '{config_name}': {error}")
for key, value in cfg.items():
- log.debug(f"Config value: '{key}' = {value!r}")
+ log.debug(f"Config value '{key}' = {value!r}")
if len(errors) > 0:
raise exceptions.Abort(f"Aborted with {len(errors)} Configuration Errors!")
diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py
index 1545d5cf..19386c92 100644
--- a/mkdocs/config/config_options.py
+++ b/mkdocs/config/config_options.py
@@ -96,11 +96,11 @@ class SubConfig(Generic[SomeConfig], BaseConfigOption[SomeConfig]):
if self._do_validation:
# Capture errors and warnings
- self.warnings = [f'Sub-option {key!r}: {msg}' for key, msg in warnings]
+ self.warnings = [f"Sub-option '{key}': {msg}" for key, msg in warnings]
if failed:
# Get the first failing one
key, err = failed[0]
- raise ValidationError(f"Sub-option {key!r} configuration error: {err}")
+ raise ValidationError(f"Sub-option '{key}': {err}")
return config
@@ -309,7 +309,7 @@ class Deprecated(BaseConfigOption):
else:
message = (
"The configuration option '{}' has been deprecated and "
- "will be removed in a future release of MkDocs."
+ "will be removed in a future release."
)
if moved_to:
message += f" Use '{moved_to}' instead."
@@ -996,11 +996,17 @@ class Plugins(OptionallyRequired[plugins.PluginCollection]):
if hasattr(plugin, 'on_startup') or hasattr(plugin, 'on_shutdown'):
self.plugin_cache[name] = plugin
- errors, warnings = plugin.load_config(
+ errors, warns = plugin.load_config(
config, self._config.config_file_path if self._config else None
)
- self.warnings.extend(f"Plugin '{name}' value: '{x}'. Warning: {y}" for x, y in warnings)
- errors_message = '\n'.join(f"Plugin '{name}' value: '{x}'. Error: {y}" for x, y in errors)
+ for warning in warns:
+ if isinstance(warning, str):
+ self.warnings.append(f"Plugin '{name}': {warning}")
+ else:
+ key, msg = warning
+ self.warnings.append(f"Plugin '{name}' option '{key}': {msg}")
+
+ errors_message = '\n'.join(f"Plugin '{name}' option '{key}': {msg}" for key, msg in errors)
if errors_message:
raise ValidationError(errors_message)
return plugin
|
mkdocs/mkdocs
|
0584e51e7d151c51579c94e80ca06aa4ea9bafe5
|
diff --git a/mkdocs/tests/config/base_tests.py b/mkdocs/tests/config/base_tests.py
index 70f96787..3138f48e 100644
--- a/mkdocs/tests/config/base_tests.py
+++ b/mkdocs/tests/config/base_tests.py
@@ -147,7 +147,7 @@ class ConfigBaseTests(unittest.TestCase):
base.load_config(config_file=config_file.name)
self.assertEqual(
'\n'.join(cm.output),
- "ERROR:mkdocs.config:Config value: 'site_name'. Error: Required configuration not provided.",
+ "ERROR:mkdocs.config:Config value 'site_name': Required configuration not provided.",
)
def test_pre_validation_error(self):
diff --git a/mkdocs/tests/config/config_options_legacy_tests.py b/mkdocs/tests/config/config_options_legacy_tests.py
index 7d926514..8adcdd96 100644
--- a/mkdocs/tests/config/config_options_legacy_tests.py
+++ b/mkdocs/tests/config/config_options_legacy_tests.py
@@ -190,7 +190,7 @@ class DeprecatedTest(TestCase):
{'d': 'value'},
warnings=dict(
d="The configuration option 'd' has been deprecated and will be removed in a "
- "future release of MkDocs."
+ "future release."
),
)
@@ -209,7 +209,7 @@ class DeprecatedTest(TestCase):
{'d': 'value'},
warnings=dict(
d="The configuration option 'd' has been deprecated and will be removed in a "
- "future release of MkDocs."
+ "future release."
),
)
@@ -223,7 +223,7 @@ class DeprecatedTest(TestCase):
{'d': 'value'},
warnings=dict(
d="The configuration option 'd' has been deprecated and will be removed in a "
- "future release of MkDocs."
+ "future release."
),
)
@@ -252,7 +252,7 @@ class DeprecatedTest(TestCase):
{'old': 'value'},
warnings=dict(
old="The configuration option 'old' has been deprecated and will be removed in a "
- "future release of MkDocs. Use 'new' instead."
+ "future release. Use 'new' instead."
),
)
self.assertEqual(conf, {'new': 'value', 'old': None})
@@ -267,7 +267,7 @@ class DeprecatedTest(TestCase):
{'old': 'value'},
warnings=dict(
old="The configuration option 'old' has been deprecated and will be removed in a "
- "future release of MkDocs. Use 'foo.bar' instead."
+ "future release. Use 'foo.bar' instead."
),
)
self.assertEqual(conf, {'foo': {'bar': 'value'}, 'old': None})
@@ -282,7 +282,7 @@ class DeprecatedTest(TestCase):
{'old': 'value', 'foo': {'existing': 'existing'}},
warnings=dict(
old="The configuration option 'old' has been deprecated and will be removed in a "
- "future release of MkDocs. Use 'foo.bar' instead."
+ "future release. Use 'foo.bar' instead."
),
)
self.assertEqual(conf, {'foo': {'existing': 'existing', 'bar': 'value'}, 'old': None})
@@ -298,7 +298,7 @@ class DeprecatedTest(TestCase):
{'old': 'value', 'foo': 'wrong type'},
warnings=dict(
old="The configuration option 'old' has been deprecated and will be removed in a "
- "future release of MkDocs. Use 'foo.bar' instead."
+ "future release. Use 'foo.bar' instead."
),
)
@@ -1247,7 +1247,7 @@ class SubConfigTest(TestCase):
)
with self.expect_error(
- option="Sub-option 'cc' configuration error: Expected one of: ('foo', 'bar') but received: True"
+ option="Sub-option 'cc': Expected one of: ('foo', 'bar') but received: True"
):
self.get_config(Schema, {'option': {'cc': True}})
@@ -1320,7 +1320,7 @@ class ConfigItemsTest(TestCase):
conf = self.get_config(Schema, {'sub': None})
with self.expect_error(
- sub="Sub-option 'opt' configuration error: Expected type: <class 'int'> but received: <class 'str'>"
+ sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
conf = self.get_config(Schema, {'sub': [{'opt': 'asdf'}, {}]})
@@ -1330,14 +1330,12 @@ class ConfigItemsTest(TestCase):
self.assertEqual(conf['sub'], [{'opt': 1}, {'opt': 2}])
with self.expect_error(
- sub="Sub-option 'opt' configuration error: Expected type: <class 'int'> but "
- "received: <class 'str'>"
+ sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]})
with self.expect_error(
- sub="Sub-option 'opt' configuration error: "
- "Expected type: <class 'int'> but received: <class 'str'>"
+ sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
conf = self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]})
diff --git a/mkdocs/tests/config/config_options_tests.py b/mkdocs/tests/config/config_options_tests.py
index 91828c5e..a34f5d60 100644
--- a/mkdocs/tests/config/config_options_tests.py
+++ b/mkdocs/tests/config/config_options_tests.py
@@ -171,7 +171,7 @@ class DeprecatedTest(TestCase):
{'d': 'value'},
warnings=dict(
d="The configuration option 'd' has been deprecated and will be removed in a "
- "future release of MkDocs."
+ "future release."
),
)
@@ -190,7 +190,7 @@ class DeprecatedTest(TestCase):
{'d': 'value'},
warnings=dict(
d="The configuration option 'd' has been deprecated and will be removed in a "
- "future release of MkDocs."
+ "future release."
),
)
@@ -204,7 +204,7 @@ class DeprecatedTest(TestCase):
{'d': 'value'},
warnings=dict(
d="The configuration option 'd' has been deprecated and will be removed in a "
- "future release of MkDocs."
+ "future release."
),
)
@@ -233,7 +233,7 @@ class DeprecatedTest(TestCase):
{'old': 'value'},
warnings=dict(
old="The configuration option 'old' has been deprecated and will be removed in a "
- "future release of MkDocs. Use 'new' instead."
+ "future release. Use 'new' instead."
),
)
self.assertEqual(conf, {'new': 'value', 'old': None})
@@ -248,7 +248,7 @@ class DeprecatedTest(TestCase):
{'old': 'value'},
warnings=dict(
old="The configuration option 'old' has been deprecated and will be removed in a "
- "future release of MkDocs. Use 'foo.bar' instead."
+ "future release. Use 'foo.bar' instead."
),
)
self.assertEqual(conf, {'foo': {'bar': 'value'}, 'old': None})
@@ -263,7 +263,7 @@ class DeprecatedTest(TestCase):
{'old': 'value', 'foo': {'existing': 'existing'}},
warnings=dict(
old="The configuration option 'old' has been deprecated and will be removed in a "
- "future release of MkDocs. Use 'foo.bar' instead."
+ "future release. Use 'foo.bar' instead."
),
)
self.assertEqual(conf, {'foo': {'existing': 'existing', 'bar': 'value'}, 'old': None})
@@ -279,7 +279,7 @@ class DeprecatedTest(TestCase):
{'old': 'value', 'foo': 'wrong type'},
warnings=dict(
old="The configuration option 'old' has been deprecated and will be removed in a "
- "future release of MkDocs. Use 'foo.bar' instead."
+ "future release. Use 'foo.bar' instead."
),
)
@@ -1252,7 +1252,7 @@ class SubConfigTest(TestCase):
option = c.SubConfig(Sub)
with self.expect_error(
- option="Sub-option 'cc' configuration error: Expected one of: ('foo', 'bar') but received: True"
+ option="Sub-option 'cc': Expected one of: ('foo', 'bar') but received: True"
):
self.get_config(Schema, {'option': {'cc': True}})
@@ -1330,7 +1330,7 @@ class SubConfigTest(TestCase):
conf = self.get_config(Schema, {'sub': None})
with self.expect_error(
- sub="Sub-option 'opt' configuration error: Expected type: <class 'int'> but received: <class 'str'>"
+ sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
conf = self.get_config(Schema, {'sub': [{'opt': 'asdf'}, {}]})
@@ -1343,14 +1343,12 @@ class SubConfigTest(TestCase):
self.assertEqual(conf.sub[0].opt, 1)
with self.expect_error(
- sub="Sub-option 'opt' configuration error: Expected type: <class 'int'> but "
- "received: <class 'str'>"
+ sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]})
with self.expect_error(
- sub="Sub-option 'opt' configuration error: "
- "Expected type: <class 'int'> but received: <class 'str'>"
+ sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
conf = self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]})
@@ -1927,7 +1925,7 @@ class PluginsTest(TestCase):
}
}
with self.expect_error(
- plugins="Plugin 'sample' value: 'bar'. Error: Expected type: <class 'int'> but received: <class 'str'>"
+ plugins="Plugin 'sample' option 'bar': Expected type: <class 'int'> but received: <class 'str'>"
):
self.get_config(Schema, cfg)
@@ -1944,8 +1942,8 @@ class PluginsTest(TestCase):
Schema,
cfg,
warnings=dict(
- plugins="Plugin 'sample2' value: 'depr'. Warning: The configuration option "
- "'depr' has been deprecated and will be removed in a future release of MkDocs."
+ plugins="Plugin 'sample2' option 'depr': The configuration option "
+ "'depr' has been deprecated and will be removed in a future release."
),
)
|
Unclear issue when trying to build the site
Hi, on two different machines (one macOS, the other Ubuntu with a fresh install of mkdocs), when I try to build the site, I get these very unclear error messages. Would anyone have an idea if the issue is with the mkdocs files or python itself?
Running python 3.10 on the Mac, 3.8 on Ubuntu. Latest version of mkdocs and materials installed. The YAML file was validated, but it is encoded in ASCII and multiple attempts to convert it to UTF8 have mysteriously failed.
It also fails when compiling with GitHub Pages, which is why I tried to debug this on my laptop. There were a few changes made to the code by removing a plug-in I believe, but even if I download old commits that used to build and publish just fine do not work on my computer or on Ubuntu.
I'm really at a loss here.
```
mkdocs build
INFO - DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
File "/usr/lib/python3/dist-packages/apport/report.py", line 13, in <module>
import fnmatch, glob, traceback, errno, sys, atexit, locale, imp, stat
File "/usr/lib/python3.8/imp.py", line 31, in <module>
warnings.warn("the imp module is deprecated in favour of importlib; "
Traceback (most recent call last):
File "/usr/local/bin/mkdocs", line 8, in <module>
sys.exit(cli())
File "/usr/lib/python3/dist-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/usr/lib/python3/dist-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/lib/python3/dist-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/lib/python3/dist-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/lib/python3/dist-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/mkdocs/__main__.py", line 247, in build_command
cfg = config.load_config(**kwargs)
File "/usr/local/lib/python3.8/dist-packages/mkdocs/config/base.py", line 363, in load_config
errors, warnings = cfg.validate()
File "/usr/local/lib/python3.8/dist-packages/mkdocs/config/base.py", line 228, in validate
run_failed, run_warnings = self._validate()
File "/usr/local/lib/python3.8/dist-packages/mkdocs/config/base.py", line 186, in _validate
self[key] = config_option.validate(value)
File "/usr/local/lib/python3.8/dist-packages/mkdocs/config/config_options.py", line 146, in validate
return self.run_validation(value)
File "/usr/local/lib/python3.8/dist-packages/mkdocs/config/config_options.py", line 937, in run_validation
name, plugin = self.load_plugin_with_namespace(name, cfg)
File "/usr/local/lib/python3.8/dist-packages/mkdocs/config/config_options.py", line 974, in load_plugin_with_namespace
return (name, self.load_plugin(name, config))
File "/usr/local/lib/python3.8/dist-packages/mkdocs/config/config_options.py", line 1002, in load_plugin
self.warnings.extend(f"Plugin '{name}' value: '{x}'. Warning: {y}" for x, y in warnings)
File "/usr/local/lib/python3.8/dist-packages/mkdocs/config/config_options.py", line 1002, in <genexpr>
self.warnings.extend(f"Plugin '{name}' value: '{x}'. Warning: {y}" for x, y in warnings)
ValueError: too many values to unpack (expected 2)
```
|
0.0
|
0584e51e7d151c51579c94e80ca06aa4ea9bafe5
|
[
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_move",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_move_complex",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_move_existing",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_simple",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_with_type",
"mkdocs/tests/config/config_options_legacy_tests.py::SubConfigTest::test_subconfig_invalid_option",
"mkdocs/tests/config/config_options_legacy_tests.py::ConfigItemsTest::test_required",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_move",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_move_complex",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_move_existing",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_simple",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_with_type",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_required",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_invalid_option",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_sub_error",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_sub_warning"
] |
[
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_get_schema",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_default_file",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_default_file_prefer_yml",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_default_file_with_yaml",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_from_closed_file",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_from_file",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_from_file_with_relative_paths",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_from_missing_file",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_from_open_file",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_load_missing_required",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_missing_required",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_post_validation_error",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_pre_and_run_validation_errors",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_pre_validation_error",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_run_and_post_validation_errors",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_run_validation_error",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_unrecognised_keys",
"mkdocs/tests/config/base_tests.py::ConfigBaseTests::test_validation_warnings",
"mkdocs/tests/config/config_options_legacy_tests.py::OptionallyRequiredTest::test_default",
"mkdocs/tests/config/config_options_legacy_tests.py::OptionallyRequiredTest::test_empty",
"mkdocs/tests/config/config_options_legacy_tests.py::OptionallyRequiredTest::test_replace_default",
"mkdocs/tests/config/config_options_legacy_tests.py::OptionallyRequiredTest::test_required",
"mkdocs/tests/config/config_options_legacy_tests.py::OptionallyRequiredTest::test_required_no_default",
"mkdocs/tests/config/config_options_legacy_tests.py::TypeTest::test_length",
"mkdocs/tests/config/config_options_legacy_tests.py::TypeTest::test_multiple_types",
"mkdocs/tests/config/config_options_legacy_tests.py::TypeTest::test_single_type",
"mkdocs/tests/config/config_options_legacy_tests.py::ChoiceTest::test_default",
"mkdocs/tests/config/config_options_legacy_tests.py::ChoiceTest::test_invalid_choice",
"mkdocs/tests/config/config_options_legacy_tests.py::ChoiceTest::test_invalid_choices",
"mkdocs/tests/config/config_options_legacy_tests.py::ChoiceTest::test_invalid_default",
"mkdocs/tests/config/config_options_legacy_tests.py::ChoiceTest::test_optional",
"mkdocs/tests/config/config_options_legacy_tests.py::ChoiceTest::test_required",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_message",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_move_invalid",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_with_invalid_type",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_deprecated_option_with_type_undefined",
"mkdocs/tests/config/config_options_legacy_tests.py::DeprecatedTest::test_removed_option",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_default_address",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_invalid_address_format",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_invalid_address_missing_port",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_invalid_address_port",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_invalid_address_range",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_invalid_address_type",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_invalid_leading_zeros",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_named_address",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_unsupported_IPv6_address",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_unsupported_address",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_valid_IPv6_address",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_valid_address",
"mkdocs/tests/config/config_options_legacy_tests.py::IpAddressTest::test_valid_full_IPv6_address",
"mkdocs/tests/config/config_options_legacy_tests.py::URLTest::test_invalid_type",
"mkdocs/tests/config/config_options_legacy_tests.py::URLTest::test_invalid_url",
"mkdocs/tests/config/config_options_legacy_tests.py::URLTest::test_optional",
"mkdocs/tests/config/config_options_legacy_tests.py::URLTest::test_valid_url",
"mkdocs/tests/config/config_options_legacy_tests.py::URLTest::test_valid_url_is_dir",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_edit_uri_bitbucket",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_edit_uri_custom",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_edit_uri_github",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_edit_uri_gitlab",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_edit_uri_template_errors",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_edit_uri_template_ok",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_edit_uri_template_warning",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_repo_name_bitbucket",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_repo_name_custom",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_repo_name_custom_and_empty_edit_uri",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_repo_name_github",
"mkdocs/tests/config/config_options_legacy_tests.py::EditURITest::test_repo_name_gitlab",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfItemsTest::test_combined_float_type",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfItemsTest::test_int_type",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfItemsTest::test_list_default",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfItemsTest::test_none_without_default",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfItemsTest::test_post_validation_error",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfItemsTest::test_string_not_a_list_of_strings",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_config_dir_prepended",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_dir_bytes",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_incorrect_type_error",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_missing_but_required",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_missing_without_exists",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_not_a_dir",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_not_a_file",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_site_dir_is_config_dir_fails",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_valid_dir",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_valid_file",
"mkdocs/tests/config/config_options_legacy_tests.py::FilesystemObjectTest::test_with_unicode",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfPathsTest::test_empty_list",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfPathsTest::test_file",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfPathsTest::test_missing_path",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfPathsTest::test_non_list",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfPathsTest::test_non_path",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfPathsTest::test_paths_localized_to_config",
"mkdocs/tests/config/config_options_legacy_tests.py::ListOfPathsTest::test_valid_path",
"mkdocs/tests/config/config_options_legacy_tests.py::SiteDirTest::test_common_prefix",
"mkdocs/tests/config/config_options_legacy_tests.py::SiteDirTest::test_doc_dir_in_site_dir",
"mkdocs/tests/config/config_options_legacy_tests.py::SiteDirTest::test_site_dir_in_docs_dir",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_post_validation_inexisting_custom_dir",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_post_validation_locale",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_post_validation_locale_invalid_type",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_post_validation_locale_none",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_post_validation_none_theme_name_and_missing_custom_dir",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_theme_as_complex_config",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_theme_as_simple_config",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_theme_as_string",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_theme_config_missing_name",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_theme_default",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_theme_invalid_type",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_theme_name_is_none",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_uninstalled_theme_as_config",
"mkdocs/tests/config/config_options_legacy_tests.py::ThemeTest::test_uninstalled_theme_as_string",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_children_config_int",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_children_config_none",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_children_empty_dict",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_children_oversized_dict",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_item_int",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_item_none",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_nested_list",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_type_dict",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_invalid_type_int",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_normal_nav",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_old_format",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_provided_dict",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_provided_empty",
"mkdocs/tests/config/config_options_legacy_tests.py::NavTest::test_warns_for_dict",
"mkdocs/tests/config/config_options_legacy_tests.py::PrivateTest::test_defined",
"mkdocs/tests/config/config_options_legacy_tests.py::SubConfigTest::test_subconfig_ignored",
"mkdocs/tests/config/config_options_legacy_tests.py::SubConfigTest::test_subconfig_normal",
"mkdocs/tests/config/config_options_legacy_tests.py::SubConfigTest::test_subconfig_unknown_option",
"mkdocs/tests/config/config_options_legacy_tests.py::SubConfigTest::test_subconfig_wrong_type",
"mkdocs/tests/config/config_options_legacy_tests.py::ConfigItemsTest::test_optional",
"mkdocs/tests/config/config_options_legacy_tests.py::ConfigItemsTest::test_subconfig_with_multiple_items",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_builtins",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_builtins_config",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_configkey",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_dict_of_dicts",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_duplicates",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_invalid_config_item",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_invalid_config_option",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_invalid_dict_item",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_list_dicts",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_missing_default",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_mixed_list",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_multiple_markdown_config_instances",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_none",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_not_list",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_simple_list",
"mkdocs/tests/config/config_options_legacy_tests.py::MarkdownExtensionsTest::test_unknown_extension",
"mkdocs/tests/config/config_options_legacy_tests.py::HooksTest::test_hooks",
"mkdocs/tests/config/config_options_legacy_tests.py::SchemaTest::test_copy",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_length",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_multiple_types",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_optional_with_default",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_single_type",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_default",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_invalid_choice",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_invalid_choices",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_invalid_default",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_required",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_message",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_move_invalid",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_with_invalid_type",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_with_type_undefined",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_removed_option",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_default_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_format",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_missing_port",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_port",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_range",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_type",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_leading_zeros",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_named_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_unsupported_IPv6_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_unsupported_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_valid_IPv6_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_valid_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_valid_full_IPv6_address",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid_type",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid_url",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_valid_url",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_valid_url_is_dir",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_bitbucket",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_custom",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_github",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_gitlab",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_template_errors",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_template_ok",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_template_warning",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_bitbucket",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_custom",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_custom_and_empty_edit_uri",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_github",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_gitlab",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_combined_float_type",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_int_type",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_list_default",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_list_of_optional",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_none_without_default",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_post_validation_error",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_string_not_a_list_of_strings",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_config_dir_prepended",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_dir_bytes",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_incorrect_type_error",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_missing_but_required",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_missing_without_exists",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_not_a_dir",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_not_a_file",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_site_dir_is_config_dir_fails",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_valid_dir",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_valid_file",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_with_unicode",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_empty_list",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_file",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_missing_path",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_non_list",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_non_path",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_none",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_paths_localized_to_config",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_valid_path",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_common_prefix",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_doc_dir_in_site_dir",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_site_dir_in_docs_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_inexisting_custom_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_locale",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_locale_invalid_type",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_locale_none",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_none_theme_name_and_missing_custom_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_complex_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_simple_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_string",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_config_missing_name",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_default",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_invalid_type",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_name_is_none",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_uninstalled_theme_as_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_uninstalled_theme_as_string",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_children_config_int",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_children_config_none",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_children_empty_dict",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_children_oversized_dict",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_item_int",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_item_none",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_nested_list",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_type_dict",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_type_int",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_normal_nav",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_old_format",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_provided_dict",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_provided_empty",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_warns_for_dict",
"mkdocs/tests/config/config_options_tests.py::PrivateTest::test_defined",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_default",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_normal",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_unknown_option",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_with_multiple_items",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_wrong_type",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins_config",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_configkey",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_dict_of_dicts",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_duplicates",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_option",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_dict_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_list_dicts",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_missing_default",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_mixed_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_multiple_markdown_config_instances",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_none",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_not_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_simple_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_unknown_extension",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_as_dict",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_empty_list_with_default",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_empty_list_with_empty_default",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_multivalue_dict",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_none_with_default",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_none_with_empty_default",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_not_list",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_not_string_or_dict",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_options_not_dict",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_uninstalled",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_deduced_theme_namespace",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_deduced_theme_namespace_overridden",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_explicit_empty_namespace",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_explicit_theme_namespace",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_options",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_without_options",
"mkdocs/tests/config/config_options_tests.py::HooksTest::test_hooks",
"mkdocs/tests/config/config_options_tests.py::HooksTest::test_hooks_wrong_type",
"mkdocs/tests/config/config_options_tests.py::SchemaTest::test_copy",
"mkdocs/tests/config/config_options_tests.py::SchemaTest::test_subclass"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-21 20:31:39+00:00
|
bsd-2-clause
| 4,008 |
|
mkdocs__mkdocs-3022
|
diff --git a/mkdocs/livereload/__init__.py b/mkdocs/livereload/__init__.py
index c2e52ab8..e136ff05 100644
--- a/mkdocs/livereload/__init__.py
+++ b/mkdocs/livereload/__init__.py
@@ -246,7 +246,7 @@ class LiveReloadServer(socketserver.ThreadingMixIn, wsgiref.simple_server.WSGISe
self._epoch_cond.wait_for(condition, timeout=self.poll_response_timeout)
return [b"%d" % self._visible_epoch]
- if path.startswith(self.mount_path):
+ if (path + "/").startswith(self.mount_path):
rel_file_path = path[len(self.mount_path) :]
if path.endswith("/"):
diff --git a/mkdocs/structure/files.py b/mkdocs/structure/files.py
index e469c9e4..91679f82 100644
--- a/mkdocs/structure/files.py
+++ b/mkdocs/structure/files.py
@@ -230,10 +230,7 @@ class File:
url = self.dest_uri
dirname, filename = posixpath.split(url)
if use_directory_urls and filename == 'index.html':
- if dirname == '':
- url = '.'
- else:
- url = dirname + '/'
+ url = (dirname or '.') + '/'
return urlquote(url)
def url_relative_to(self, other: File) -> str:
diff --git a/mkdocs/structure/pages.py b/mkdocs/structure/pages.py
index f24ad967..6592495b 100644
--- a/mkdocs/structure/pages.py
+++ b/mkdocs/structure/pages.py
@@ -88,7 +88,7 @@ class Page:
@property
def url(self) -> str:
"""The URL of the page relative to the MkDocs `site_dir`."""
- return '' if self.file.url == '.' else self.file.url
+ return '' if self.file.url in ('.', './') else self.file.url
file: File
"""The documentation [`File`][mkdocs.structure.files.File] that the page is being rendered from."""
@@ -133,7 +133,7 @@ class Page:
@property
def is_homepage(self) -> bool:
"""Evaluates to `True` for the homepage of the site and `False` for all other pages."""
- return self.is_top_level and self.is_index and self.file.url in ['.', 'index.html']
+ return self.is_top_level and self.is_index and self.file.url in ('.', './', 'index.html')
previous_page: Optional[Page]
"""The [page][mkdocs.structure.pages.Page] object for the previous page or `None`.
|
mkdocs/mkdocs
|
1fa2af7926b334a5b02229c3ea1649ff04955b77
|
diff --git a/mkdocs/tests/structure/file_tests.py b/mkdocs/tests/structure/file_tests.py
index 7f5fd1ee..8d8257f0 100644
--- a/mkdocs/tests/structure/file_tests.py
+++ b/mkdocs/tests/structure/file_tests.py
@@ -168,7 +168,7 @@ class TestFiles(PathAssertionMixin, unittest.TestCase):
self.assertPathsEqual(f.abs_src_path, '/path/to/docs/index.md')
self.assertEqual(f.dest_uri, 'index.html')
self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html')
- self.assertEqual(f.url, '.')
+ self.assertEqual(f.url, './')
self.assertEqual(f.name, 'index')
self.assertTrue(f.is_documentation_page())
self.assertFalse(f.is_static_page())
@@ -182,7 +182,7 @@ class TestFiles(PathAssertionMixin, unittest.TestCase):
self.assertPathsEqual(f.abs_src_path, '/path/to/docs/README.md')
self.assertEqual(f.dest_uri, 'index.html')
self.assertPathsEqual(f.abs_dest_path, '/path/to/site/index.html')
- self.assertEqual(f.url, '.')
+ self.assertEqual(f.url, './')
self.assertEqual(f.name, 'index')
self.assertTrue(f.is_documentation_page())
self.assertFalse(f.is_static_page())
@@ -446,7 +446,7 @@ class TestFiles(PathAssertionMixin, unittest.TestCase):
]
to_file_urls = [
- '.',
+ './',
'foo/',
'foo/bar/',
'foo/bar/baz/',
@@ -493,18 +493,18 @@ class TestFiles(PathAssertionMixin, unittest.TestCase):
from_file = File('index.html', '/path/to/docs', '/path/to/site', use_directory_urls=True)
expected = [
- '.', # . relative to .
- '..', # . relative to foo/
- '../..', # . relative to foo/bar/
- '../../..', # . relative to foo/bar/baz/
- '..', # . relative to foo
- '../..', # . relative to foo/bar
- '../../..', # . relative to foo/bar/baz
+ './', # . relative to .
+ '../', # . relative to foo/
+ '../../', # . relative to foo/bar/
+ '../../../', # . relative to foo/bar/baz/
+ '../', # . relative to foo
+ '../../', # . relative to foo/bar
+ '../../../', # . relative to foo/bar/baz
]
for i, filename in enumerate(to_files):
file = File(filename, '/path/to/docs', '/path/to/site', use_directory_urls=True)
- self.assertEqual(from_file.url, '.')
+ self.assertEqual(from_file.url, './')
self.assertEqual(file.url, to_file_urls[i])
self.assertEqual(from_file.url_relative_to(file.url), expected[i])
self.assertEqual(from_file.url_relative_to(file), expected[i])
diff --git a/mkdocs/tests/structure/page_tests.py b/mkdocs/tests/structure/page_tests.py
index 24b17a01..9ccd9ff8 100644
--- a/mkdocs/tests/structure/page_tests.py
+++ b/mkdocs/tests/structure/page_tests.py
@@ -659,7 +659,7 @@ class RelativePathExtensionTests(unittest.TestCase):
def test_relative_html_link_index(self):
self.assertEqual(
self.get_rendered_result(['non-index.md', 'index.md']),
- '<p><a href="..">link</a></p>',
+ '<p><a href="../">link</a></p>',
)
@mock.patch('mkdocs.structure.pages.open', mock.mock_open(read_data='[link](sub2/index.md)'))
@@ -696,7 +696,7 @@ class RelativePathExtensionTests(unittest.TestCase):
def test_relative_html_link_parent_index(self):
self.assertEqual(
self.get_rendered_result(['sub2/non-index.md', 'index.md']),
- '<p><a href="../..">link</a></p>',
+ '<p><a href="../../">link</a></p>',
)
@mock.patch(
|
Link to paragraph on index.md breaks
I try to link from a subpage to a paragraph on my root index.md:
`[MyLink](../index.md#contact)`
This results when clicking in a 404 trying to open the following URL:
`documentation#contact`
Correct would be to link to
`documentation/#contact` (note the slash)
Just linking to the page itself works fine
`[MyLink](../index.md)`
`documentation/` (slash is in the link)
Anybody has a clue if I do anything wrong or if this is a bug?
I use mkdocs with Materials template. Can provide more if required.
|
0.0
|
1fa2af7926b334a5b02229c3ea1649ff04955b77
|
[
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_relative_url_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_index_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_readme_index_file_use_directory_urls",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_parent_index"
] |
[
"mkdocs/tests/structure/file_tests.py::TestFiles::test_add_files_from_theme",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file_clean_modified",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file_dirty_modified",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file_dirty_not_modified",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_copy_file_same_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_css_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_css_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_file_eq",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_file_name_with_space",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_file_ne",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_files",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_files_append_remove_src_paths",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_filter_paths",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_files",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_files_exclude_readme_with_index",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_files_include_readme_without_index",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_get_relative_url",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_javascript_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_javascript_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_file_nested",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_file_nested_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_index_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_index_file_nested",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_index_file_nested_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_md_readme_index_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_media_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_media_file_use_directory_urls",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_sort_files",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_static_file",
"mkdocs/tests/structure/file_tests.py::TestFiles::test_static_file_use_directory_urls",
"mkdocs/tests/structure/page_tests.py::PageTests::test_BOM",
"mkdocs/tests/structure/page_tests.py::PageTests::test_homepage",
"mkdocs/tests/structure/page_tests.py::PageTests::test_missing_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page_no_parent",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page_no_parent_no_directory_urls",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_nonindex_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url_nested",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url_nested_no_slash",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_defaults",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url_warning",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_eq",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_ne",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_no_directory_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_render",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_capitalized_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_homepage_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_meta",
"mkdocs/tests/structure/page_tests.py::PageTests::test_predefined_page_title",
"mkdocs/tests/structure/page_tests.py::SourceDateEpochTests::test_source_date_epoch",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_win_local_path",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_bad_relative_html_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_email_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_external_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_no_links",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_hash_only",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_index_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_page",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_page_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_with_encoded_space",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_with_unencoded_space",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_homepage",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_sibling",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_subpage"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-10-25 21:45:07+00:00
|
bsd-2-clause
| 4,009 |
|
mkdocs__mkdocs-3191
|
diff --git a/docs/user-guide/writing-your-docs.md b/docs/user-guide/writing-your-docs.md
index 4697abd5..66a10067 100644
--- a/docs/user-guide/writing-your-docs.md
+++ b/docs/user-guide/writing-your-docs.md
@@ -380,10 +380,14 @@ specific page. The following keys are supported:
MkDocs will attempt to determine the title of a document in the following
ways, in order:
- 1. A title defined in the [nav] configuration setting for a document.
- 2. A title defined in the `title` meta-data key of a document.
- 3. A level 1 Markdown header on the first line of the document body. Please note that [Setext-style] headers are not supported.
- 4. The filename of a document.
+ 1. A title defined in the [nav] configuration setting for a document.
+
+ 2. A title defined in the `title` meta-data key of a document.
+
+ 3. A level 1 Markdown header on the first line of the document body.
+ ([Setext-style] headers are supported *only since MkDocs 1.5*.)
+
+ 4. The filename of a document.
Upon finding a title for a page, MkDoc does not continue checking any
additional sources in the above list.
diff --git a/mkdocs/structure/pages.py b/mkdocs/structure/pages.py
index b2785687..e5a95874 100644
--- a/mkdocs/structure/pages.py
+++ b/mkdocs/structure/pages.py
@@ -1,27 +1,36 @@
from __future__ import annotations
+import copy
import logging
import os
import posixpath
-from typing import TYPE_CHECKING, Any, Mapping, MutableMapping
+import warnings
+from typing import TYPE_CHECKING, Any, Callable, Mapping, MutableMapping
from urllib.parse import unquote as urlunquote
from urllib.parse import urljoin, urlsplit, urlunsplit
-from xml.etree.ElementTree import Element
+from xml.etree import ElementTree as etree
import markdown
-from markdown.extensions import Extension
-from markdown.treeprocessors import Treeprocessor
+import markdown.extensions
+import markdown.postprocessors
+import markdown.treeprocessors
from markdown.util import AMP_SUBSTITUTE
from mkdocs.structure.files import File, Files
from mkdocs.structure.toc import get_toc
-from mkdocs.utils import get_build_date, get_markdown_title, meta
+from mkdocs.utils import get_build_date, get_markdown_title, meta, weak_property
if TYPE_CHECKING:
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.nav import Section
from mkdocs.structure.toc import TableOfContents
+_unescape: Callable[[str], str]
+try:
+ _unescape = markdown.treeprocessors.UnescapeTreeprocessor().unescape # type: ignore
+except AttributeError:
+ _unescape = markdown.postprocessors.UnescapePostprocessor().run
+
log = logging.getLogger(__name__)
@@ -32,7 +41,8 @@ class Page:
) -> None:
file.page = self
self.file = file
- self.title = title
+ if title is not None:
+ self.title = title
# Navigation attributes
self.parent = None
@@ -50,6 +60,7 @@ class Page:
# Placeholders to be filled in later in the build process.
self.markdown = None
+ self._title_from_render: str | None = None
self.content = None
self.toc = [] # type: ignore
self.meta = {}
@@ -69,9 +80,6 @@ class Page:
def _indent_print(self, depth=0):
return '{}{}'.format(' ' * depth, repr(self))
- title: str | None
- """Contains the Title for the current page."""
-
markdown: str | None
"""The original Markdown content from the file."""
@@ -226,11 +234,18 @@ class Page:
raise
self.markdown, self.meta = meta.get_data(source)
- self._set_title()
def _set_title(self) -> None:
+ warnings.warn(
+ "_set_title is no longer used in MkDocs and will be removed soon.", DeprecationWarning
+ )
+
+ @weak_property
+ def title(self) -> str | None:
"""
- Set the title for a Markdown document.
+ Returns the title for the current page.
+
+ Before calling `read_source()`, this value is empty. It can also be updated by `render()`.
Check these in order and use the first that returns a valid title:
- value provided on init (passed in from config)
@@ -238,48 +253,56 @@ class Page:
- content of the first H1 in Markdown content
- convert filename to title
"""
- if self.title is not None:
- return
+ if self.markdown is None:
+ return None
if 'title' in self.meta:
- self.title = self.meta['title']
- return
+ return self.meta['title']
- assert self.markdown is not None
- title = get_markdown_title(self.markdown)
+ if self._title_from_render:
+ return self._title_from_render
+ elif self.content is None: # Preserve legacy behavior only for edge cases in plugins.
+ title_from_md = get_markdown_title(self.markdown)
+ if title_from_md is not None:
+ return title_from_md
- if title is None:
- if self.is_homepage:
- title = 'Home'
- else:
- title = self.file.name.replace('-', ' ').replace('_', ' ')
- # Capitalize if the filename was all lowercase, otherwise leave it as-is.
- if title.lower() == title:
- title = title.capitalize()
+ if self.is_homepage:
+ return 'Home'
- self.title = title
+ title = self.file.name.replace('-', ' ').replace('_', ' ')
+ # Capitalize if the filename was all lowercase, otherwise leave it as-is.
+ if title.lower() == title:
+ title = title.capitalize()
+ return title
def render(self, config: MkDocsConfig, files: Files) -> None:
"""
Convert the Markdown source file to HTML as per the config.
"""
- extensions = [_RelativePathExtension(self.file, files), *config['markdown_extensions']]
+ if self.markdown is None:
+ raise RuntimeError("`markdown` field hasn't been set (via `read_source`)")
+ relative_path_extension = _RelativePathExtension(self.file, files)
+ extract_title_extension = _ExtractTitleExtension()
md = markdown.Markdown(
- extensions=extensions,
+ extensions=[
+ relative_path_extension,
+ extract_title_extension,
+ *config['markdown_extensions'],
+ ],
extension_configs=config['mdx_configs'] or {},
)
- assert self.markdown is not None
self.content = md.convert(self.markdown)
self.toc = get_toc(getattr(md, 'toc_tokens', []))
+ self._title_from_render = extract_title_extension.title
-class _RelativePathTreeprocessor(Treeprocessor):
+class _RelativePathTreeprocessor(markdown.treeprocessors.Treeprocessor):
def __init__(self, file: File, files: Files) -> None:
self.file = file
self.files = files
- def run(self, root: Element) -> Element:
+ def run(self, root: etree.Element) -> etree.Element:
"""
Update urls on anchors and images to make them relative
@@ -335,7 +358,7 @@ class _RelativePathTreeprocessor(Treeprocessor):
return urlunsplit(components)
-class _RelativePathExtension(Extension):
+class _RelativePathExtension(markdown.extensions.Extension):
"""
The Extension class is what we pass to markdown, it then
registers the Treeprocessor.
@@ -348,3 +371,32 @@ class _RelativePathExtension(Extension):
def extendMarkdown(self, md: markdown.Markdown) -> None:
relpath = _RelativePathTreeprocessor(self.file, self.files)
md.treeprocessors.register(relpath, "relpath", 0)
+
+
+class _ExtractTitleExtension(markdown.extensions.Extension):
+ def __init__(self) -> None:
+ self.title: str | None = None
+
+ def extendMarkdown(self, md: markdown.Markdown) -> None:
+ md.treeprocessors.register(
+ _ExtractTitleTreeprocessor(self),
+ "mkdocs_extract_title",
+ priority=1, # Close to the end.
+ )
+
+
+class _ExtractTitleTreeprocessor(markdown.treeprocessors.Treeprocessor):
+ def __init__(self, ext: _ExtractTitleExtension) -> None:
+ self.ext = ext
+
+ def run(self, root: etree.Element) -> etree.Element:
+ for el in root:
+ if el.tag == 'h1':
+ # Drop anchorlink from the element, if present.
+ if len(el) > 0 and el[-1].tag == 'a' and not (el.tail or '').strip():
+ el = copy.copy(el)
+ del el[-1]
+ # Extract the text only, recursively.
+ self.ext.title = _unescape(''.join(el.itertext()))
+ break
+ return root
diff --git a/mkdocs/utils/__init__.py b/mkdocs/utils/__init__.py
index 3eb55584..5ebf3731 100644
--- a/mkdocs/utils/__init__.py
+++ b/mkdocs/utils/__init__.py
@@ -385,13 +385,7 @@ def dirname_to_title(dirname: str) -> str:
def get_markdown_title(markdown_src: str) -> str | None:
- """
- Get the title of a Markdown document. The title in this case is considered
- to be a H1 that occurs before any other content in the document.
- The procedure is then to iterate through the lines, stopping at the first
- non-whitespace content. If it is a title, return that, otherwise return
- None.
- """
+ """Soft-deprecated, do not use."""
lines = markdown_src.replace('\r\n', '\n').replace('\r', '\n').split('\n')
while lines:
line = lines.pop(0).strip()
@@ -460,6 +454,19 @@ class CountHandler(logging.NullHandler):
return [(logging.getLevelName(k), v) for k, v in sorted(self.counts.items(), reverse=True)]
+class weak_property:
+ """Same as a read-only property, but allows overwriting the field for good."""
+
+ def __init__(self, func):
+ self.func = func
+ self.__doc__ = func.__doc__
+
+ def __get__(self, instance, owner=None):
+ if instance is None:
+ return self
+ return self.func(instance)
+
+
def __getattr__(name: str):
if name == 'warning_filter':
warnings.warn(
|
mkdocs/mkdocs
|
8ecdfb2510a481c89d0659ba103aa9a87eb94d62
|
diff --git a/mkdocs/tests/structure/page_tests.py b/mkdocs/tests/structure/page_tests.py
index 9ccd9ff8..30a90f68 100644
--- a/mkdocs/tests/structure/page_tests.py
+++ b/mkdocs/tests/structure/page_tests.py
@@ -4,6 +4,7 @@ import sys
import unittest
from unittest import mock
+from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import File, Files
from mkdocs.structure.pages import Page
from mkdocs.tests.base import dedent, load_config, tempdir
@@ -299,7 +300,84 @@ class PageTests(unittest.TestCase):
self.assertEqual(pg.parent, None)
self.assertEqual(pg.previous_page, None)
self.assertEqual(pg.title, 'Welcome to MkDocs')
- self.assertEqual(pg.toc, [])
+ pg.render(cfg, fl)
+ self.assertEqual(pg.title, 'Welcome to MkDocs')
+
+ _SETEXT_CONTENT = dedent(
+ '''
+ Welcome to MkDocs Setext
+ ========================
+
+ This tests extracting a setext style title.
+ '''
+ )
+
+ @tempdir(files={'testing_setext_title.md': _SETEXT_CONTENT})
+ def test_page_title_from_setext_markdown(self, docs_dir):
+ cfg = load_config()
+ fl = File('testing_setext_title.md', docs_dir, docs_dir, use_directory_urls=True)
+ pg = Page(None, fl, cfg)
+ self.assertIsNone(pg.title)
+ pg.read_source(cfg)
+ self.assertEqual(pg.title, 'Testing setext title')
+ pg.render(cfg, fl)
+ self.assertEqual(pg.title, 'Welcome to MkDocs Setext')
+
+ @tempdir(files={'testing_setext_title.md': _SETEXT_CONTENT})
+ def test_page_title_from_markdown_stripped_anchorlinks(self, docs_dir):
+ cfg = MkDocsConfig()
+ cfg.site_name = 'example'
+ cfg.markdown_extensions = {'toc': {'permalink': '&'}}
+ self.assertEqual(cfg.validate(), ([], []))
+ fl = File('testing_setext_title.md', docs_dir, docs_dir, use_directory_urls=True)
+ pg = Page(None, fl, cfg)
+ pg.read_source(cfg)
+ pg.render(cfg, fl)
+ self.assertEqual(pg.title, 'Welcome to MkDocs Setext')
+
+ _FORMATTING_CONTENT = dedent(
+ '''
+ # Hello *beautiful* `world`
+
+ Hi.
+ '''
+ )
+
+ @tempdir(files={'testing_formatting.md': _FORMATTING_CONTENT})
+ def test_page_title_from_markdown_strip_formatting(self, docs_dir):
+ cfg = load_config()
+ fl = File('testing_formatting.md', docs_dir, docs_dir, use_directory_urls=True)
+ pg = Page(None, fl, cfg)
+ pg.read_source(cfg)
+ pg.render(cfg, fl)
+ self.assertEqual(pg.title, 'Hello beautiful world')
+
+ _ATTRLIST_CONTENT = dedent(
+ '''
+ # Welcome to MkDocs Attr { #welcome }
+
+ This tests extracting the title, with enabled attr_list markdown_extension.
+ '''
+ )
+
+ @tempdir(files={'testing_attr_list.md': _ATTRLIST_CONTENT})
+ def test_page_title_from_markdown_stripped_attr_list(self, docs_dir):
+ cfg = load_config()
+ cfg.markdown_extensions.append('attr_list')
+ fl = File('testing_attr_list.md', docs_dir, docs_dir, use_directory_urls=True)
+ pg = Page(None, fl, cfg)
+ pg.read_source(cfg)
+ pg.render(cfg, fl)
+ self.assertEqual(pg.title, 'Welcome to MkDocs Attr')
+
+ @tempdir(files={'testing_attr_list.md': _ATTRLIST_CONTENT})
+ def test_page_title_from_markdown_preserved_attr_list(self, docs_dir):
+ cfg = load_config()
+ fl = File('testing_attr_list.md', docs_dir, docs_dir, use_directory_urls=True)
+ pg = Page(None, fl, cfg)
+ pg.read_source(cfg)
+ pg.render(cfg, fl)
+ self.assertEqual(pg.title, 'Welcome to MkDocs Attr { #welcome }')
def test_page_title_from_meta(self):
cfg = load_config(docs_dir=self.DOCS_DIR)
@@ -324,6 +402,8 @@ class PageTests(unittest.TestCase):
self.assertEqual(pg.previous_page, None)
self.assertEqual(pg.title, 'A Page Title')
self.assertEqual(pg.toc, [])
+ pg.render(cfg, fl)
+ self.assertEqual(pg.title, 'A Page Title')
def test_page_title_from_filename(self):
cfg = load_config(docs_dir=self.DOCS_DIR)
@@ -347,7 +427,8 @@ class PageTests(unittest.TestCase):
self.assertEqual(pg.parent, None)
self.assertEqual(pg.previous_page, None)
self.assertEqual(pg.title, 'Page title')
- self.assertEqual(pg.toc, [])
+ pg.render(cfg, fl)
+ self.assertEqual(pg.title, 'Page title')
def test_page_title_from_capitalized_filename(self):
cfg = load_config(docs_dir=self.DOCS_DIR)
@@ -371,7 +452,6 @@ class PageTests(unittest.TestCase):
self.assertEqual(pg.parent, None)
self.assertEqual(pg.previous_page, None)
self.assertEqual(pg.title, 'pageTitle')
- self.assertEqual(pg.toc, [])
def test_page_title_from_homepage_filename(self):
cfg = load_config(docs_dir=self.DOCS_DIR)
|
Add support to extract underline-ish title (setext-style headings)
The util function [`get_markdown_title`](https://github.com/mkdocs/mkdocs/blob/master/mkdocs/utils/__init__.py#L332) supports only ATX-style headers. It should also support:
```markdown
A level-one heading
===================
A level-two heading
-------------------
```
|
0.0
|
8ecdfb2510a481c89d0659ba103aa9a87eb94d62
|
[
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_formatting",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_stripped_anchorlinks",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_stripped_attr_list",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_setext_markdown"
] |
[
"mkdocs/tests/structure/page_tests.py::PageTests::test_BOM",
"mkdocs/tests/structure/page_tests.py::PageTests::test_homepage",
"mkdocs/tests/structure/page_tests.py::PageTests::test_missing_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page_no_parent",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page_no_parent_no_directory_urls",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_nonindex_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url_nested",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url_nested_no_slash",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_defaults",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url_warning",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_eq",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_ne",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_no_directory_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_render",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_capitalized_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_homepage_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_preserved_attr_list",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_meta",
"mkdocs/tests/structure/page_tests.py::PageTests::test_predefined_page_title",
"mkdocs/tests/structure/page_tests.py::SourceDateEpochTests::test_source_date_epoch",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_win_local_path",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_bad_relative_html_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_email_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_external_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_no_links",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_hash_only",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_parent_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_index_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_page",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_page_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_with_encoded_space",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_with_unencoded_space",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_homepage",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_sibling",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_subpage"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-04-21 20:05:32+00:00
|
bsd-2-clause
| 4,010 |
|
mkdocs__mkdocs-3324
|
diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py
index cb95e741..c0c827ff 100644
--- a/mkdocs/config/config_options.py
+++ b/mkdocs/config/config_options.py
@@ -945,11 +945,18 @@ class ExtraScriptValue(Config):
return self.path
-class ExtraScript(SubConfig[ExtraScriptValue]):
- def run_validation(self, value: object) -> ExtraScriptValue:
+class ExtraScript(BaseConfigOption[Union[ExtraScriptValue, str]]):
+ def __init__(self):
+ super().__init__()
+ self.option_type = SubConfig[ExtraScriptValue]()
+
+ def run_validation(self, value: object) -> ExtraScriptValue | str:
+ self.option_type.warnings = self.warnings
if isinstance(value, str):
- value = {'path': value, 'type': 'module' if value.endswith('.mjs') else ''}
- return super().run_validation(value)
+ if value.endswith('.mjs'):
+ return self.option_type.run_validation({'path': value, 'type': 'module'})
+ return value
+ return self.option_type.run_validation(value)
class MarkdownExtensions(OptionallyRequired[List[str]]):
diff --git a/mkdocs/structure/pages.py b/mkdocs/structure/pages.py
index 34c0bc76..e42faffc 100644
--- a/mkdocs/structure/pages.py
+++ b/mkdocs/structure/pages.py
@@ -437,7 +437,7 @@ class _ExtractTitleTreeprocessor(markdown.treeprocessors.Treeprocessor):
for el in root:
if el.tag == 'h1':
# Drop anchorlink from the element, if present.
- if len(el) > 0 and el[-1].tag == 'a' and not (el.tail or '').strip():
+ if len(el) > 0 and el[-1].tag == 'a' and not (el[-1].tail or '').strip():
el = copy.copy(el)
del el[-1]
# Extract the text only, recursively.
diff --git a/readthedocs.yml b/readthedocs.yml
deleted file mode 100644
index ae64ca7f..00000000
--- a/readthedocs.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-build:
- image: latest
-
-python:
- setup_py_install: true
-
-requirements_file: requirements/project.txt
|
mkdocs/mkdocs
|
fcb2da399f029bd569b708479a39a5f2c700b5a2
|
diff --git a/mkdocs/tests/config/config_options_tests.py b/mkdocs/tests/config/config_options_tests.py
index abd7cb20..6101c2e5 100644
--- a/mkdocs/tests/config/config_options_tests.py
+++ b/mkdocs/tests/config/config_options_tests.py
@@ -9,7 +9,7 @@ import re
import sys
import textwrap
import unittest
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, TypeVar
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, TypeVar, Union
from unittest.mock import patch
if TYPE_CHECKING:
@@ -700,14 +700,14 @@ class ExtraScriptsTest(TestCase):
option = c.ListOfItems(c.ExtraScript(), default=[])
conf = self.get_config(Schema, {'option': ['foo.js', {'path': 'bar.js', 'async': True}]})
- assert_type(conf.option, List[c.ExtraScriptValue])
+ assert_type(conf.option, List[Union[c.ExtraScriptValue, str]])
self.assertEqual(len(conf.option), 2)
- self.assertIsInstance(conf.option[0], c.ExtraScriptValue)
+ self.assertIsInstance(conf.option[1], c.ExtraScriptValue)
self.assertEqual(
- [(x.path, x.type, x.defer, x.async_) for x in conf.option],
+ conf.option,
[
- ('foo.js', '', False, False),
- ('bar.js', '', False, True),
+ 'foo.js',
+ {'path': 'bar.js', 'type': '', 'defer': False, 'async': True},
],
)
@@ -718,14 +718,14 @@ class ExtraScriptsTest(TestCase):
conf = self.get_config(
Schema, {'option': ['foo.mjs', {'path': 'bar.js', 'type': 'module'}]}
)
- assert_type(conf.option, List[c.ExtraScriptValue])
+ assert_type(conf.option, List[Union[c.ExtraScriptValue, str]])
self.assertEqual(len(conf.option), 2)
self.assertIsInstance(conf.option[0], c.ExtraScriptValue)
self.assertEqual(
- [(x.path, x.type, x.defer, x.async_) for x in conf.option],
+ conf.option,
[
- ('foo.mjs', 'module', False, False),
- ('bar.js', 'module', False, False),
+ {'path': 'foo.mjs', 'type': 'module', 'defer': False, 'async': False},
+ {'path': 'bar.js', 'type': 'module', 'defer': False, 'async': False},
],
)
@@ -748,8 +748,8 @@ class ExtraScriptsTest(TestCase):
warnings=dict(option="Sub-option 'foo': Unrecognised configuration name: foo"),
)
self.assertEqual(
- [(x.path, x.type, x.defer, x.async_) for x in conf.option],
- [('foo.js', '', False, False)],
+ conf.option,
+ [{'path': 'foo.js', 'type': '', 'defer': False, 'async': False, 'foo': 'bar'}],
)
|
Unhashable type: 'ExtraScriptValue' Error
I have been encountering the following error when I add an extra_javascript to my yml file:
```
INFO - DeprecationWarning: warning_filter doesn't do anything since MkDocs 1.2 and will be removed soon. All messages on the
`mkdocs` logger get counted automatically.
File
"/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs_print_site_plugin/plugin.py",
line 10, in <module>
from mkdocs.utils import write_file, copy_file, get_relative_url, warning_filter
File
"/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/utils/__init__.py",
line 453, in __getattr__
warnings.warn(
INFO - Building documentation...
INFO - Cleaning site directory
INFO - The following pages exist in the docs directory, but are not included in the "nav" configuration:
- pages/integration/export.md
Traceback (most recent call last):
File "/home/mouhand/work_projects/service-observatory-backend/env/bin/mkdocs", line 8, in <module>
sys.exit(cli())
^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/click/core.py", line 1157, in __call__
return self.main(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/click/core.py", line 1078, in main
rv = self.invoke(ctx)
^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/click/core.py", line 1688, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/click/core.py", line 1434, in invoke
return ctx.invoke(self.callback, **ctx.params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/click/core.py", line 783, in invoke
return __callback(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/__main__.py", line 270, in serve_command
serve.serve(**kwargs)
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/commands/serve.py", line 98, in serve
builder(config)
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/commands/serve.py", line 79, in builder
build(config, live_server=None if is_clean else server, dirty=is_dirty)
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/commands/build.py", line 340, in build
_build_theme_template(template, env, files, config, nav)
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/commands/build.py", line 110, in _build_theme_template
output = _build_template(template_name, template, files, config, nav)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/commands/build.py", line 87, in _build_template
context = config.plugins.on_template_context(context, template_name=name, config=config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/plugins.py", line 555, in on_template_context
return self.run_event(
^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/plugins.py", line 507, in run_event
result = method(item, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs_print_site_plugin/plugin.py", line 288, in on_template_context
self.context['extra_javascript'] = [get_relative_url(f, self.print_page.file.url) for f in config.get('extra_javascript')]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs_print_site_plugin/plugin.py", line 288, in <listcomp>
self.context['extra_javascript'] = [get_relative_url(f, self.print_page.file.url) for f in config.get('extra_javascript')]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/mouhand/work_projects/service-observatory-backend/env/lib/python3.11/site-packages/mkdocs/utils/__init__.py", line 243, in get_relative_url
dest_parts = _norm_parts(url)
^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'ExtraScriptValue'
```
in my mkdocs.yml:
```
extra_javascript:
- javascripts/extra.js
```
|
0.0
|
fcb2da399f029bd569b708479a39a5f2c700b5a2
|
[
"mkdocs/tests/config/config_options_tests.py::ExtraScriptsTest::test_js_async"
] |
[
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_length",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_multiple_types",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_optional_with_default",
"mkdocs/tests/config/config_options_tests.py::TypeTest::test_single_type",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_default",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_invalid_choice",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_invalid_choices",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_invalid_default",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::ChoiceTest::test_required",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_message",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_move",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_move_complex",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_move_existing",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_move_invalid",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_simple",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_with_invalid_type",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_with_type",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_deprecated_option_with_type_undefined",
"mkdocs/tests/config/config_options_tests.py::DeprecatedTest::test_removed_option",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_default_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_format",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_missing_port",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_port",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_range",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_address_type",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_invalid_leading_zeros",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_named_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_unsupported_IPv6_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_unsupported_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_valid_IPv6_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_valid_address",
"mkdocs/tests/config/config_options_tests.py::IpAddressTest::test_valid_full_IPv6_address",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid_type",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_invalid_url",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_valid_url",
"mkdocs/tests/config/config_options_tests.py::URLTest::test_valid_url_is_dir",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_bitbucket",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_custom",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_github",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_gitlab",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_template_errors",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_template_ok",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_edit_uri_template_warning",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_bitbucket",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_custom",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_custom_and_empty_edit_uri",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_github",
"mkdocs/tests/config/config_options_tests.py::EditURITest::test_repo_name_gitlab",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_combined_float_type",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_int_type",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_list_default",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_list_of_optional",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_none_without_default",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_post_validation_error",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_string_not_a_list_of_strings",
"mkdocs/tests/config/config_options_tests.py::ListOfItemsTest::test_warning",
"mkdocs/tests/config/config_options_tests.py::ExtraScriptsTest::test_mjs",
"mkdocs/tests/config/config_options_tests.py::ExtraScriptsTest::test_unknown_key",
"mkdocs/tests/config/config_options_tests.py::ExtraScriptsTest::test_wrong_type",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_all_keys_are_strings",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_combined_float_type",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_dict_default",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_dict_of_optional",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_int_type",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_none_without_default",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_post_validation_error",
"mkdocs/tests/config/config_options_tests.py::DictOfItemsTest::test_string_not_a_dict_of_strings",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_config_dir_prepended",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_dir_bytes",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_incorrect_type_error",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_missing_but_required",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_missing_without_exists",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_not_a_dir",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_not_a_file",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_site_dir_is_config_dir_fails",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_valid_dir",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_valid_file",
"mkdocs/tests/config/config_options_tests.py::FilesystemObjectTest::test_with_unicode",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_empty_list",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_file",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_missing_path",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_non_list",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_non_path",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_none",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_paths_localized_to_config",
"mkdocs/tests/config/config_options_tests.py::ListOfPathsTest::test_valid_path",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_common_prefix",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_doc_dir_in_site_dir",
"mkdocs/tests/config/config_options_tests.py::SiteDirTest::test_site_dir_in_docs_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_inexisting_custom_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_locale",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_locale_invalid_type",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_locale_none",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_post_validation_none_theme_name_and_missing_custom_dir",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_complex_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_simple_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_as_string",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_config_missing_name",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_default",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_invalid_type",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_theme_name_is_none",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_uninstalled_theme_as_config",
"mkdocs/tests/config/config_options_tests.py::ThemeTest::test_uninstalled_theme_as_string",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_children_config_int",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_children_config_none",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_children_empty_dict",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_children_oversized_dict",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_item_int",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_item_none",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_nested_list",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_type_dict",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_invalid_type_int",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_normal_nav",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_old_format",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_provided_dict",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_provided_empty",
"mkdocs/tests/config/config_options_tests.py::NavTest::test_warns_for_dict",
"mkdocs/tests/config/config_options_tests.py::PrivateTest::test_defined",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_config_file_path_pass_through",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_default",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_optional",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_required",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_invalid_option",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_normal",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_unknown_option",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_with_multiple_items",
"mkdocs/tests/config/config_options_tests.py::SubConfigTest::test_subconfig_wrong_type",
"mkdocs/tests/config/config_options_tests.py::NestedSubConfigTest::test_sets_nested_and_not_nested",
"mkdocs/tests/config/config_options_tests.py::NestedSubConfigTest::test_sets_nested_different",
"mkdocs/tests/config/config_options_tests.py::NestedSubConfigTest::test_sets_nested_not_dict",
"mkdocs/tests/config/config_options_tests.py::NestedSubConfigTest::test_sets_only_one_nested",
"mkdocs/tests/config/config_options_tests.py::NestedSubConfigTest::test_unspecified",
"mkdocs/tests/config/config_options_tests.py::NestedSubConfigTest::test_wrong_key_nested",
"mkdocs/tests/config/config_options_tests.py::NestedSubConfigTest::test_wrong_type_nested",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_builtins_config",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_configkey",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_dict_of_dicts",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_duplicates",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_config_option",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_invalid_dict_item",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_list_dicts",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_missing_default",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_mixed_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_multiple_markdown_config_instances",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_none",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_not_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_simple_list",
"mkdocs/tests/config/config_options_tests.py::MarkdownExtensionsTest::test_unknown_extension",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_as_dict",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_empty_list_with_default",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_empty_list_with_empty_default",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_multivalue_dict",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_none_with_default",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_none_with_empty_default",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_not_list",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_not_string_or_dict",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_options_not_dict",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_sub_error",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_sub_warning",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_uninstalled",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_deduced_theme_namespace",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_deduced_theme_namespace_overridden",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_explicit_empty_namespace",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_explicit_theme_namespace",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_multiple_instances",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_multiple_instances_and_warning",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_with_options",
"mkdocs/tests/config/config_options_tests.py::PluginsTest::test_plugin_config_without_options",
"mkdocs/tests/config/config_options_tests.py::HooksTest::test_hooks",
"mkdocs/tests/config/config_options_tests.py::HooksTest::test_hooks_wrong_type",
"mkdocs/tests/config/config_options_tests.py::SchemaTest::test_copy",
"mkdocs/tests/config/config_options_tests.py::SchemaTest::test_subclass"
] |
{
"failed_lite_validators": [
"has_removed_files",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-08-01 17:29:04+00:00
|
bsd-2-clause
| 4,011 |
|
mkdocs__mkdocs-3466
|
diff --git a/mkdocs/config/config_options.py b/mkdocs/config/config_options.py
index aacff403..9b16e302 100644
--- a/mkdocs/config/config_options.py
+++ b/mkdocs/config/config_options.py
@@ -10,6 +10,7 @@ import traceback
import types
import warnings
from collections import Counter, UserString
+from types import SimpleNamespace
from typing import (
Any,
Callable,
@@ -993,6 +994,12 @@ class MarkdownExtensions(OptionallyRequired[List[str]]):
raise ValidationError(f"Invalid config options for Markdown Extension '{ext}'.")
self.configdata[ext] = cfg
+ def pre_validation(self, config, key_name):
+ # To appease validation in case it involves the `!relative` tag.
+ config._current_page = current_page = SimpleNamespace() # type: ignore[attr-defined]
+ current_page.file = SimpleNamespace()
+ current_page.file.src_path = ''
+
def run_validation(self, value: object) -> list[str]:
self.configdata: dict[str, dict] = {}
if not isinstance(value, (list, tuple, dict)):
@@ -1037,6 +1044,7 @@ class MarkdownExtensions(OptionallyRequired[List[str]]):
return extensions
def post_validation(self, config: Config, key_name: str):
+ config._current_page = None # type: ignore[attr-defined]
config[self.configkey] = self.configdata
diff --git a/mkdocs/utils/yaml.py b/mkdocs/utils/yaml.py
index b0c0e7ad..46745eec 100644
--- a/mkdocs/utils/yaml.py
+++ b/mkdocs/utils/yaml.py
@@ -97,12 +97,13 @@ class RelativeDirPlaceholder(_DirPlaceholder):
super().__init__(config, suffix)
def value(self) -> str:
- if self.config._current_page is None:
+ current_page = self.config._current_page
+ if current_page is None:
raise exceptions.ConfigurationError(
"The current file is not set for the '!relative' tag. "
"It cannot be used in this context; the intended usage is within `markdown_extensions`."
)
- return os.path.dirname(self.config._current_page.file.abs_src_path)
+ return os.path.dirname(os.path.join(self.config.docs_dir, current_page.file.src_path))
def get_yaml_loader(loader=yaml.Loader, config: MkDocsConfig | None = None):
|
mkdocs/mkdocs
|
dc45916aa1cc4b4d4796dd45656bd1ff60d4ce44
|
diff --git a/mkdocs/tests/build_tests.py b/mkdocs/tests/build_tests.py
index 275aad37..4b7596bf 100644
--- a/mkdocs/tests/build_tests.py
+++ b/mkdocs/tests/build_tests.py
@@ -814,7 +814,7 @@ class _TestPreprocessor(markdown.preprocessors.Preprocessor):
class _TestExtension(markdown.extensions.Extension):
def __init__(self, base_path: str) -> None:
- self.base_path = base_path
+ self.base_path = str(base_path)
def extendMarkdown(self, md: markdown.Markdown) -> None:
md.preprocessors.register(_TestPreprocessor(self.base_path), "mkdocs_test", priority=32)
|
Wrong example for `!relative` option
The Configuration page lists an example using `pymdownx.snippets` for the `!relative` YAML tag.
The issue with this example is, that the `base_path` option of snippets is expecting a list and not a single String, which breaks the configuration itself.
In fact, the relative option cannot be used by snippets at all it seems.
This error in the documentation should be fixed, as it will otherwise give people the idea, that it can be used with snippets like that...
Or IF it can be used, there should be more clarification on this.
Below is a collection of stacktraces thrown by MkDocs when using `!relative` in different setups:
```yaml
markdown_extensions:
# ...
- pymdownx.snippets:
base_path: !relative
```
<details><summary>Stacktrace</summary>
<p>
```
ERROR - Config value 'markdown_extensions': Failed to load extension 'pymdownx.snippets'.
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\mkdocs\config\config_options.py", line 1021, in run_validation
md.registerExtensions((ext,), self.configdata)
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\markdown\core.py", line 115, in registerExtensions
ext.extendMarkdown(self)
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\pymdownx\snippets.py", line 402, in extendMarkdown
snippet = SnippetPreprocessor(config, md)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\pymdownx\snippets.py", line 85, in __init__
self.base_path = [os.path.abspath(b) for b in base]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'RelativeDirPlaceholder' object is not iterable
Aborted with 1 configuration errors!
ERROR - [21:51:48] An error happened during the rebuild. The server will appear stuck until build errors are resolved.
```
</p>
</details>
```yaml
markdown_extensions:
# ...
- pymdownx.snippets:
base_path:
- !relative
```
<details><summary>Stacktrace</summary>
<p>
```
ERROR - Config value 'markdown_extensions': Failed to load extension 'pymdownx.snippets'.
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\mkdocs\utils\yaml.py", line 52, in __fspath__
return os.path.join(self.value(), self.suffix)
^^^^^^^^^^^^
File "C:\Users\Andreas\AppData\Local\Programs\Python\Python311\Lib\site-packages\mkdocs\utils\yaml.py", line 98, in value
raise exceptions.ConfigurationError(
ConfigurationError: The current file is not set for the '!relative' tag. It cannot be used in this context; the intended usage is within `markdown_extensions`.
Aborted with 1 configuration errors!
ERROR - [21:52:36] An error happened during the rebuild. The server will appear stuck until build errors are resolved.
```
</p>
</details>
|
0.0
|
dc45916aa1cc4b4d4796dd45656bd1ff60d4ce44
|
[
"mkdocs/tests/build_tests.py::BuildTests::test_markdown_extension_with_relative"
] |
[
"mkdocs/tests/build_tests.py::BuildTests::test_build_extra_template",
"mkdocs/tests/build_tests.py::BuildTests::test_build_page",
"mkdocs/tests/build_tests.py::BuildTests::test_build_page_custom_template",
"mkdocs/tests/build_tests.py::BuildTests::test_build_page_dirty_modified",
"mkdocs/tests/build_tests.py::BuildTests::test_build_page_dirty_not_modified",
"mkdocs/tests/build_tests.py::BuildTests::test_build_page_empty",
"mkdocs/tests/build_tests.py::BuildTests::test_build_page_error",
"mkdocs/tests/build_tests.py::BuildTests::test_build_page_plugin_error",
"mkdocs/tests/build_tests.py::BuildTests::test_build_sitemap_template",
"mkdocs/tests/build_tests.py::BuildTests::test_build_theme_template",
"mkdocs/tests/build_tests.py::BuildTests::test_conflicting_readme_and_index",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url__absolute_nested_no_page_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url__absolute_no_page_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url_absolute_nested_no_page",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url_absolute_no_page",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url_homepage",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url_homepage_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url_nested_page",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url_nested_page_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url_relative_no_page",
"mkdocs/tests/build_tests.py::BuildTests::test_context_base_url_relative_no_page_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_context_extra_css_js_from_homepage",
"mkdocs/tests/build_tests.py::BuildTests::test_context_extra_css_js_from_nested_page",
"mkdocs/tests/build_tests.py::BuildTests::test_context_extra_css_js_from_nested_page_use_directory_urls",
"mkdocs/tests/build_tests.py::BuildTests::test_context_extra_css_js_no_page",
"mkdocs/tests/build_tests.py::BuildTests::test_context_extra_css_path_warning",
"mkdocs/tests/build_tests.py::BuildTests::test_copy_theme_files",
"mkdocs/tests/build_tests.py::BuildTests::test_copying_media",
"mkdocs/tests/build_tests.py::BuildTests::test_exclude_pages_with_invalid_links",
"mkdocs/tests/build_tests.py::BuildTests::test_exclude_readme_and_index",
"mkdocs/tests/build_tests.py::BuildTests::test_extra_context",
"mkdocs/tests/build_tests.py::BuildTests::test_not_site_dir_contains_stale_files",
"mkdocs/tests/build_tests.py::BuildTests::test_plugins_adding_files_and_interacting",
"mkdocs/tests/build_tests.py::BuildTests::test_populate_page",
"mkdocs/tests/build_tests.py::BuildTests::test_populate_page_dirty_modified",
"mkdocs/tests/build_tests.py::BuildTests::test_populate_page_dirty_not_modified",
"mkdocs/tests/build_tests.py::BuildTests::test_populate_page_read_error",
"mkdocs/tests/build_tests.py::BuildTests::test_populate_page_read_plugin_error",
"mkdocs/tests/build_tests.py::BuildTests::test_site_dir_contains_stale_files",
"mkdocs/tests/build_tests.py::BuildTests::test_skip_extra_template_empty_output",
"mkdocs/tests/build_tests.py::BuildTests::test_skip_ioerror_extra_template",
"mkdocs/tests/build_tests.py::BuildTests::test_skip_missing_extra_template",
"mkdocs/tests/build_tests.py::BuildTests::test_skip_missing_theme_template",
"mkdocs/tests/build_tests.py::BuildTests::test_skip_theme_template_empty_output"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-11-12 17:02:57+00:00
|
bsd-2-clause
| 4,012 |
|
mkdocs__mkdocs-3564
|
diff --git a/mkdocs/structure/pages.py b/mkdocs/structure/pages.py
index ef13e512..8b0a642d 100644
--- a/mkdocs/structure/pages.py
+++ b/mkdocs/structure/pages.py
@@ -10,6 +10,7 @@ from urllib.parse import unquote as urlunquote
from urllib.parse import urljoin, urlsplit, urlunsplit
import markdown
+import markdown.extensions.toc
import markdown.htmlparser # type: ignore
import markdown.postprocessors
import markdown.treeprocessors
@@ -549,7 +550,7 @@ class _HTMLHandler(markdown.htmlparser.htmlparser.HTMLParser): # type: ignore[n
class _ExtractTitleTreeprocessor(markdown.treeprocessors.Treeprocessor):
title: str | None = None
- postprocessors: Sequence[markdown.postprocessors.Postprocessor] = ()
+ md: markdown.Markdown
def run(self, root: etree.Element) -> etree.Element:
for el in root:
@@ -561,14 +562,15 @@ class _ExtractTitleTreeprocessor(markdown.treeprocessors.Treeprocessor):
# Extract the text only, recursively.
title = ''.join(el.itertext())
# Unescape per Markdown implementation details.
- for pp in self.postprocessors:
- title = pp.run(title)
- self.title = title
+ title = markdown.extensions.toc.stashedHTML2text(
+ title, self.md, strip_entities=False
+ )
+ self.title = title.strip()
break
return root
def _register(self, md: markdown.Markdown) -> None:
- self.postprocessors = tuple(md.postprocessors)
+ self.md = md
md.treeprocessors.register(self, "mkdocs_extract_title", priority=-1) # After the end.
diff --git a/mkdocs/structure/toc.py b/mkdocs/structure/toc.py
index 6d09867b..e1df40be 100644
--- a/mkdocs/structure/toc.py
+++ b/mkdocs/structure/toc.py
@@ -33,7 +33,7 @@ class AnchorLink:
self.children = []
title: str
- """The text of the item."""
+ """The text of the item, as HTML."""
@property
def url(self) -> str:
diff --git a/pyproject.toml b/pyproject.toml
index 28355b73..71bc189e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -36,7 +36,7 @@ dependencies = [
"click >=7.0",
"Jinja2 >=2.11.1",
"markupsafe >=2.0.1",
- "Markdown >=3.3.6",
+ "Markdown >=3.4.1",
"PyYAML >=5.1",
"watchdog >=2.0",
"ghp-import >=1.0",
@@ -57,7 +57,7 @@ min-versions = [
"click ==7.0",
"Jinja2 ==2.11.1",
"markupsafe ==2.0.1",
- "Markdown ==3.3.6",
+ "Markdown ==3.4.1",
"PyYAML ==5.1",
"watchdog ==2.0",
"ghp-import ==1.0",
|
mkdocs/mkdocs
|
d6fcc56a3e2b287a2dc0310a7472ba4cdb177854
|
diff --git a/mkdocs/tests/structure/page_tests.py b/mkdocs/tests/structure/page_tests.py
index ee6aa159..77d8542b 100644
--- a/mkdocs/tests/structure/page_tests.py
+++ b/mkdocs/tests/structure/page_tests.py
@@ -6,9 +6,11 @@ import textwrap
import unittest
from unittest import mock
+import markdown
+
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import File, Files
-from mkdocs.structure.pages import Page, _RelativePathTreeprocessor
+from mkdocs.structure.pages import Page, _ExtractTitleTreeprocessor, _RelativePathTreeprocessor
from mkdocs.tests.base import dedent, tempdir
DOCS_DIR = os.path.join(
@@ -315,9 +317,16 @@ class PageTests(unittest.TestCase):
self.assertEqual(pg.parent, None)
self.assertEqual(pg.previous_page, None)
self.assertEqual(pg.title, 'Welcome to MkDocs')
- pg.render(cfg, fl)
+ pg.render(cfg, Files([fl]))
self.assertEqual(pg.title, 'Welcome to MkDocs')
+ def _test_extract_title(self, content, expected, extensions={}):
+ md = markdown.Markdown(extensions=list(extensions.keys()), extension_configs=extensions)
+ extract_title_ext = _ExtractTitleTreeprocessor()
+ extract_title_ext._register(md)
+ md.convert(content)
+ self.assertEqual(extract_title_ext.title, expected)
+
_SETEXT_CONTENT = dedent(
'''
Welcome to MkDocs Setext
@@ -327,46 +336,37 @@ class PageTests(unittest.TestCase):
'''
)
- @tempdir(files={'testing_setext_title.md': _SETEXT_CONTENT})
- def test_page_title_from_setext_markdown(self, docs_dir):
- cfg = load_config()
- fl = File('testing_setext_title.md', docs_dir, docs_dir, use_directory_urls=True)
- pg = Page(None, fl, cfg)
- self.assertIsNone(pg.title)
- pg.read_source(cfg)
- self.assertEqual(pg.title, 'Testing setext title')
- pg.render(cfg, fl)
- self.assertEqual(pg.title, 'Welcome to MkDocs Setext')
-
- @tempdir(files={'testing_setext_title.md': _SETEXT_CONTENT})
- def test_page_title_from_markdown_stripped_anchorlinks(self, docs_dir):
- cfg = MkDocsConfig()
- cfg.site_name = 'example'
- cfg.markdown_extensions = {'toc': {'permalink': '&'}}
- self.assertEqual(cfg.validate(), ([], []))
- fl = File('testing_setext_title.md', docs_dir, docs_dir, use_directory_urls=True)
- pg = Page(None, fl, cfg)
- pg.read_source(cfg)
- pg.render(cfg, fl)
- self.assertEqual(pg.title, 'Welcome to MkDocs Setext')
+ def test_page_title_from_setext_markdown(self):
+ self._test_extract_title(
+ self._SETEXT_CONTENT,
+ expected='Welcome to MkDocs Setext',
+ )
- _FORMATTING_CONTENT = dedent(
- '''
- # \\*Hello --- *beautiful* `world`
+ def test_page_title_from_markdown_stripped_anchorlinks(self):
+ self._test_extract_title(
+ self._SETEXT_CONTENT,
+ extensions={'toc': {'permalink': '&'}},
+ expected='Welcome to MkDocs Setext',
+ )
- Hi.
- '''
- )
+ def test_page_title_from_markdown_strip_formatting(self):
+ self._test_extract_title(
+ '''# \\*Hello --- *beautiful* `wor<dl>`''',
+ extensions={'smarty': {}},
+ expected='*Hello — beautiful wor<dl>',
+ )
- @tempdir(files={'testing_formatting.md': _FORMATTING_CONTENT})
- def test_page_title_from_markdown_strip_formatting(self, docs_dir):
- cfg = load_config()
- cfg.markdown_extensions.append('smarty')
- fl = File('testing_formatting.md', docs_dir, docs_dir, use_directory_urls=True)
- pg = Page(None, fl, cfg)
- pg.read_source(cfg)
- pg.render(cfg, fl)
- self.assertEqual(pg.title, '*Hello — beautiful world')
+ def test_page_title_from_markdown_strip_raw_html(self):
+ self._test_extract_title(
+ '''# Hello <b>world</b>''',
+ expected='Hello world',
+ )
+
+ def test_page_title_from_markdown_strip_image(self):
+ self._test_extract_title(
+ '''# Hi ''',
+ expected='Hi', # TODO: Should the alt text of the image be extracted?
+ )
_ATTRLIST_CONTENT = dedent(
'''
@@ -376,24 +376,18 @@ class PageTests(unittest.TestCase):
'''
)
- @tempdir(files={'testing_attr_list.md': _ATTRLIST_CONTENT})
- def test_page_title_from_markdown_stripped_attr_list(self, docs_dir):
- cfg = load_config()
- cfg.markdown_extensions.append('attr_list')
- fl = File('testing_attr_list.md', docs_dir, docs_dir, use_directory_urls=True)
- pg = Page(None, fl, cfg)
- pg.read_source(cfg)
- pg.render(cfg, fl)
- self.assertEqual(pg.title, 'Welcome to MkDocs Attr')
+ def test_page_title_from_markdown_stripped_attr_list(self):
+ self._test_extract_title(
+ self._ATTRLIST_CONTENT,
+ extensions={'attr_list': {}},
+ expected='Welcome to MkDocs Attr',
+ )
- @tempdir(files={'testing_attr_list.md': _ATTRLIST_CONTENT})
- def test_page_title_from_markdown_preserved_attr_list(self, docs_dir):
- cfg = load_config()
- fl = File('testing_attr_list.md', docs_dir, docs_dir, use_directory_urls=True)
- pg = Page(None, fl, cfg)
- pg.read_source(cfg)
- pg.render(cfg, fl)
- self.assertEqual(pg.title, 'Welcome to MkDocs Attr { #welcome }')
+ def test_page_title_from_markdown_preserved_attr_list(self):
+ self._test_extract_title(
+ self._ATTRLIST_CONTENT,
+ expected='Welcome to MkDocs Attr { #welcome }',
+ )
def test_page_title_from_meta(self):
cfg = load_config(docs_dir=DOCS_DIR)
@@ -418,7 +412,7 @@ class PageTests(unittest.TestCase):
self.assertEqual(pg.previous_page, None)
self.assertEqual(pg.title, 'A Page Title')
self.assertEqual(pg.toc, [])
- pg.render(cfg, fl)
+ pg.render(cfg, Files([fl]))
self.assertEqual(pg.title, 'A Page Title')
def test_page_title_from_filename(self):
@@ -443,7 +437,7 @@ class PageTests(unittest.TestCase):
self.assertEqual(pg.parent, None)
self.assertEqual(pg.previous_page, None)
self.assertEqual(pg.title, 'Page title')
- pg.render(cfg, fl)
+ pg.render(cfg, Files([fl]))
self.assertEqual(pg.title, 'Page title')
def test_page_title_from_capitalized_filename(self):
@@ -704,7 +698,7 @@ class PageTests(unittest.TestCase):
pg.read_source(cfg)
self.assertEqual(pg.content, None)
self.assertEqual(pg.toc, [])
- pg.render(cfg, [fl])
+ pg.render(cfg, Files([fl]))
self.assertTrue(
pg.content.startswith('<h1 id="welcome-to-mkdocs">Welcome to MkDocs</h1>\n')
)
|
Header and navigation sidebars display incorrectly arbitrary markup
Hello!
## Since when does the bug occur?
I recently upgraded my `mkdocs` package from `1.4.2` to `1.5.2`, and I noticed this bug when...
* I don't specify a page title in `mkdocs.yml` file or in the page metadata (in yaml).
* I use an emoji (HTML in general) in the first level section title in the markdown file:
```md
# Intégration et Déploiement Continu sur :simple-gitlab: Gitlab
```
For example (with `mkdocs-material` theme and `readthedocs` theme):


... while it was displayed like that before:

More generally, some parts like the search page of `readthedocs` theme don't handle well the HTML in title sections.
## External links:
[`readthedocs` theme pictures and bug explanations](https://github.com/squidfunk/mkdocs-material/issues/5893) are from @squidfunk.
|
0.0
|
d6fcc56a3e2b287a2dc0310a7472ba4cdb177854
|
[
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_image",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_raw_html"
] |
[
"mkdocs/tests/structure/page_tests.py::PageTests::test_BOM",
"mkdocs/tests/structure/page_tests.py::PageTests::test_homepage",
"mkdocs/tests/structure/page_tests.py::PageTests::test_missing_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page_no_parent",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page_no_parent_no_directory_urls",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_nonindex_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url_nested",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url_nested_no_slash",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_defaults",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url_custom_from_file",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url_warning",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_eq",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_ne",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_no_directory_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_render",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_capitalized_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_homepage_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_preserved_attr_list",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_formatting",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_stripped_anchorlinks",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_stripped_attr_list",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_meta",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_setext_markdown",
"mkdocs/tests/structure/page_tests.py::PageTests::test_predefined_page_title",
"mkdocs/tests/structure/page_tests.py::SourceDateEpochTests::test_source_date_epoch",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_anchor_link_with_validation",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_anchor_link_with_validation_and_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_preserved_and_warned",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_with_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_with_validation",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_with_validation_and_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_with_validation_just_slash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_self_anchor_link_with_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_self_anchor_link_with_validation_and_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_win_local_path",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_bad_relative_doc_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_email_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_external_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_image_link_with_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_invalid_email_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_no_links",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_possible_target_uris",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_doc_link_without_extension",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_hash_only",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_parent_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_index_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_page",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_page_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_with_encoded_space",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_with_unencoded_space",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_homepage",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_sibling",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_subpage",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_slash_link_with_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_self_anchor_link_with_suggestion"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-02-04 21:26:55+00:00
|
bsd-2-clause
| 4,013 |
|
mkdocs__mkdocs-3578
|
diff --git a/mkdocs/structure/pages.py b/mkdocs/structure/pages.py
index 8b0a642d..5b4a849b 100644
--- a/mkdocs/structure/pages.py
+++ b/mkdocs/structure/pages.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import copy
import enum
import logging
import posixpath
@@ -20,6 +19,7 @@ from mkdocs import utils
from mkdocs.structure import StructureItem
from mkdocs.structure.toc import get_toc
from mkdocs.utils import _removesuffix, get_build_date, get_markdown_title, meta, weak_property
+from mkdocs.utils.rendering import get_heading_text
if TYPE_CHECKING:
from xml.etree import ElementTree as etree
@@ -555,23 +555,13 @@ class _ExtractTitleTreeprocessor(markdown.treeprocessors.Treeprocessor):
def run(self, root: etree.Element) -> etree.Element:
for el in root:
if el.tag == 'h1':
- # Drop anchorlink from the element, if present.
- if len(el) > 0 and el[-1].tag == 'a' and not (el[-1].tail or '').strip():
- el = copy.copy(el)
- del el[-1]
- # Extract the text only, recursively.
- title = ''.join(el.itertext())
- # Unescape per Markdown implementation details.
- title = markdown.extensions.toc.stashedHTML2text(
- title, self.md, strip_entities=False
- )
- self.title = title.strip()
+ self.title = get_heading_text(el, self.md)
break
return root
def _register(self, md: markdown.Markdown) -> None:
self.md = md
- md.treeprocessors.register(self, "mkdocs_extract_title", priority=-1) # After the end.
+ md.treeprocessors.register(self, "mkdocs_extract_title", priority=1) # Close to the end.
class _AbsoluteLinksValidationValue(enum.IntEnum):
diff --git a/mkdocs/utils/rendering.py b/mkdocs/utils/rendering.py
new file mode 100644
index 00000000..545e1efb
--- /dev/null
+++ b/mkdocs/utils/rendering.py
@@ -0,0 +1,104 @@
+from __future__ import annotations
+
+import copy
+from typing import TYPE_CHECKING, Callable
+
+import markdown
+import markdown.treeprocessors
+
+if TYPE_CHECKING:
+ from xml.etree import ElementTree as etree
+
+# TODO: This will become unnecessary after min-versions have Markdown >=3.4
+_unescape: Callable[[str], str]
+try:
+ _unescape = markdown.treeprocessors.UnescapeTreeprocessor().unescape
+except AttributeError:
+ _unescape = lambda s: s
+
+# TODO: Most of this file will become unnecessary after https://github.com/Python-Markdown/markdown/pull/1441
+
+
+def get_heading_text(el: etree.Element, md: markdown.Markdown) -> str:
+ el = copy.deepcopy(el)
+ _remove_anchorlink(el)
+ _remove_fnrefs(el)
+ _extract_alt_texts(el)
+ return _strip_tags(_render_inner_html(el, md))
+
+
+def _strip_tags(text: str) -> str:
+ """Strip HTML tags and return plain text. Note: HTML entities are unaffected."""
+ # A comment could contain a tag, so strip comments first
+ while (start := text.find('<!--')) != -1 and (end := text.find('-->', start)) != -1:
+ text = text[:start] + text[end + 3 :]
+
+ while (start := text.find('<')) != -1 and (end := text.find('>', start)) != -1:
+ text = text[:start] + text[end + 1 :]
+
+ # Collapse whitespace
+ text = ' '.join(text.split())
+ return text
+
+
+def _render_inner_html(el: etree.Element, md: markdown.Markdown) -> str:
+ # The `UnescapeTreeprocessor` runs after `toc` extension so run here.
+ text = md.serializer(el)
+ text = _unescape(text)
+
+ # Strip parent tag
+ start = text.index('>') + 1
+ end = text.rindex('<')
+ text = text[start:end].strip()
+
+ for pp in md.postprocessors:
+ text = pp.run(text)
+ return text
+
+
+def _remove_anchorlink(el: etree.Element) -> None:
+ """Drop anchorlink from the element, if present."""
+ if len(el) > 0 and el[-1].tag == 'a' and el[-1].get('class') == 'headerlink':
+ del el[-1]
+
+
+def _remove_fnrefs(root: etree.Element) -> None:
+ """Remove footnote references from the element, if any are present."""
+ for parent in root.findall('.//sup[@id]/..'):
+ _replace_elements_with_text(parent, _predicate_for_fnrefs)
+
+
+def _predicate_for_fnrefs(el: etree.Element) -> str | None:
+ if el.tag == 'sup' and el.get('id', '').startswith('fnref'):
+ return ''
+ return None
+
+
+def _extract_alt_texts(root: etree.Element) -> None:
+ """For images that have an `alt` attribute, replace them with this content."""
+ for parent in root.findall('.//img[@alt]/..'):
+ _replace_elements_with_text(parent, _predicate_for_alt_texts)
+
+
+def _predicate_for_alt_texts(el: etree.Element) -> str | None:
+ if el.tag == 'img' and (alt := el.get('alt')):
+ return alt
+ return None
+
+
+def _replace_elements_with_text(
+ parent: etree.Element, predicate: Callable[[etree.Element], str | None]
+) -> None:
+ """For each child element, if matched, replace it with the text returned from the predicate."""
+ carry_text = ""
+ for child in reversed(parent): # Reversed for the ability to mutate during iteration.
+ # Remove matching elements but carry any `tail` text to preceding elements.
+ new_text = predicate(child)
+ if new_text is not None:
+ carry_text = new_text + (child.tail or "") + carry_text
+ parent.remove(child)
+ elif carry_text:
+ child.tail = (child.tail or "") + carry_text
+ carry_text = ""
+ if carry_text:
+ parent.text = (parent.text or "") + carry_text
diff --git a/pyproject.toml b/pyproject.toml
index 71bc189e..28355b73 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -36,7 +36,7 @@ dependencies = [
"click >=7.0",
"Jinja2 >=2.11.1",
"markupsafe >=2.0.1",
- "Markdown >=3.4.1",
+ "Markdown >=3.3.6",
"PyYAML >=5.1",
"watchdog >=2.0",
"ghp-import >=1.0",
@@ -57,7 +57,7 @@ min-versions = [
"click ==7.0",
"Jinja2 ==2.11.1",
"markupsafe ==2.0.1",
- "Markdown ==3.4.1",
+ "Markdown ==3.3.6",
"PyYAML ==5.1",
"watchdog ==2.0",
"ghp-import ==1.0",
|
mkdocs/mkdocs
|
e755aaed7ea47348a60495ab364d5483ab90a4a6
|
diff --git a/mkdocs/tests/structure/page_tests.py b/mkdocs/tests/structure/page_tests.py
index 77d8542b..14bb85da 100644
--- a/mkdocs/tests/structure/page_tests.py
+++ b/mkdocs/tests/structure/page_tests.py
@@ -342,6 +342,12 @@ class PageTests(unittest.TestCase):
expected='Welcome to MkDocs Setext',
)
+ def test_page_title_from_markdown_with_email(self):
+ self._test_extract_title(
+ '''# <[email protected]>''',
+ expected='foo@example.org',
+ )
+
def test_page_title_from_markdown_stripped_anchorlinks(self):
self._test_extract_title(
self._SETEXT_CONTENT,
@@ -349,6 +355,24 @@ class PageTests(unittest.TestCase):
expected='Welcome to MkDocs Setext',
)
+ def test_page_title_from_markdown_strip_footnoteref(self):
+ foootnotes = '''\n\n[^1]: foo\n[^2]: bar'''
+ self._test_extract_title(
+ '''# Header[^1] foo[^2] bar''' + foootnotes,
+ extensions={'footnotes': {}},
+ expected='Header foo bar',
+ )
+ self._test_extract_title(
+ '''# *Header[^1]* *foo*[^2]''' + foootnotes,
+ extensions={'footnotes': {}},
+ expected='Header foo',
+ )
+ self._test_extract_title(
+ '''# *Header[^1][^2]s''' + foootnotes,
+ extensions={'footnotes': {}},
+ expected='*Headers',
+ )
+
def test_page_title_from_markdown_strip_formatting(self):
self._test_extract_title(
'''# \\*Hello --- *beautiful* `wor<dl>`''',
@@ -356,17 +380,19 @@ class PageTests(unittest.TestCase):
expected='*Hello — beautiful wor<dl>',
)
+ def test_page_title_from_markdown_html_entity(self):
+ self._test_extract_title('''# Foo < & bar''', expected='Foo < & bar')
+ self._test_extract_title('''# Foo > & bar''', expected='Foo > & bar')
+
def test_page_title_from_markdown_strip_raw_html(self):
- self._test_extract_title(
- '''# Hello <b>world</b>''',
- expected='Hello world',
- )
+ self._test_extract_title('''# Hello <b>world</b>''', expected='Hello world')
+
+ def test_page_title_from_markdown_strip_comments(self):
+ self._test_extract_title('''# foo <!-- comment with <em> --> bar''', expected='foo bar')
def test_page_title_from_markdown_strip_image(self):
- self._test_extract_title(
- '''# Hi ''',
- expected='Hi', # TODO: Should the alt text of the image be extracted?
- )
+ self._test_extract_title('''# Hi ''', expected='Hi 😄')
+ self._test_extract_title('''# Hi *--*''', expected='Hi -😄-')
_ATTRLIST_CONTENT = dedent(
'''
|
Header and navigation sidebars display incorrectly arbitrary markup
Hello!
## Since when does the bug occur?
I recently upgraded my `mkdocs` package from `1.4.2` to `1.5.2`, and I noticed this bug when...
* I don't specify a page title in `mkdocs.yml` file or in the page metadata (in yaml).
* I use an emoji (HTML in general) in the first level section title in the markdown file:
```md
# Intégration et Déploiement Continu sur :simple-gitlab: Gitlab
```
For example (with `mkdocs-material` theme and `readthedocs` theme):


... while it was displayed like that before:

More generally, some parts like the search page of `readthedocs` theme don't handle well the HTML in title sections.
## External links:
[`readthedocs` theme pictures and bug explanations](https://github.com/squidfunk/mkdocs-material/issues/5893) are from @squidfunk.
|
0.0
|
e755aaed7ea47348a60495ab364d5483ab90a4a6
|
[
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_html_entity",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_comments",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_footnoteref",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_image",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_with_email"
] |
[
"mkdocs/tests/structure/page_tests.py::PageTests::test_BOM",
"mkdocs/tests/structure/page_tests.py::PageTests::test_homepage",
"mkdocs/tests/structure/page_tests.py::PageTests::test_missing_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page_no_parent",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_index_page_no_parent_no_directory_urls",
"mkdocs/tests/structure/page_tests.py::PageTests::test_nested_nonindex_page",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url_nested",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_canonical_url_nested_no_slash",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_defaults",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url_custom_from_file",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_edit_url_warning",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_eq",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_ne",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_no_directory_url",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_render",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_capitalized_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_homepage_filename",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_preserved_attr_list",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_formatting",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_strip_raw_html",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_stripped_anchorlinks",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_markdown_stripped_attr_list",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_meta",
"mkdocs/tests/structure/page_tests.py::PageTests::test_page_title_from_setext_markdown",
"mkdocs/tests/structure/page_tests.py::PageTests::test_predefined_page_title",
"mkdocs/tests/structure/page_tests.py::SourceDateEpochTests::test_source_date_epoch",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_anchor_link_with_validation",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_anchor_link_with_validation_and_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_preserved_and_warned",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_with_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_with_validation",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_with_validation_and_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_link_with_validation_just_slash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_self_anchor_link_with_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_self_anchor_link_with_validation_and_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_absolute_win_local_path",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_bad_relative_doc_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_email_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_external_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_image_link_with_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_invalid_email_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_no_links",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_possible_target_uris",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_doc_link_without_extension",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_hash_only",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_parent_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_index",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_index_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_page",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_sub_page_hash",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_with_encoded_space",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_html_link_with_unencoded_space",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_homepage",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_sibling",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_image_link_from_subpage",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_relative_slash_link_with_suggestion",
"mkdocs/tests/structure/page_tests.py::RelativePathExtensionTests::test_self_anchor_link_with_suggestion"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2024-02-24 11:39:39+00:00
|
bsd-2-clause
| 4,014 |
|
mkorpela__overrides-42
|
diff --git a/overrides/enforce.py b/overrides/enforce.py
index 29c97ff..95e8607 100644
--- a/overrides/enforce.py
+++ b/overrides/enforce.py
@@ -27,7 +27,7 @@ class EnforceOverridesMeta(ABCMeta):
@staticmethod
def handle_special_value(value):
- if isinstance(value, classmethod):
+ if isinstance(value, classmethod) or isinstance(value, staticmethod):
value = value.__get__(None, dict)
elif isinstance(value, property):
value = value.fget
|
mkorpela/overrides
|
8cfef0064f9a09c5b7c8d6d7a152455f1de26209
|
diff --git a/tests/test_enforce.py b/tests/test_enforce.py
index c73de72..6566684 100644
--- a/tests/test_enforce.py
+++ b/tests/test_enforce.py
@@ -22,15 +22,17 @@ class Enforcing(EnforceOverrides):
def nonfinal_property(self):
return "super_property"
+ @staticmethod
+ def nonfinal_staticmethod():
+ return "super_staticmethod"
+
@classmethod
def nonfinal_classmethod(cls):
return "super_classmethod"
class EnforceTests(unittest.TestCase):
-
def test_enforcing_when_all_ok(self):
-
class Subclazz(Enforcing):
classVariableIsOk = "OK!"
@@ -72,6 +74,18 @@ class EnforceTests(unittest.TestCase):
self.assertNotEqual(PropertyOverrider.nonfinal_property,
Enforcing.nonfinal_property)
+ def test_enforcing_when_staticmethod_overriden(self):
+ class StaticMethodOverrider(Enforcing):
+ @staticmethod
+ @overrides
+ def nonfinal_staticmethod():
+ return "subclass_staticmethod"
+
+ self.assertNotEqual(
+ StaticMethodOverrider.nonfinal_staticmethod(),
+ Enforcing.nonfinal_staticmethod(),
+ )
+
def test_enforcing_when_classmethod_overriden(self):
class ClassMethodOverrider(Enforcing):
@classmethod
|
@staticmethod doesn't work with @overrides
```
@staticmethod
@overrides
def get_all_statements(player_index: int) -> List[Statement]:
```
AssertionError: Method get_all_statements overrides but does not have @overrides decorator
```
@overrides
@staticmethod
def get_all_statements(player_index: int) -> List[Statement]:
```
@staticmethod
File "/Users/tyleryep/miniconda3/lib/python3.7/site-packages/overrides/overrides.py", line 57, in overrides
for super_class in _get_base_classes(sys._getframe(2), method.__globals__):
AttributeError: 'staticmethod' object has no attribute '__globals__'
|
0.0
|
8cfef0064f9a09c5b7c8d6d7a152455f1de26209
|
[
"tests/test_enforce.py::EnforceTests::test_enforcing_when_staticmethod_overriden"
] |
[
"tests/test_enforce.py::EnforceTests::test_enforcing_when_all_ok",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_classmethod_overriden",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_none_explicit_override",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_property_overriden",
"tests/test_enforce.py::EnforceTests::tests_enforcing_when_finality_broken"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2020-06-16 07:33:48+00:00
|
apache-2.0
| 4,015 |
|
mkorpela__overrides-52
|
diff --git a/overrides/enforce.py b/overrides/enforce.py
index 83b82df..42c35c6 100644
--- a/overrides/enforce.py
+++ b/overrides/enforce.py
@@ -123,6 +123,11 @@ def ensure_return_type_compatibility(super_sig, sub_sig):
class EnforceOverridesMeta(ABCMeta):
def __new__(mcls, name, bases, namespace, **kwargs):
+ # Ignore any methods defined on the metaclass when enforcing overrides.
+ for method in dir(mcls):
+ if not method.startswith("__") and method != "mro":
+ setattr(getattr(mcls, method), "__ignored__", True)
+
cls = super().__new__(mcls, name, bases, namespace, **kwargs)
for name, value in namespace.items():
# Actually checking the direct parent should be enough,
@@ -133,7 +138,7 @@ class EnforceOverridesMeta(ABCMeta):
is_override = getattr(value, "__override__", False)
for base in bases:
base_class_method = getattr(base, name, False)
- if not base_class_method or not callable(base_class_method):
+ if not base_class_method or not callable(base_class_method) or getattr(base_class_method, "__ignored__", False):
continue
assert (
is_override
|
mkorpela/overrides
|
f8179a87450d34f3490bdaaf6df19ee8b771ebd3
|
diff --git a/tests/test_enforce.py b/tests/test_enforce.py
index c624be8..013077b 100644
--- a/tests/test_enforce.py
+++ b/tests/test_enforce.py
@@ -104,6 +104,16 @@ class EnforceTests(unittest.TestCase):
self.assertNotEqual(ClassMethodOverrider.nonfinal_classmethod(),
Enforcing.nonfinal_classmethod())
+ def test_enforcing_when_metaclass_method_overridden(self):
+ class MetaClassMethodOverrider(Enforcing):
+ def register(self):
+ pass
+
+ with self.assertRaises(AssertionError):
+ class SubClass(MetaClassMethodOverrider):
+ def register(self):
+ pass
+
def test_ensure_compatible_when_compatible(self):
def sup(a, /, b: str, c: int, *, d, e, **kwargs) -> object:
pass
@@ -113,7 +123,6 @@ class EnforceTests(unittest.TestCase):
ensure_compatible(sup, sub)
-
def test_ensure_compatible_when_return_types_are_incompatible(self):
def sup(x) -> int:
pass
|
Creating a method with the same name as a method in `EnforceOverridesMeta` raises
Because `register` is defined in `abc.ABCMeta` and `handle_special_value` is defined in `EnforceOverridesMeta`, the code incorrectly determines that classes that redefine these methods are missing an `@overrides` decorator. Instead, `EnforceOverridesMeta` should ignore methods that are missing an `@overrides` decorator if they are defined on `EnforceOverridesMeta`.
```python
class RegisterRepro(overrides.EnforceOverrides):
def register(self):
pass
# AssertionError: Method register overrides but does not have @overrides decorator
```
```python
class HandleSpecialValueRepro(overrides.EnforceOverrides):
def handle_special_value(self):
pass
# AssertionError: Method handle_special_value overrides but does not have @overrides decorator
```
|
0.0
|
f8179a87450d34f3490bdaaf6df19ee8b771ebd3
|
[
"tests/test_enforce.py::EnforceTests::test_enforcing_when_metaclass_method_overridden"
] |
[
"tests/test_enforce.py::EnforceTests::test_enforcing_when_all_ok",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_classmethod_overriden",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_finality_broken",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_incompatible",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_none_explicit_override",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_property_overriden",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_staticmethod_overriden",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_additional_arg",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_compatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_missing_arg",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_parameter_kinds_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_parameter_lists_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_parameter_positions_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_parameter_types_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_return_types_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_union_compatible"
] |
{
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-23 20:50:23+00:00
|
apache-2.0
| 4,016 |
|
mkorpela__overrides-59
|
diff --git a/overrides/enforce.py b/overrides/enforce.py
index 85a45ca..40a5535 100644
--- a/overrides/enforce.py
+++ b/overrides/enforce.py
@@ -2,7 +2,7 @@ import inspect
from abc import ABCMeta
from inspect import Parameter, Signature
from types import FunctionType
-from typing import Callable, TypeVar, Union
+from typing import Callable, TypeVar, Union, get_type_hints
from typing_utils import issubtype # type: ignore
@@ -28,14 +28,16 @@ def ensure_signature_is_compatible(
:param sub_callable: Function to check compatibility of.
"""
super_sig = inspect.signature(super_callable)
+ super_type_hints = get_type_hints(super_callable)
sub_sig = inspect.signature(sub_callable)
+ sub_type_hints = get_type_hints(sub_callable)
- ensure_return_type_compatibility(super_sig, sub_sig)
- ensure_all_args_defined_in_sub(super_sig, sub_sig)
+ ensure_return_type_compatibility(super_type_hints, sub_type_hints)
+ ensure_all_args_defined_in_sub(super_sig, sub_sig, super_type_hints, sub_type_hints)
ensure_no_extra_args_in_sub(super_sig, sub_sig)
-def ensure_all_args_defined_in_sub(super_sig, sub_sig):
+def ensure_all_args_defined_in_sub(super_sig, sub_sig, super_type_hints, sub_type_hints):
sub_has_var_args = any(
p.kind == Parameter.VAR_POSITIONAL for p in sub_sig.parameters.values()
)
@@ -68,9 +70,9 @@ def ensure_all_args_defined_in_sub(super_sig, sub_sig):
elif super_index != sub_index and super_param.kind != Parameter.KEYWORD_ONLY:
raise TypeError(f"`{name}` is not parameter `{super_index}`")
elif (
- super_param.annotation != Parameter.empty
- and sub_param.annotation != Parameter.empty
- and not issubtype(super_param.annotation, sub_param.annotation)
+ name in super_type_hints
+ and name in sub_type_hints
+ and not issubtype(super_type_hints[name], sub_type_hints[name])
):
raise TypeError(
f"`{name} must be a supertype of `{super_param.annotation}`"
@@ -112,14 +114,14 @@ def ensure_no_extra_args_in_sub(super_sig, sub_sig):
raise TypeError(f"`{name}` is not a valid parameter.")
-def ensure_return_type_compatibility(super_sig, sub_sig):
+def ensure_return_type_compatibility(super_type_hints, sub_type_hints):
if (
- super_sig.return_annotation != Signature.empty
- and sub_sig.return_annotation != Signature.empty
- and not issubtype(sub_sig.return_annotation, super_sig.return_annotation)
+ 'return' in super_type_hints
+ and 'return' in sub_type_hints
+ and not issubtype(sub_type_hints['return'], super_type_hints['return'])
):
raise TypeError(
- f"`{sub_sig.return_annotation}` is not a `{super_sig.return_annotation}`."
+ f"`{sub_type_hints['return']}` is not a `{super_type_hints['return']}`."
)
|
mkorpela/overrides
|
74516d8042a95591508199d6ab15b7490bca52fb
|
diff --git a/tests/test_enforce.py b/tests/test_enforce.py
index 99b982e..96c4fed 100644
--- a/tests/test_enforce.py
+++ b/tests/test_enforce.py
@@ -124,6 +124,15 @@ class EnforceTests(unittest.TestCase):
ensure_signature_is_compatible(sup, sub)
+ def test_ensure_compatible_when_type_hints_are_strings(self):
+ def sup(x: "str") -> "object":
+ pass
+
+ def sub(x: "object") -> "str":
+ pass
+
+ ensure_signature_is_compatible(sup, sub)
+
def test_ensure_compatible_when_return_types_are_incompatible(self):
def sup(x) -> int:
pass
|
Signature validation fails when __future__.annotations is imported
When `from __future__ import annotations` is imported, all annotations are converted into strings. Currently, the code incorrectly assumes that type annotations are objects. A simple fix to this problem is to use the `typing.get_type_hints` function in the standard library to extract type hints instead of using `inspect.signature`. This will become the default behavior in Python 3.10, so we will have to do this eventually.
|
0.0
|
74516d8042a95591508199d6ab15b7490bca52fb
|
[
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_type_hints_are_strings"
] |
[
"tests/test_enforce.py::EnforceTests::test_allowed_extra_args_in_overrider",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_all_ok",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_classmethod_overriden",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_finality_broken",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_incompatible",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_metaclass_method_overridden",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_none_explicit_override",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_property_overriden",
"tests/test_enforce.py::EnforceTests::test_enforcing_when_staticmethod_overriden",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_additional_arg",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_compatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_missing_arg",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_parameter_kinds_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_parameter_lists_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_parameter_positions_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_parameter_types_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_ensure_compatible_when_return_types_are_incompatible",
"tests/test_enforce.py::EnforceTests::test_generic_sub",
"tests/test_enforce.py::EnforceTests::test_if_super_has_args_then_sub_must_have",
"tests/test_enforce.py::EnforceTests::test_if_super_has_kwargs_then_sub_must_have",
"tests/test_enforce.py::EnforceTests::test_union_compatible"
] |
{
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-04-24 15:19:30+00:00
|
apache-2.0
| 4,017 |
|
mlenzen__collections-extended-108
|
diff --git a/README.rst b/README.rst
index 5d0137b..c739d4a 100644
--- a/README.rst
+++ b/README.rst
@@ -6,8 +6,8 @@ README
:alt: Build Status
-.. image:: https://coveralls.io/repos/mlenzen/collections-extended/badge.svg?branch=master
- :target: https://coveralls.io/r/mlenzen/collections-extended?branch=master
+.. image:: https://coveralls.io/repos/github/mlenzen/collections-extended/badge.svg?branch=master
+ :target: https://coveralls.io/github/mlenzen/collections-extended?branch=master
:alt: Coverage
Documentation: http://collections-extended.lenzm.net/
diff --git a/collections_extended/_util.py b/collections_extended/_util.py
index f5a81f8..84050a5 100644
--- a/collections_extended/_util.py
+++ b/collections_extended/_util.py
@@ -67,6 +67,11 @@ class Sentinel(object):
NOT_SET = Sentinel('not_set')
+def deprecation_warning(msg):
+ """Raise a deprecation warning."""
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
+
+
def deprecated(msg, dep_version):
"""Decorate a function, method or class to mark as deprecated.
@@ -96,7 +101,7 @@ def deprecated(msg, dep_version):
@wraps(func)
def inner(*args, **kwargs):
- warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
+ deprecation_warning(msg)
return func(*args, **kwargs)
return inner
diff --git a/collections_extended/bags.py b/collections_extended/bags.py
index c23094f..fa67503 100644
--- a/collections_extended/bags.py
+++ b/collections_extended/bags.py
@@ -188,7 +188,7 @@ class _basebag(Set):
@deprecated(
"Use `heapq.nlargest(n, self.counts(), key=itemgetter(1))` instead or "
"`sorted(self.counts(), reverse=True, key=itemgetter(1))` for `n=None`",
- '1.1',
+ '1.0',
)
def nlargest(self, n=None):
"""List the n most common elements and their counts.
diff --git a/collections_extended/indexed_dict.py b/collections_extended/indexed_dict.py
index a1c9275..2b6fc0f 100644
--- a/collections_extended/indexed_dict.py
+++ b/collections_extended/indexed_dict.py
@@ -4,7 +4,7 @@
"""
import collections
-from ._util import NOT_SET
+from ._util import NOT_SET, deprecation_warning
__all__ = ('IndexedDict', )
@@ -33,38 +33,82 @@ class IndexedDict(collections.MutableMapping):
self._dict = {}
self._list = []
- def get(self, key=NOT_SET, index=NOT_SET, d=None):
- """Return value with given key or index.
+ def get(self, key=NOT_SET, index=NOT_SET, default=NOT_SET, d=NOT_SET):
+ """Return value with given `key` or `index`.
- If no value is found, return d (None by default).
+ If no value is found, return `default` (`None` by default).
+
+ .. deprecated :: 1.1
+ The `d` parameter has been renamed `default`. `d` will be removed in
+ some future version.
+
+ Args:
+ key: The key of the value to get
+ index: The index of the value to get
+ default: The value to return if `key` is not found or `index` is
+ out of bounds. If it is NOT_SET, None is returned.
+ d: DEPRECATED: Old parameter name for `default`
"""
+ if d is not NOT_SET:
+ if default is not NOT_SET:
+ raise ValueError('Specified default and d')
+ deprecation_warning(
+ "IndexedDict.pop parameter 'd' has been renamed to 'default'"
+ )
+ default = d
+ if default is NOT_SET:
+ default = None
+
if index is NOT_SET and key is not NOT_SET:
try:
index, value = self._dict[key]
except KeyError:
- return d
+ return default
else:
return value
elif index is not NOT_SET and key is NOT_SET:
try:
key, value = self._list[index]
except IndexError:
- return d
+ return default
else:
return value
else:
raise KEY_EQ_INDEX_ERROR
- def pop(self, key=NOT_SET, index=NOT_SET, d=NOT_SET):
- """Remove and return value with given key or index (last item by default).
+ def pop(self, key=NOT_SET, index=NOT_SET, default=NOT_SET, d=NOT_SET):
+ """Remove and return value.
+
+ Optionally, specify the `key` or `index` of the value to pop.
+ If `key` is specified and is not found a `KeyError` is raised unless
+ `default` is specified. Likewise, if `index` is specified that is out of
+ bounds, an `IndexError` is raised unless `default` is specified.
- If key is not found, returns d if given,
- otherwise raises KeyError or IndexError.
+ Both `index` and `key` cannot be specified. If neither is specified,
+ then the last value is popped.
This is generally O(N) unless removing last item, then O(1).
- """
- has_default = d is not NOT_SET
+ .. deprecated :: 1.1
+ The `d` parameter has been renamed `default`. `d` will be removed in
+ some future version.
+
+ Args:
+ key: The key of the value to pop
+ index: The index of the value to pop
+ default: The value to return if the key is not found or the index is
+ out of bounds
+ d: DEPRECATED: Old parameter name for `default`
+ """
+ if d is not NOT_SET:
+ if default is not NOT_SET:
+ raise ValueError('Specified default and d')
+ deprecation_warning(
+ "IndexedDict.pop parameter 'd' has been renamed to 'default'"
+ )
+ default = d
+
+ has_default = default is not NOT_SET
if index is NOT_SET and key is not NOT_SET:
index, value = self._pop_key(key, has_default)
elif key is NOT_SET:
@@ -73,7 +117,7 @@ class IndexedDict(collections.MutableMapping):
raise KEY_AND_INDEX_ERROR
if index is None:
- return d
+ return default
else:
self._fix_indices_after_delete(index)
return value
|
mlenzen/collections-extended
|
490b8457266f40a0268aab3e038733ebe2a2020f
|
diff --git a/tests/test_bags.py b/tests/test_bags.py
index 0e66f01..43f9d39 100644
--- a/tests/test_bags.py
+++ b/tests/test_bags.py
@@ -66,10 +66,8 @@ def test_nlargest():
def test_nlargest_deprecated():
"""Test that nlargest raises a DeprecationWarning."""
b = bag()
- with warnings.catch_warnings():
- warnings.simplefilter('error')
- with pytest.raises(DeprecationWarning):
- b.nlargest()
+ with pytest.deprecated_call():
+ b.nlargest()
def test_from_map():
diff --git a/tests/test_indexed_dict.py b/tests/test_indexed_dict.py
index af5f81e..b6c1f0e 100644
--- a/tests/test_indexed_dict.py
+++ b/tests/test_indexed_dict.py
@@ -1,6 +1,3 @@
-# pylint: disable=redefined-outer-name
-# pylint: disable=W0212
-
import pytest
from collections_extended.indexed_dict import IndexedDict
@@ -11,7 +8,7 @@ def assert_internal_state(self):
Returns True, so it can be used in an assert expression itself."""
assert len(self._dict) == len(self._list)
- for k, (i, v) in self._dict.items():
+ for k, (i, v) in self._dict.items(): # noqa
k2, v2 = self._list[i]
assert k2 == k
assert v2 is v
@@ -61,11 +58,32 @@ def test_get_key_found(d, indexing):
assert d.get(**indexing) == 11
[email protected]("indexing", [{"key": "x"}, {"index": 100}, {"index": -6}])
+def test_get_specifying_missing_default(d, indexing):
+ assert d.get(default=5, **indexing) == 5
+
+
+def test_get_deprecated_param(d):
+ with pytest.deprecated_call():
+ assert d.get('x', d='XXX') == 'XXX'
+
+
@pytest.mark.parametrize("indexing", [{"key": "x"}, {"index": 100}, {"index": -6}])
def test_get_missing_default(d, indexing):
assert d.get(**indexing) is None
+def test_get_duplicate_default(d):
+ with pytest.raises(ValueError):
+ d.get(d=None, default=None)
+ with pytest.raises(ValueError):
+ d.get(d='XXX', default=None)
+ with pytest.raises(ValueError):
+ d.get(d=None, default='XXX')
+ with pytest.raises(ValueError):
+ d.get(d='XXX', default='XXX')
+
+
def test_get_both_key_and_index(d):
with pytest.raises(TypeError):
d.get(key="a", index=4)
@@ -93,6 +111,11 @@ def test_pop_missing_default(d, indexing):
assert list(d) == list("abcde")
+def test_pop_duplicate_default(d):
+ with pytest.raises(ValueError):
+ d.pop(d='XXX', default='XXX')
+
+
def test_pop_missing_key_no_default(d):
with pytest.raises(KeyError):
d.pop("X")
@@ -106,6 +129,11 @@ def test_pop_missing_index_no_default(d, index):
assert list(d) == list("abcde")
+def test_deprecated_pop_default(d):
+ with pytest.deprecated_call():
+ assert d.pop(999, d='XXX') == 'XXX'
+
+
def test_pop_empty_default():
d = IndexedDict()
assert d.pop(d="XXX") == "XXX"
|
Rename `d` arguments to `default` in indexed_dict
|
0.0
|
490b8457266f40a0268aab3e038733ebe2a2020f
|
[
"tests/test_indexed_dict.py::test_get_specifying_missing_default[indexing0]",
"tests/test_indexed_dict.py::test_get_specifying_missing_default[indexing1]",
"tests/test_indexed_dict.py::test_get_specifying_missing_default[indexing2]",
"tests/test_indexed_dict.py::test_get_deprecated_param",
"tests/test_indexed_dict.py::test_get_duplicate_default",
"tests/test_indexed_dict.py::test_pop_duplicate_default",
"tests/test_indexed_dict.py::test_deprecated_pop_default"
] |
[
"tests/test_bags.py::test_init",
"tests/test_bags.py::test_repr",
"tests/test_bags.py::test_str",
"tests/test_bags.py::test_count",
"tests/test_bags.py::test_nlargest",
"tests/test_bags.py::test_nlargest_deprecated",
"tests/test_bags.py::test_from_map",
"tests/test_bags.py::test_copy",
"tests/test_bags.py::test_len",
"tests/test_bags.py::test_contains",
"tests/test_bags.py::test_compare_eq_set[-]",
"tests/test_bags.py::test_compare_eq_set[a-a]",
"tests/test_bags.py::test_compare_eq_set[ab-ab]",
"tests/test_bags.py::test_compare_ne_set[ab-a]",
"tests/test_bags.py::test_compare_ne_set[a-ab]",
"tests/test_bags.py::test_compare_ne_set[aa-a]",
"tests/test_bags.py::test_compare_ne_set[aa-ab]",
"tests/test_bags.py::test_compare_ne_set[ac-ab]",
"tests/test_bags.py::test_compare_unorderable",
"tests/test_bags.py::test_rich_comp_equal",
"tests/test_bags.py::test_rich_comp_superset",
"tests/test_bags.py::test_rich_comp_subset",
"tests/test_bags.py::test_rich_comp_unorderable_eq_len",
"tests/test_bags.py::test_rich_comp_unorderable_diff_len",
"tests/test_bags.py::test_rich_comp_type_mismatch",
"tests/test_bags.py::test_comparison_chaining",
"tests/test_bags.py::test_and",
"tests/test_bags.py::test_isdisjoint",
"tests/test_bags.py::test_or",
"tests/test_bags.py::test_add_op",
"tests/test_bags.py::test_add",
"tests/test_bags.py::test_clear",
"tests/test_bags.py::test_discard",
"tests/test_bags.py::test_sub",
"tests/test_bags.py::test_mul",
"tests/test_bags.py::test_mul_empty_set",
"tests/test_bags.py::test_product",
"tests/test_bags.py::test_product_commutative",
"tests/test_bags.py::test_xor",
"tests/test_bags.py::test_ior",
"tests/test_bags.py::test_iand",
"tests/test_bags.py::test_ixor",
"tests/test_bags.py::test_isub",
"tests/test_bags.py::test_remove_all",
"tests/test_bags.py::test_iadd",
"tests/test_bags.py::test_hash",
"tests/test_bags.py::test_num_unique_elems",
"tests/test_bags.py::test_pop",
"tests/test_bags.py::test_hashability",
"tests/test_indexed_dict.py::test_empty_construction",
"tests/test_indexed_dict.py::test_dict_construction",
"tests/test_indexed_dict.py::test_kwargs_construction",
"tests/test_indexed_dict.py::test_tuples_construction",
"tests/test_indexed_dict.py::test_clear",
"tests/test_indexed_dict.py::test_get_key_found[indexing0]",
"tests/test_indexed_dict.py::test_get_key_found[indexing1]",
"tests/test_indexed_dict.py::test_get_key_found[indexing2]",
"tests/test_indexed_dict.py::test_get_missing_default[indexing0]",
"tests/test_indexed_dict.py::test_get_missing_default[indexing1]",
"tests/test_indexed_dict.py::test_get_missing_default[indexing2]",
"tests/test_indexed_dict.py::test_get_both_key_and_index",
"tests/test_indexed_dict.py::test_get_no_key_or_index",
"tests/test_indexed_dict.py::test_pop_found[indexing0]",
"tests/test_indexed_dict.py::test_pop_found[indexing1]",
"tests/test_indexed_dict.py::test_pop_found[indexing2]",
"tests/test_indexed_dict.py::test_pop_last",
"tests/test_indexed_dict.py::test_pop_missing_default[indexing0]",
"tests/test_indexed_dict.py::test_pop_missing_default[indexing1]",
"tests/test_indexed_dict.py::test_pop_missing_default[indexing2]",
"tests/test_indexed_dict.py::test_pop_missing_key_no_default",
"tests/test_indexed_dict.py::test_pop_missing_index_no_default[100]",
"tests/test_indexed_dict.py::test_pop_missing_index_no_default[-6]",
"tests/test_indexed_dict.py::test_pop_empty_default",
"tests/test_indexed_dict.py::test_pop_empty_no_default",
"tests/test_indexed_dict.py::test_pop_both_key_and_index",
"tests/test_indexed_dict.py::test_fast_pop_found[indexing0]",
"tests/test_indexed_dict.py::test_fast_pop_found[indexing1]",
"tests/test_indexed_dict.py::test_fast_pop_found[indexing2]",
"tests/test_indexed_dict.py::test_fast_pop_last",
"tests/test_indexed_dict.py::test_fast_pop_last_key",
"tests/test_indexed_dict.py::test_fast_pop_missing_key",
"tests/test_indexed_dict.py::test_fast_pop_missing_index",
"tests/test_indexed_dict.py::test_fast_pop_empty",
"tests/test_indexed_dict.py::test_fast_pop_both_key_and_index",
"tests/test_indexed_dict.py::test_popitem",
"tests/test_indexed_dict.py::test_popitem_first",
"tests/test_indexed_dict.py::test_popitem_empty",
"tests/test_indexed_dict.py::test_copy",
"tests/test_indexed_dict.py::test_move_to_end_key_found[indexing0]",
"tests/test_indexed_dict.py::test_move_to_end_key_found[indexing1]",
"tests/test_indexed_dict.py::test_move_to_end_key_found[indexing2]",
"tests/test_indexed_dict.py::test_move_to_end_noop",
"tests/test_indexed_dict.py::test_move_to_begin_key_found[indexing0]",
"tests/test_indexed_dict.py::test_move_to_begin_key_found[indexing1]",
"tests/test_indexed_dict.py::test_move_to_begin_key_found[indexing2]",
"tests/test_indexed_dict.py::test_move_to_begin_noop",
"tests/test_indexed_dict.py::test_move_to_end_missing_key",
"tests/test_indexed_dict.py::test_move_to_end_missing_index[100]",
"tests/test_indexed_dict.py::test_move_to_end_missing_index[-6]",
"tests/test_indexed_dict.py::test_move_to_end_both_key_and_index",
"tests/test_indexed_dict.py::test_move_to_end_no_key_or_index",
"tests/test_indexed_dict.py::test_index",
"tests/test_indexed_dict.py::test_index_missing",
"tests/test_indexed_dict.py::test_key",
"tests/test_indexed_dict.py::test_key_negative",
"tests/test_indexed_dict.py::test_key_missing",
"tests/test_indexed_dict.py::test_len",
"tests/test_indexed_dict.py::test_getitem",
"tests/test_indexed_dict.py::test_getitem_missing",
"tests/test_indexed_dict.py::test_setitem_overwrite",
"tests/test_indexed_dict.py::test_setitem_create",
"tests/test_indexed_dict.py::test_delitem",
"tests/test_indexed_dict.py::test_delitem_missing",
"tests/test_indexed_dict.py::test_contains",
"tests/test_indexed_dict.py::test_keys",
"tests/test_indexed_dict.py::test_values",
"tests/test_indexed_dict.py::test_none_key",
"tests/test_indexed_dict.py::test_repr"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-08-17 05:25:39+00:00
|
apache-2.0
| 4,018 |
|
mlenzen__collections-extended-152
|
diff --git a/HISTORY.rst b/HISTORY.rst
index c371394..ac95bf9 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -34,6 +34,8 @@ Added
Fixed
"""""
+* tuples passed to the bijection constructor must have len == 2, not >= 2
+
Deprecated
""""""""""
diff --git a/collections_extended/bijection.py b/collections_extended/bijection.py
index 5547bf6..591216a 100644
--- a/collections_extended/bijection.py
+++ b/collections_extended/bijection.py
@@ -25,7 +25,8 @@ class bijection(MutableMapping):
self[key] = value
else:
for pair in iterable:
- self[pair[0]] = pair[1]
+ key, value = pair
+ self[key] = value
for key, value in kwarg.items():
self[key] = value
|
mlenzen/collections-extended
|
28bffb3c5193544013c5047bca45292a3dfe8223
|
diff --git a/tests/test_bijection.py b/tests/test_bijection.py
index 576cd77..48af061 100644
--- a/tests/test_bijection.py
+++ b/tests/test_bijection.py
@@ -34,6 +34,11 @@ def test_init_from_pairs():
assert bijection({'a': 1, 'b': 2}) == bijection((('a', 1), ('b', 2)))
+def test_init_from_triples_fails():
+ with pytest.raises(ValueError):
+ bijection((('a', 1, 0), ('b', 2, 0), ))
+
+
def test_repr():
"""Test __repr__."""
b = bijection()
|
bijection.__init__ tuples need to be len == 2
|
0.0
|
28bffb3c5193544013c5047bca45292a3dfe8223
|
[
"tests/test_bijection.py::test_init_from_triples_fails"
] |
[
"tests/test_bijection.py::test_bijection",
"tests/test_bijection.py::test_init_from_pairs",
"tests/test_bijection.py::test_repr",
"tests/test_bijection.py::test_setting_value",
"tests/test_bijection.py::test_iter",
"tests/test_bijection.py::test_clear"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2021-06-10 05:54:52+00:00
|
apache-2.0
| 4,019 |
|
mlouielu__twstock-35
|
diff --git a/twstock/stock.py b/twstock/stock.py
index 842c4ff..ba2f706 100644
--- a/twstock/stock.py
+++ b/twstock/stock.py
@@ -1,10 +1,12 @@
# -*- coding: utf-8 -*-
import datetime
-import json
import urllib.parse
from collections import namedtuple
-import sys
+try:
+ from json.decoder import JSONDecodeError
+except ImportError:
+ JSONDecodeError = ValueError
import requests
@@ -43,23 +45,19 @@ class TWSEFetcher(BaseFetcher):
def __init__(self):
pass
- def fetch(self, year: int, month: int, sid: str, retry=5):
+ def fetch(self, year: int, month: int, sid: str, retry: int=5):
params = {'date': '%d%02d01' % (year, month), 'stockNo': sid}
- r = requests.get(self.REPORT_URL, params=params)
- if sys.version_info < (3, 5):
+ for retry_i in range(retry):
+ r = requests.get(self.REPORT_URL, params=params)
try:
data = r.json()
- except ValueError:
- if retry:
- return self.fetch(year, month, sid, retry - 1)
- data = {'stat': '', 'data': []}
+ except JSONDecodeError:
+ continue
+ else:
+ break
else:
- try:
- data = r.json()
- except json.decoder.JSONDecodeError:
- if retry:
- return self.fetch(year, month, sid, retry - 1)
- data = {'stat': '', 'data': []}
+ # Fail in all retries
+ data = {'stat': '', 'data': []}
if data['stat'] == 'OK':
data['data'] = self.purify(data)
@@ -71,16 +69,17 @@ class TWSEFetcher(BaseFetcher):
data[0] = datetime.datetime.strptime(self._convert_date(data[0]), '%Y/%m/%d')
data[1] = int(data[1].replace(',', ''))
data[2] = int(data[2].replace(',', ''))
- data[3] = float(data[3].replace(',', ''))
- data[4] = float(data[4].replace(',', ''))
- data[5] = float(data[5].replace(',', ''))
- data[6] = float(data[6].replace(',', ''))
- data[7] = float(0.0 if data[7].replace(',', '') == 'X0.00' else data[7].replace(',', '')) # +/-/X表示漲/跌/不比價
+ data[3] = None if data[3] == '--' else float(data[3].replace(',', ''))
+ data[4] = None if data[4] == '--' else float(data[4].replace(',', ''))
+ data[5] = None if data[5] == '--' else float(data[5].replace(',', ''))
+ data[6] = None if data[6] == '--' else float(data[6].replace(',', ''))
+ # +/-/X表示漲/跌/不比價
+ data[7] = float(0.0 if data[7].replace(',', '') == 'X0.00' else data[7].replace(',', ''))
data[8] = int(data[8].replace(',', ''))
return DATATUPLE(*data)
def purify(self, original_data):
- return [self._make_datatuple(d) for d in original_data['data'] if d[3] != '--']
+ return [self._make_datatuple(d) for d in original_data['data']]
class TPEXFetcher(BaseFetcher):
@@ -90,10 +89,19 @@ class TPEXFetcher(BaseFetcher):
def __init__(self):
pass
- def fetch(self, year: int, month: int, sid: str):
+ def fetch(self, year: int, month: int, sid: str, retry: int=5):
params = {'d': '%d/%d' % (year - 1911, month), 'stkno': sid}
- r = requests.get(self.REPORT_URL, params=params)
- data = r.json()
+ for retry_i in range(retry):
+ r = requests.get(self.REPORT_URL, params=params)
+ try:
+ data = r.json()
+ except JSONDecodeError:
+ continue
+ else:
+ break
+ else:
+ # Fail in all retries
+ data = {'aaData': []}
data['data'] = []
if data['aaData']:
@@ -108,10 +116,10 @@ class TPEXFetcher(BaseFetcher):
data[0] = datetime.datetime.strptime(self._convert_date(data[0]), '%Y/%m/%d')
data[1] = int(data[1].replace(',', '')) * 1000
data[2] = int(data[2].replace(',', '')) * 1000
- data[3] = float(data[3].replace(',', ''))
- data[4] = float(data[4].replace(',', ''))
- data[5] = float(data[5].replace(',', ''))
- data[6] = float(data[6].replace(',', ''))
+ data[3] = None if data[3] == '--' else float(data[3].replace(',', ''))
+ data[4] = None if data[4] == '--' else float(data[4].replace(',', ''))
+ data[5] = None if data[5] == '--' else float(data[5].replace(',', ''))
+ data[6] = None if data[6] == '--' else float(data[6].replace(',', ''))
data[7] = float(data[7].replace(',', ''))
data[8] = int(data[8].replace(',', ''))
return DATATUPLE(*data)
|
mlouielu/twstock
|
80320e0163414195b3859620c892237ed47a4304
|
diff --git a/test/test_stock.py b/test/test_stock.py
index ea4c7b6..92fbbd2 100644
--- a/test/test_stock.py
+++ b/test/test_stock.py
@@ -23,6 +23,20 @@ class FetcherTest(object):
self.assertEqual(dt.change, 2.0)
self.assertEqual(dt.transaction, 15718)
+ def test_make_datatuple_without_prices(self):
+ data = ['106/05/02', '45,851,963', '9,053,856,108', '--',
+ '--', '--', '--', ' 0.00', '15,718']
+ dt = self.fetcher._make_datatuple(data)
+ self.assertEqual(dt.date, datetime.datetime(2017, 5, 2))
+ self.assertEqual(dt.capacity, 45851963)
+ self.assertEqual(dt.turnover, 9053856108)
+ self.assertEqual(dt.open, None)
+ self.assertEqual(dt.high, None)
+ self.assertEqual(dt.low, None)
+ self.assertEqual(dt.close, None)
+ self.assertEqual(dt.change, 0.0)
+ self.assertEqual(dt.transaction, 15718)
+
class TWSEFetcerTest(unittest.TestCase, FetcherTest):
fetcher = stock.TWSEFetcher()
@@ -33,7 +47,7 @@ class TPEXFetcherTest(unittest.TestCase, FetcherTest):
def test_make_datatuple(self):
data = ['106/05/02', '45,851', '9,053,856', '198.50',
- '199.00', '195.50', '196.50', '+2.00', '15,718']
+ '199.00', '195.50', '196.50', '2.00', '15,718']
dt = self.fetcher._make_datatuple(data)
self.assertEqual(dt.date, datetime.datetime(2017, 5, 2))
self.assertEqual(dt.capacity, 45851000)
@@ -45,6 +59,20 @@ class TPEXFetcherTest(unittest.TestCase, FetcherTest):
self.assertEqual(dt.change, 2.0)
self.assertEqual(dt.transaction, 15718)
+ def test_make_datatuple_without_prices(self):
+ data = ['106/05/02', '45,851', '9,053,856', '--',
+ '--', '--', '--', '0.00', '15,718']
+ dt = self.fetcher._make_datatuple(data)
+ self.assertEqual(dt.date, datetime.datetime(2017, 5, 2))
+ self.assertEqual(dt.capacity, 45851000)
+ self.assertEqual(dt.turnover, 9053856000)
+ self.assertEqual(dt.open, None)
+ self.assertEqual(dt.high, None)
+ self.assertEqual(dt.low, None)
+ self.assertEqual(dt.close, None)
+ self.assertEqual(dt.change, 0.0)
+ self.assertEqual(dt.transaction, 15718)
+
class StockTest(object):
def test_fetch_31(self):
|
2017 12/18 大樹(6469) Error
2017 12/18 大樹(6469) ,當天無交易量,證交所的資料為 '--'
程式會出現 Error。
希望能自動拿前一天的收盤價取代表示。
|
0.0
|
80320e0163414195b3859620c892237ed47a4304
|
[
"test/test_stock.py::TWSEFetcerTest::test_make_datatuple_without_prices",
"test/test_stock.py::TPEXFetcherTest::test_make_datatuple_without_prices"
] |
[
"test/test_stock.py::TWSEFetcerTest::test_convert_date",
"test/test_stock.py::TWSEFetcerTest::test_make_datatuple",
"test/test_stock.py::TPEXFetcherTest::test_convert_date",
"test/test_stock.py::TPEXFetcherTest::test_make_datatuple",
"test/test_stock.py::TWSEStockTest::test_capacity",
"test/test_stock.py::TWSEStockTest::test_change",
"test/test_stock.py::TWSEStockTest::test_close",
"test/test_stock.py::TWSEStockTest::test_date",
"test/test_stock.py::TWSEStockTest::test_fetch_31",
"test/test_stock.py::TWSEStockTest::test_high",
"test/test_stock.py::TWSEStockTest::test_low",
"test/test_stock.py::TWSEStockTest::test_open",
"test/test_stock.py::TWSEStockTest::test_price",
"test/test_stock.py::TWSEStockTest::test_transaction",
"test/test_stock.py::TWSEStockTest::test_turnover",
"test/test_stock.py::TPEXStockTest::test_capacity",
"test/test_stock.py::TPEXStockTest::test_change",
"test/test_stock.py::TPEXStockTest::test_close",
"test/test_stock.py::TPEXStockTest::test_date",
"test/test_stock.py::TPEXStockTest::test_fetch_31",
"test/test_stock.py::TPEXStockTest::test_high",
"test/test_stock.py::TPEXStockTest::test_low",
"test/test_stock.py::TPEXStockTest::test_open",
"test/test_stock.py::TPEXStockTest::test_price",
"test/test_stock.py::TPEXStockTest::test_transaction",
"test/test_stock.py::TPEXStockTest::test_turnover"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-03-14 15:54:08+00:00
|
mit
| 4,020 |
|
mlrun__mlrun-27
|
diff --git a/mlrun/db/httpd.py b/mlrun/db/httpd.py
index e9c53354..1ed01fcd 100644
--- a/mlrun/db/httpd.py
+++ b/mlrun/db/httpd.py
@@ -20,7 +20,6 @@ from http import HTTPStatus
from flask import Flask, jsonify, request
-from mlrun.artifacts import Artifact
from mlrun.db import RunDBError
from mlrun.db.filedb import FileRunDB
from mlrun.utils import logger
@@ -218,15 +217,10 @@ def store_artifact(project, uid):
_file_db.store_artifact(key, data, uid, tag, project)
return jsonify(ok=True)
-# curl http://localhost:8080/artifact/p1&key=k&tag=t
[email protected]('/artifact/<project>/<uid>', methods=['GET'])
+# curl http://localhost:8080/artifact/p1/tag/key
[email protected]('/artifact/<project>/<tag>/<path:key>', methods=['GET'])
@catch_err
-def read_artifact(project, uid):
- key = request.args.get('key')
- if not key:
- return json_error(HTTPStatus.BAD_REQUEST, reason='missing data')
-
- tag = request.args.get('tag', '')
+def read_artifact(project, tag, key):
data = _file_db.read_artifact(key, tag, project)
return data
diff --git a/mlrun/db/httpdb.py b/mlrun/db/httpdb.py
index cf516fff..6080a32c 100644
--- a/mlrun/db/httpdb.py
+++ b/mlrun/db/httpdb.py
@@ -93,13 +93,13 @@ class HTTPRunDB(RunDBInterface):
path = self._path_of('run', project, uid)
error = f'store run {project}/{uid}'
params = {'commit': bool2str(commit)}
- body = dict_to_json(struct)
+ body = _as_json(struct)
self._api_call('POST', path, error, params, body=body)
def update_run(self, updates: dict, uid, project=''):
path = self._path_of('run', project, uid)
error = f'update run {project}/{uid}'
- body = dict_to_json(updates)
+ body = _as_json(updates)
self._api_call('PATCH', path, error, body=body)
def read_run(self, uid, project=''):
@@ -149,17 +149,17 @@ class HTTPRunDB(RunDBInterface):
}
error = f'store artifact {project}/{uid}'
+
+ body = _as_json(artifact)
self._api_call(
- 'POST', path, error, params=params, body=dict_to_json(artifact))
+ 'POST', path, error, params=params, body=body)
def read_artifact(self, key, tag='', project=''):
- path = self._path_of('artifact', project, key) # TODO: uid?
- params = {
- 'key': key,
- 'tag': tag,
- }
+ project = project or default_project
+ tag = tag or 'latest'
+ path = self._path_of('artifact', project, tag, key)
error = f'read artifact {project}/{key}'
- resp = self._api_call('GET', path, error, params=params)
+ resp = self._api_call('GET', path, error)
return resp.content
def del_artifact(self, key, tag='', project=''):
@@ -197,3 +197,10 @@ class HTTPRunDB(RunDBInterface):
}
error = 'del artifacts'
self._api_call('DELETE', 'artifacts', error, params=params)
+
+
+def _as_json(obj):
+ fn = getattr(obj, 'to_json', None)
+ if fn:
+ return fn()
+ return dict_to_json(obj)
|
mlrun/mlrun
|
bb4b1fd00e08134004e8723ec32af9f52c06eb63
|
diff --git a/tests/test_httpdb.py b/tests/test_httpdb.py
index e432064e..88b04ccd 100644
--- a/tests/test_httpdb.py
+++ b/tests/test_httpdb.py
@@ -157,7 +157,7 @@ def test_artifact(create_server):
db = server.conn
prj, uid, key, body = 'p7', 'u199', 'k800', 'cucumber'
- artifact = Artifact(key, body).to_dict()
+ artifact = Artifact(key, body)
db.store_artifact(key, artifact, uid, project=prj)
# TODO: Need a run file
@@ -168,7 +168,7 @@ def test_artifacts(create_server):
server: Server = create_server()
db = server.conn
prj, uid, key, body = 'p9', 'u19', 'k802', 'tomato'
- artifact = Artifact(key, body).to_dict()
+ artifact = Artifact(key, body)
db.store_artifact(key, artifact, uid, project=prj)
artifacts = db.list_artifacts(project=prj)
|
httpd/db artifacts broken
@tebeka the artifacts get/store etc is broken
a. you must use the `artifact.to_json()` vs dumps like in filedb, since `to_json()` accounts for model details, also `body` is not stored in the DB
b. artifacts object path should be `/artifact/<project>/<uid/tag>/<key>' (key not as arg)
, (uid/tag is like a git tree and can also list all keys in a tree)
https://github.com/mlrun/mlrun/blob/0935dda40fb3a5db551a4b4e269adbac4813a792/mlrun/db/httpdb.py#L142
|
0.0
|
bb4b1fd00e08134004e8723ec32af9f52c06eb63
|
[
"tests/test_httpdb.py::test_artifact",
"tests/test_httpdb.py::test_artifacts"
] |
[
"tests/test_httpdb.py::test_log",
"tests/test_httpdb.py::test_run",
"tests/test_httpdb.py::test_runs",
"tests/test_httpdb.py::test_basic_auth",
"tests/test_httpdb.py::test_bearer_auth"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-10-10 13:52:43+00:00
|
apache-2.0
| 4,021 |
|
mmerickel__wired-2
|
diff --git a/CHANGES.rst b/CHANGES.rst
index 8f65c20..971a172 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -3,6 +3,9 @@ unreleased
- Add support for Python 3.7.
+- Fix an issue where two different service classes with the same name would
+ be treated as the same service, defeating the type-based lookup.
+
0.1.1 (2018-08-04)
==================
diff --git a/src/wired/container.py b/src/wired/container.py
index 84d7726..37ea146 100644
--- a/src/wired/container.py
+++ b/src/wired/container.py
@@ -418,9 +418,10 @@ def _iface_for_type(obj):
return iface
# make a new iface and cache it on the object
- name = obj.__name__
+ name = obj.__qualname__
iface = InterfaceClass(
- '%s_IService' % name, __doc__='service_factory generated interface'
+ '%s_%s_IService' % (name, id(obj)),
+ __doc__='service_factory generated interface',
)
obj._service_iface = iface
return iface
|
mmerickel/wired
|
f6367cc7c9566e4bf42ecefaa33f07fa5bef692c
|
diff --git a/tests/test_container.py b/tests/test_container.py
index a27c16b..144ce00 100644
--- a/tests/test_container.py
+++ b/tests/test_container.py
@@ -204,3 +204,16 @@ def test_unregistered_lookup(registry):
with pytest.raises(LookupError):
c.get(IBarService) # IFooService is not specific enough
assert c.get(IBarService, default=marker) is marker
+
+
+def test_unique_class_objects_with_same_name_dont_conflict(registry):
+ def make_class():
+ class Greeter:
+ pass
+
+ return Greeter
+
+ ClassA = make_class()
+ ClassB = make_class()
+ registry.register_singleton(ClassA(), ClassA)
+ assert registry.find_factory(ClassB) is None
|
Lookup by class (instead of name) doesn't use fully qualified name
I just did this in a test and was surprised it passed:
```python
# from wired.samples.simple_factory import Greeter
class Greeter:
pass
factory = registry.find_factory(Greeter)
```
I have a registry with wired.samples.simple_factory.Greeter registered. I made a local Greeter, expecting it to fail on lookup. It passed.
It appears `wired` only uses the class name, thus two different classes, same name but different modules/packages, would be considered "the same".
|
0.0
|
f6367cc7c9566e4bf42ecefaa33f07fa5bef692c
|
[
"tests/test_container.py::test_unique_class_objects_with_same_name_dont_conflict"
] |
[
"tests/test_container.py::test_sentinel_repr",
"tests/test_container.py::test_various_params[contexts0--Interface]",
"tests/test_container.py::test_various_params[contexts0--IFooService]",
"tests/test_container.py::test_various_params[contexts0--DummyService]",
"tests/test_container.py::test_various_params[contexts0-foo-Interface]",
"tests/test_container.py::test_various_params[contexts0-foo-IFooService]",
"tests/test_container.py::test_various_params[contexts0-foo-DummyService]",
"tests/test_container.py::test_various_params[contexts1--Interface]",
"tests/test_container.py::test_various_params[contexts1--IFooService]",
"tests/test_container.py::test_various_params[contexts1--DummyService]",
"tests/test_container.py::test_various_params[contexts1-foo-Interface]",
"tests/test_container.py::test_various_params[contexts1-foo-IFooService]",
"tests/test_container.py::test_various_params[contexts1-foo-DummyService]",
"tests/test_container.py::test_various_params[contexts2--Interface]",
"tests/test_container.py::test_various_params[contexts2--IFooService]",
"tests/test_container.py::test_various_params[contexts2--DummyService]",
"tests/test_container.py::test_various_params[contexts2-foo-Interface]",
"tests/test_container.py::test_various_params[contexts2-foo-IFooService]",
"tests/test_container.py::test_various_params[contexts2-foo-DummyService]",
"tests/test_container.py::test_various_params[contexts3--Interface]",
"tests/test_container.py::test_various_params[contexts3--IFooService]",
"tests/test_container.py::test_various_params[contexts3--DummyService]",
"tests/test_container.py::test_various_params[contexts3-foo-Interface]",
"tests/test_container.py::test_various_params[contexts3-foo-IFooService]",
"tests/test_container.py::test_various_params[contexts3-foo-DummyService]",
"tests/test_container.py::test_basic_caching",
"tests/test_container.py::test_basic_singletons",
"tests/test_container.py::test_bind_context",
"tests/test_container.py::test_different_contexts_in_nested_lookup",
"tests/test_container.py::test_override_cache_via_set",
"tests/test_container.py::test_override_cache_via_set_fails",
"tests/test_container.py::test_find_factory",
"tests/test_container.py::test_unregistered_factory_lookup",
"tests/test_container.py::test_unregistered_lookup"
] |
{
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-03-23 16:26:39+00:00
|
mit
| 4,022 |
|
mmngreco__IneqPy-17
|
diff --git a/ineqpy/api.py b/ineqpy/api.py
index 07167e1..fab2179 100644
--- a/ineqpy/api.py
+++ b/ineqpy/api.py
@@ -1,22 +1,18 @@
-"""This module extend pandas.DataFrames with the main functions from statistics and
-inequality modules.
+"""This module extend pandas.DataFrames with the main functions from statistics
+and inequality modules.
"""
-from . import _statistics
from . import inequality
from . import statistics
-from . import utils
-from .statistics import mean
from functools import partial
from types import MethodType
import inspect
-import numpy as np
import pandas as pd
-class Convey(pd.DataFrame):
+class Convey:
def __init__(
self,
data=None,
@@ -26,9 +22,7 @@ class Convey(pd.DataFrame):
group=None,
**kw
):
- super(Convey, self).__init__(
- data=data, index=index, columns=columns, **kw
- )
+ self.df = pd.DataFrame(data=data, index=index, columns=columns, **kw)
self.weights = weights
self.group = group
self._attach_method(statistics, self)
@@ -38,12 +32,13 @@ class Convey(pd.DataFrame):
def _constructor(self):
return Survey
- @staticmethod
+ @classmethod
def _attach_method(module, instance):
# get methods names contained in module
res_names = list()
res_methods = list()
method_name_list = inspect.getmembers(module, inspect.isfunction)
+
for method_name, func in method_name_list:
# if method_name.startswith('_'): continue # avoid private methods
func = getattr(module, method_name) # get function
@@ -57,10 +52,8 @@ class Convey(pd.DataFrame):
res_names.append(method_name)
setattr(instance, method_name, func)
- _constructor_sliced = pd.Series
-
-class Survey(pd.DataFrame):
+class Survey:
def __init__(
self,
data=None,
@@ -70,18 +63,10 @@ class Survey(pd.DataFrame):
group=None,
**kw
):
- super(Survey, self).__init__(
- data=data, index=index, columns=columns, **kw
- )
+ self.df = pd.DataFrame(data=data, index=index, columns=columns, **kw)
self.weights = weights
self.group = group
- @property
- def _constructor(self):
- return Survey
-
- _constructor_sliced = pd.Series
-
def c_moment(
self, variable=None, weights=None, order=2, param=None, ddof=0
):
@@ -120,9 +105,12 @@ class Survey(pd.DataFrame):
Implement: https://en.wikipedia.org/wiki/L-moment#cite_note-wang:96-6
"""
+ data = self.df
+
if weights is None:
weights = self.weights
- return statistics.c_moment(variable, weights, self, order, param, ddof)
+
+ return statistics.c_moment(variable, weights, data, order, param, ddof)
def percentile(
self, variable=None, weights=None, p=50, interpolate="lower"
@@ -144,9 +132,10 @@ class Survey(pd.DataFrame):
percentile : float or pd.Series
"""
+ data = self.df
if weights is None:
weights = self.weights
- return statistics.percentile(variable, weights, self, p, interpolate)
+ return statistics.percentile(variable, weights, data, p, interpolate)
def std_moment(
self, variable=None, weights=None, param=None, order=3, ddof=0
@@ -186,10 +175,11 @@ class Survey(pd.DataFrame):
implementation.
"""
+ data = self.df
if weights is None:
weights = self.weights
return statistics.std_moment(
- variable, weights, self, param, order, ddof
+ variable, weights, data, param, order, ddof
)
def mean(self, variable=None, weights=None):
@@ -211,9 +201,10 @@ class Survey(pd.DataFrame):
mean : array-like or float
"""
# if pass a DataFrame separate variables.
+ data = self.df
if weights is None:
weights = self.weights
- return statistics.mean(variable, weights, self)
+ return statistics.mean(variable, weights, data)
def density(self, variable=None, weights=None, groups=None):
"""Calculates density in percentage. This make division of variable
@@ -237,9 +228,10 @@ class Survey(pd.DataFrame):
Retrieved:
https://en.wikipedia.org/w/index.php?title=Histogram&oldid=779516918
"""
+ data = self.df
if weights is None:
weights = self.weights
- return statistics.density(variable, weights, groups, self)
+ return statistics.density(variable, weights, groups, data)
def var(self, variable=None, weights=None, ddof=0):
"""Calculate the population variance of `variable` given `weights`.
@@ -271,9 +263,10 @@ class Survey(pd.DataFrame):
-----
If stratificated sample must pass with groupby each strata.
"""
+ data = self.df
if weights is None:
weights = self.weights
- return statistics.var(variable, weights, self, ddof)
+ return statistics.var(variable, weights, data, ddof)
def coef_variation(self, variable=None, weights=None):
"""Calculate the coefficient of variation of a `variable` given weights.
@@ -301,9 +294,10 @@ class Survey(pd.DataFrame):
oldid=778842331
"""
# TODO complete docstring
+ data = self.df
if weights is None:
weights = self.weights
- return statistics.coef_variation(variable, weights, self)
+ return statistics.coef_variation(variable, weights, data)
def kurt(self, variable=None, weights=None):
"""Calculate the asymmetry coefficient
@@ -330,9 +324,10 @@ class Survey(pd.DataFrame):
-----
It is an alias of the standardized fourth-order moment.
"""
+ data = self.df
if weights is None:
weights = self.weights
- return statistics.kurt(variable, weights, self)
+ return statistics.kurt(variable, weights, data)
def skew(self, variable=None, weights=None):
"""Returns the asymmetry coefficient of a sample.
@@ -361,9 +356,10 @@ class Survey(pd.DataFrame):
It is an alias of the standardized third-order moment.
"""
+ data = self.df
if weights is None:
weights = self.weights
- return statistics.skew(variable, weights, self)
+ return statistics.skew(variable, weights, data)
# INEQUALITY
# ----------
@@ -394,9 +390,10 @@ class Survey(pd.DataFrame):
from micro-data. National Tax Journal. http://doi.org/10.2307/41788716
"""
# TODO complete docstring
+ data = self.df
if weights is None:
weights = self.weights
- return inequality.concentration(income, weights, self, sort)
+ return inequality.concentration(income, weights, data, sort)
def lorenz(self, income=None, weights=None):
"""In economics, the Lorenz curve is a graphical representation of the
@@ -430,11 +427,12 @@ class Survey(pd.DataFrame):
Retrieved 14:34, May 15, 2017, from
https://en.wikipedia.org/w/index.php?title=Lorenz_curve&oldid=764853675
"""
+ data = self.df
if weights is None:
weights = self.weights
if income is None:
income = self.income
- return inequality.lorenz(income, weights, self)
+ return inequality.lorenz(income, weights, data)
def gini(self, income=None, weights=None, sort=True):
"""The Gini coefficient (sometimes expressed as a Gini ratio or a
@@ -490,9 +488,10 @@ class Survey(pd.DataFrame):
- Implement statistical deviation calculation, VAR (GINI)
"""
+ data = self.df
if weights is None:
weights = self.weights
- return inequality.gini(income, weights, self, sort)
+ return inequality.gini(income, weights, data, sort)
def atkinson(self, income=None, weights=None, e=0.5):
"""More precisely labelled a family of income grouped measures, the
@@ -538,9 +537,10 @@ class Survey(pd.DataFrame):
http://www.jstor.org/stable/41788716
- The results has difference with stata, maybe have a bug.
"""
+ data = self.df
if weights is None:
weights = self.weights
- return inequality.atkinson(income, weights, self, e)
+ return inequality.atkinson(income, weights, data, e)
def kakwani(self, tax=None, income_pre_tax=None, weights=None):
"""The Kakwani (1977) index of tax progressivity is defined as twice the
@@ -576,9 +576,10 @@ class Survey(pd.DataFrame):
micro-data. National Tax Journal. http://doi.org/10.2307/41788716
"""
# main calc
+ data = self.df
if weights is None:
weights = self.weights
- return inequality.kakwani(tax, income_pre_tax, weights, self)
+ return inequality.kakwani(tax, income_pre_tax, weights, data)
def reynolds_smolensky(
self, income_pre_tax=None, income_post_tax=None, weights=None
@@ -614,10 +615,11 @@ class Survey(pd.DataFrame):
Jenkins, S. (1988). Calculating income distribution indices from
micro-data. National Tax Journal. http://doi.org/10.2307/41788716
"""
+ data = self.df
if weights is None:
weights = self.weights
return inequality.reynolds_smolensky(
- income_pre_tax, income_post_tax, weights, self
+ income_pre_tax, income_post_tax, weights, data
)
def theil(self, income=None, weights=None):
@@ -650,9 +652,11 @@ class Survey(pd.DataFrame):
https://en.wikipedia.org/w/index.php?title=Theil_index&oldid=755407818
"""
+ data = self.df
if weights is None:
weights = self.weights
- return inequality.theil(income, weights, self)
+
+ return inequality.theil(income, weights, data)
def avg_tax_rate(self, total_tax=None, total_base=None, weights=None):
"""This function compute the average tax rate given a base income and a
@@ -675,6 +679,8 @@ class Survey(pd.DataFrame):
(2011). Panel de declarantes de IRPF 1999-2007:
Metodología, estructura y variables. Documentos.
"""
+ data = self.df
if weights is None:
weights = self.weights
- return inequality.avg_tax_rate(total_tax, total_base, weights, self)
+
+ return inequality.avg_tax_rate(total_tax, total_base, weights, data)
diff --git a/ineqpy/inequality.py b/ineqpy/inequality.py
index de8ffdf..1bd07ab 100644
--- a/ineqpy/inequality.py
+++ b/ineqpy/inequality.py
@@ -96,16 +96,20 @@ def lorenz(income, weights=None, data=None):
total_income = income * weights
idx_sort = np.argsort(income)
+
weights = weights[idx_sort].cumsum() / weights.sum()
weights = weights.reshape(len(weights), 1)
+
total_income = total_income[idx_sort].cumsum() / total_income.sum()
total_income = total_income.reshape(len(total_income), 1)
- res = pd.DataFrame(
- np.c_[weights, total_income],
- columns=["Equality", "Income"],
- index=weights,
- )
+
+ # to pandas
+ data = np.hstack([weights, total_income])
+ columns = ["Equality", "Income"]
+ index = pd.Index(weights.round(3).squeeze())
+ res = pd.DataFrame(data=data, columns=columns, index=index)
res.index.name = "x"
+
return res
|
mmngreco/IneqPy
|
0223d5fb125a6561633c9849817c1b299da84a4e
|
diff --git a/tests/test_api.py b/tests/test_api.py
index 47c37ee..cdfbf2a 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -1,5 +1,6 @@
-import numpy as np
import ineqpy
+import numpy as np
+import pandas as pd
def test_api():
@@ -7,17 +8,34 @@ def test_api():
# only checks that all methods works.
svy = ineqpy.api.Survey
data = np.random.randint(0, 100, (int(1e3), 3))
- w = np.random.randint(1, 10, int(1e3))
- data = np.c_[data, w]
+ w = np.random.randint(1, 10, int(1e3)).reshape(-1, 1)
+ data = np.hstack([data, w])
columns = list("abcw")
+ try:
+ df = svy(data=data, columns=columns, weights="w")
+ df.weights
+ df.mean("a")
+ df.var("a")
+ df.skew("a")
+ df.kurt("a")
+ df.gini("a")
+ df.atkinson("a")
+ df.theil("a")
+ df.percentile("a")
+ assert True
+ except Exception as e:
+ assert False, e
+
+
+def test_df():
+ # GH #15
+ LEN = 10
+ values = [np.arange(LEN), np.random.randint(1, 10, LEN)]
+ df = pd.DataFrame(values, index=["x", "n"]).T
- df = svy(data=data, columns=columns, weights="w")
- df.weights
- df.mean("a")
- df.var("a")
- df.skew("a")
- df.kurt("a")
- df.gini("a")
- df.atkinson("a")
- df.theil("a")
- df.percentile("a")
+ try:
+ svy = ineqpy.api.Survey(df, df.index, df.columns, weights="n")
+ svy.lorenz("x")
+ assert True
+ except Exception as e:
+ assert False, e
|
Can not retrieve DataFrame
Hello,
this works:
svy.lorenz('Reduced.Lunch').plot(legend=False,colors=['silver', 'black'])
BUT I can not get the data frame!!!
svy.lorenz('Reduced.Lunch') gives me:
AttributeError: 'numpy.ndarray' object has no attribute 'endswith'
Can you help me ?
|
0.0
|
0223d5fb125a6561633c9849817c1b299da84a4e
|
[
"tests/test_api.py::test_df"
] |
[
"tests/test_api.py::test_api"
] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-11-15 19:09:49+00:00
|
mit
| 4,023 |
|
mocobeta__janome-49
|
diff --git a/janome/lattice.py b/janome/lattice.py
index 27a2046..0a9388d 100644
--- a/janome/lattice.py
+++ b/janome/lattice.py
@@ -100,7 +100,7 @@ class EOS(object):
class Lattice:
def __init__(self, size, dic):
self.snodes = [[BOS()]] + [[] for i in range(0, size + 1)]
- self.enodes = [[], [BOS()]] + [[] for i in range(0, size + 2)]
+ self.enodes = [[], [BOS()]] + [[] for i in range(0, size + 1)]
self.conn_costs = [[]]
self.p = 1
self.dic = dic
diff --git a/janome/tokenizer.py b/janome/tokenizer.py
index 5606c90..ccc476b 100644
--- a/janome/tokenizer.py
+++ b/janome/tokenizer.py
@@ -141,7 +141,7 @@ class Tokenizer:
A Tokenizer tokenizes Japanese texts with system and optional user defined dictionary.
It is strongly recommended to re-use a Tokenizer object because object initialization cost is high.
"""
- MAX_CHUNK_SIZE = 1000
+ MAX_CHUNK_SIZE = 1024
CHUNK_SIZE = 500
def __init__(self, udic='', udic_enc='utf8', udic_type='ipadic', max_unknown_length=1024, wakati=False, mmap=False):
@@ -212,7 +212,7 @@ class Tokenizer:
lattice = Lattice(chunk_size, self.sys_dic)
pos = 0
while not self.__should_split(text, pos):
- encoded_partial_text = text[pos:pos+min(50, len(text)-pos)].encode('utf-8')
+ encoded_partial_text = text[pos:pos+min(50, chunk_size-pos)].encode('utf-8')
# user dictionary
if self.user_dic:
entries = self.user_dic.lookup(encoded_partial_text)
@@ -238,7 +238,7 @@ class Tokenizer:
assert length >= 0
# buffer for unknown word
buf = text[pos]
- for p in range(pos + 1, min(len(text), pos + length + 1)):
+ for p in range(pos + 1, min(chunk_size, pos + length + 1)):
_cates = self.sys_dic.get_char_categories(text[p])
if cate in _cates or any(cate in _compat_cates for _compat_cates in _cates.values()):
buf += text[p]
|
mocobeta/janome
|
b1c84b062152769ec80fbbe02fb856d2858f28a3
|
diff --git a/tests/test_lattice.py b/tests/test_lattice.py
index cf4b890..14d6a66 100644
--- a/tests/test_lattice.py
+++ b/tests/test_lattice.py
@@ -33,7 +33,7 @@ class TestLattice(unittest.TestCase):
lattice = Lattice(5, SYS_DIC)
self.assertEqual(7, len(lattice.snodes))
self.assertTrue(isinstance(lattice.snodes[0][0], BOS))
- self.assertEqual(9, len(lattice.enodes))
+ self.assertEqual(8, len(lattice.enodes))
self.assertTrue(isinstance(lattice.enodes[1][0], BOS))
def test_add_forward_end(self):
diff --git a/tests/test_tokenizer.py b/tests/test_tokenizer.py
index cc249d2..1928cf5 100644
--- a/tests/test_tokenizer.py
+++ b/tests/test_tokenizer.py
@@ -173,6 +173,13 @@ class TestTokenizer(unittest.TestCase):
text = unicode(text)
tokens = Tokenizer().tokenize(text)
+ def test_tokenize_large_text3(self):
+ with open('tests/text_large_nonjp.txt', encoding='utf-8') as f:
+ text = f.read()
+ if not PY3:
+ text = unicode(text)
+ tokens = Tokenizer().tokenize(text)
+
def test_tokenize_large_text_stream(self):
with open('tests/text_lemon.txt', encoding='utf-8') as f:
text = f.read()
@@ -187,6 +194,13 @@ class TestTokenizer(unittest.TestCase):
text = unicode(text)
tokens = list(Tokenizer().tokenize(text, stream = True))
+ def test_tokenize_large_text_stream3(self):
+ with open('tests/text_large_nonjp.txt', encoding='utf-8') as f:
+ text = f.read()
+ if not PY3:
+ text = unicode(text)
+ tokens = list(Tokenizer().tokenize(text, stream = True))
+
def test_tokenize_wakati(self):
text = u'すもももももももものうち'
tokens = Tokenizer(wakati = True).tokenize(text, wakati = True)
diff --git a/tests/text_large_nonjp.txt b/tests/text_large_nonjp.txt
new file mode 100644
index 0000000..fa61527
--- /dev/null
+++ b/tests/text_large_nonjp.txt
@@ -0,0 +1,1 @@
+longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglongtext
|
IndexError: list index out of rangeと表示されます。
卒業制作でクローラーを制作しながらPythonを勉強しているのですが、このようなエラーが出て困っています。何が原因なのかさっぱりわからないのでお力を貸して頂けないでしょうか?
よろしくお願いします。
文字列として渡す値に問題があるような気がするのですが、リスト配列からはみ出ているというのがよくわかりません。
**エラー内容**
```
Traceback (most recent call last):
File "/vagrant/pysearch-master/manage.py", line 15, in <module>
crawl_web('https://news.google.com/news/headlines?hl=ja&ned=jp', 3)
File "/vagrant/pysearch-master/web_crawler/crawler.py", line 137, in crawl_web
add_page_to_index(page_url, html)
File "/vagrant/pysearch-master/web_crawler/crawler.py", line 121, in add_page_to_index
for word in _split_to_word(line): #janomeで日本語形態解析して単語をwordに代入
File "/vagrant/pysearch-master/web_crawler/crawler.py", line 45, in _split_to_word
return [token.surface for token in t.tokenize(text)]
File "/home/vagrant/.virtualenvs/dev/local/lib/python3.4/site-packages/janome/tokenizer.py", line 193, in tokenize
return list(self.__tokenize_stream(text, wakati))
File "/home/vagrant/.virtualenvs/dev/local/lib/python3.4/site-packages/janome/tokenizer.py", line 200, in __tokenize_stream
tokens, pos = self.__tokenize_partial(text[processed:], wakati)
File "/home/vagrant/.virtualenvs/dev/local/lib/python3.4/site-packages/janome/tokenizer.py", line 254, in __tokenize_partial
lattice.end()
File "/home/vagrant/.virtualenvs/dev/local/lib/python3.4/site-packages/janome/lattice.py", line 154, in end
self.add(eos)
File "/home/vagrant/.virtualenvs/dev/local/lib/python3.4/site-packages/janome/lattice.py", line 140, in add
node.index = len(self.snodes[self.p])
IndexError: list index out of range
```
**htmlからbody以下にあるタグの中にあるテキストを解析に渡す**
```
def add_page_to_index(url, html):
body_soup = BeautifulSoup(html, "html.parser").find('body')
#htmlないの属性タグとその中身をchild_tagに入れていってる<body>以下にある全てのタグ<a>やら<th>やらを持ってくる。
#先ずはbodyより下のhtml全部持ってきて次にその下のdivを持ってきてul持ってきてどんどん掘り下げる感じ
#if body_soup.findChildren() is not None:
for child_tag in body_soup.findChildren():
#beautifulsoupの機能でタグの名前だけ取り出してる。スクリプトだけは避ける。それ以降の処理がスキップされてループに戻る
if child_tag.name == 'script': #child_tag.nameタグの名前を取り出す
continue
#.textはそのタグの中身を表示する。<a>link</a>だったらlinkだけとりだす。
child_text = child_tag.text
for line in child_text.split('\n'): #文字列から改行を取り除いて分ける。
line = line.rstrip().lstrip() #上のコードだけだと両端の空白が消せないからここで削除している。実際には削除はできないので取り除いたのを返している
for word in _split_to_word(line): #janomeで日本語形態解析して単語をwordに代入
add_to_index(word, url)
```
**add_page_to_indexで文字列で受け取ったテキストを解析して単語にして返す**
```
def _split_to_word(text):
"""Japanese morphological analysis with janome.
Splitting text and creating words list.
"""
t = Tokenizer()
#token.surfaceで日本語の文字だけ取り出せる。例えば車は高いだったら"車" "は" "高い" だけ取り出せる。
return [token.surface for token in t.tokenize(text)]
```
|
0.0
|
b1c84b062152769ec80fbbe02fb856d2858f28a3
|
[
"tests/test_lattice.py::TestLattice::test_initialize_lattice",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_large_text3",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_large_text_stream3"
] |
[
"tests/test_lattice.py::TestLattice::test_add_forward_end",
"tests/test_lattice.py::TestLattice::test_add_forward_end_mmap",
"tests/test_lattice.py::TestLattice::test_backward",
"tests/test_lattice.py::TestLattice::test_backward_mmap",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize2",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_large_text",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_large_text2",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_large_text_stream",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_large_text_stream2",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_mmap",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_unknown",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_unknown_no_baseform",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_wakati",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_wakati_mode_only",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_with_simplified_userdic",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_with_userdic",
"tests/test_tokenizer.py::TestTokenizer::test_tokenize_with_userdic_wakati"
] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2017-12-06 15:37:39+00:00
|
apache-2.0
| 4,024 |
|
modernatx__seqlike-76
|
diff --git a/seqlike/codon_tables.py b/seqlike/codon_tables.py
index 349b764..0849d4e 100644
--- a/seqlike/codon_tables.py
+++ b/seqlike/codon_tables.py
@@ -79,13 +79,13 @@ CODON_TABLE = {
}
# https://github.com/Edinburgh-Genome-Foundry/codon-usage-tables/blob/master/codon_usage_data/tables/h_sapiens_9606.csv
-human_codon_table = get_codons_table("h_sapiens_9606")
+human_codon_table = get_codons_table("h_sapiens_9606").copy()
# https://github.com/Edinburgh-Genome-Foundry/codon-usage-tables/blob/master/codon_usage_data/tables/s_cerevisiae_4932.csv
-yeast_codon_table = get_codons_table("s_cerevisiae_4932")
+yeast_codon_table = get_codons_table("s_cerevisiae_4932").copy()
# https://github.com/Edinburgh-Genome-Foundry/codon-usage-tables/blob/master/codon_usage_data/tables/e_coli_316407.csv
-ecoli_codon_table = get_codons_table("e_coli_316407")
+ecoli_codon_table = get_codons_table("e_coli_316407").copy()
random_codon_table = {
"*": {"TAA": 0.33, "TAG": 0.33, "TGA": 0.33},
|
modernatx/seqlike
|
1859afc419b6f530d37ff849f4b76cd8576b8bd8
|
diff --git a/tests/test_codon_tables.py b/tests/test_codon_tables.py
index d7c449d..2a78b85 100644
--- a/tests/test_codon_tables.py
+++ b/tests/test_codon_tables.py
@@ -1,5 +1,6 @@
import pytest
+from python_codon_tables import get_codons_table
from seqlike import aaSeqLike
from seqlike.codon_tables import (
codon_table_to_codon_map,
@@ -32,3 +33,11 @@ def test_codon_table_to_codon_map(letter):
human_codon_map = codon_table_to_codon_map(sort_codon_table_by_frequency(human_codon_table))
codon = aaSeqLike(letter).back_translate(codon_map=human_codon_map)
assert sorted(human_codon_table[letter].items(), key=lambda x: x[1], reverse=True)[0][0] == str(codon)
+
+
[email protected]("codon_table_name", ["h_sapiens_9606", "s_cerevisiae_4932"])
+def test_codon_table(codon_table_name):
+ assert ''.join(sorted(human_codon_table.keys())) == '*-ACDEFGHIKLMNPQRSTVWXY'
+
+ codons_table = get_codons_table(codon_table_name)
+ assert ''.join(sorted(codons_table.keys())) == '*ACDEFGHIKLMNPQRSTVWY'
\ No newline at end of file
|
fix codons_table bug
Adding entries to a codon table generated by `python_codon_tables.get_codons_table()` has the insidious effect of adding these entries to codon tables generated by subsequent calls to `get_codons_table()`. For example:
```python
import python_codon_tables as pct
# generate a codon table; assertion passes
table1 = pct.get_codons_table("h_sapiens_9606")
assert ''.join(sorted(table1.keys())) == '*ACDEFGHIKLMNPQRSTVWY'
# let's add some new letters; assertion passes
table1["-"] = {"---": 1}
table1["X"] = {"NNN": 1}
assert ''.join(sorted(table1.keys())) == '*-ACDEFGHIKLMNPQRSTVWXY'
# now if we call get_codons_table again, these new letters are somehow included and the assertion will fail
table2 = pct.get_codons_table("h_sapiens_9606")
assert ''.join(sorted(table2.keys())) == '*ACDEFGHIKLMNPQRSTVWY'
```
Simply adding a copy operation to codon table objects fixes this bug.
|
0.0
|
1859afc419b6f530d37ff849f4b76cd8576b8bd8
|
[
"tests/test_codon_tables.py::test_codon_table[h_sapiens_9606]",
"tests/test_codon_tables.py::test_codon_table[s_cerevisiae_4932]"
] |
[
"tests/test_codon_tables.py::test_sort_codon_table_by_frequency[codon_table0]",
"tests/test_codon_tables.py::test_sort_codon_table_by_frequency[codon_table1]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[A]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[C]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[D]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[E]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[F]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[G]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[H]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[I]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[K]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[L]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[M]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[N]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[P]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[Q]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[R]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[S]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[T]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[V]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[W]",
"tests/test_codon_tables.py::test_codon_table_to_codon_map[Y]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2023-06-05 16:49:52+00:00
|
apache-2.0
| 4,025 |
|
modm-io__lbuild-11
|
diff --git a/lbuild/main.py b/lbuild/main.py
index 7593491..95016c1 100644
--- a/lbuild/main.py
+++ b/lbuild/main.py
@@ -24,7 +24,7 @@ from lbuild.format import format_option_short_description
from lbuild.api import Builder
-__version__ = '1.4.3'
+__version__ = '1.4.4'
class InitAction:
diff --git a/lbuild/node.py b/lbuild/node.py
index ae95df9..030ca97 100644
--- a/lbuild/node.py
+++ b/lbuild/node.py
@@ -308,7 +308,7 @@ class BaseNode(anytree.Node):
except LbuildException as b:
if not ignore_failure:
raise LbuildException("Cannot resolve dependencies!\n" + str(b))
- print("ignoring", dependency_name)
+ LOGGER.debug("ignoring", dependency_name)
self._dependencies = list(dependencies)
self._dependencies_resolved = not ignore_failure
for child in self.children:
diff --git a/lbuild/parser.py b/lbuild/parser.py
index 7c9fb19..dbc69d0 100644
--- a/lbuild/parser.py
+++ b/lbuild/parser.py
@@ -220,7 +220,10 @@ class Parser(BaseNode):
def find_any(self, queries, types=None):
nodes = set()
for query in utils.listify(queries):
- nodes |= set(self._resolve_partial(query, set()))
+ result = self._resolve_partial(query, None)
+ if result is None:
+ raise LbuildException("Cannot resolve '{}'".format(query))
+ nodes |= set(result)
if types:
types = utils.listify(types)
nodes = [n for n in nodes if any(n.type == t for t in types)]
|
modm-io/lbuild
|
b27975301922834e0173369873cd705673391708
|
diff --git a/test/parser_test.py b/test/parser_test.py
index 4479f3b..20834a0 100644
--- a/test/parser_test.py
+++ b/test/parser_test.py
@@ -138,6 +138,16 @@ class ParserTest(unittest.TestCase):
self.assertIn("repo1:other", self.parser.modules)
self.assertIn("repo1:module1", self.parser.modules)
+ def test_raise_unknown_module(self):
+ self.parser.parse_repository(self._get_path("combined/repo1.lb"))
+ self.parser._config_flat = lbuild.config.ConfigNode.from_file(self._get_path("combined/test1.xml"))
+
+ self.parser.merge_repository_options()
+ modules = self.parser.prepare_repositories()
+ self.parser.config.modules.append(":unknown")
+ self.assertRaises(lbuild.exception.LbuildException,
+ lambda: self.parser.find_modules(self.parser.config.modules))
+
def _get_build_modules(self):
self.parser.parse_repository(self._get_path("combined/repo1.lb"))
self.parser.parse_repository(self._get_path("combined/repo2/repo2.lb"))
|
No warning/error on non-existing modules
You can add arbitrary module lines like `<module>This does not exist and is bullshit</module>` and there will be no error or warning. This is very unpleasant if modules names in modm changed and you will get no feedback from lbuild that a requested module was not found.
Accidentally reported against wrong project dergraaf/library-builder#31
|
0.0
|
b27975301922834e0173369873cd705673391708
|
[
"test/parser_test.py::ParserTest::test_raise_unknown_module"
] |
[
"test/parser_test.py::ParserTest::test_repository_should_contain_options",
"test/parser_test.py::ParserTest::test_should_build_archive_modules",
"test/parser_test.py::ParserTest::test_should_build_jinja_2_modules",
"test/parser_test.py::ParserTest::test_should_build_modules",
"test/parser_test.py::ParserTest::test_should_find_files_in_repository_1",
"test/parser_test.py::ParserTest::test_should_find_files_in_repository_2",
"test/parser_test.py::ParserTest::test_should_merge_build_module_options",
"test/parser_test.py::ParserTest::test_should_merge_options",
"test/parser_test.py::ParserTest::test_should_parse_modules",
"test/parser_test.py::ParserTest::test_should_parse_modules_from_multiple_repositories",
"test/parser_test.py::ParserTest::test_should_parse_optional_functions_in_module",
"test/parser_test.py::ParserTest::test_should_parse_repository_1",
"test/parser_test.py::ParserTest::test_should_raise_when_no_module_is_found",
"test/parser_test.py::ParserTest::test_should_raise_when_overwriting_file",
"test/parser_test.py::ParserTest::test_should_raise_when_overwriting_file_in_tree",
"test/parser_test.py::ParserTest::test_should_resolve_module_dependencies",
"test/parser_test.py::ParserTest::test_should_select_available_modules"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
}
|
2018-10-16 16:01:10+00:00
|
bsd-2-clause
| 4,026 |
|
moogar0880__PyTrakt-108
|
diff --git a/HISTORY.rst b/HISTORY.rst
index 250fe12..cbd7617 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -1,5 +1,10 @@
Release History
^^^^^^^^^^^^^^^
+2.10.0 (2019-06-25)
++++++++++++++++++++
+
+* Add the ability to return a list of search results instead of their underlying media types (#106)
+
2.9.1 (2019-02-24)
++++++++++++++++++
diff --git a/trakt/__init__.py b/trakt/__init__.py
index f1b1d1e..c731ff7 100644
--- a/trakt/__init__.py
+++ b/trakt/__init__.py
@@ -5,6 +5,6 @@ try:
except ImportError:
pass
-version_info = (2, 9, 1)
+version_info = (2, 10, 0)
__author__ = 'Jon Nappi'
__version__ = '.'.join([str(i) for i in version_info])
diff --git a/trakt/sync.py b/trakt/sync.py
index 39aee61..4e89700 100644
--- a/trakt/sync.py
+++ b/trakt/sync.py
@@ -114,48 +114,64 @@ def remove_from_collection(media):
yield 'sync/collection/remove', media.to_json()
-@get
def search(query, search_type='movie', year=None):
"""Perform a search query against all of trakt's media types
:param query: Your search string
:param search_type: The type of object you're looking for. Must be one of
'movie', 'show', 'episode', or 'person'
+ :param year: This parameter is ignored as it is no longer a part of the
+ official API. It is left here as a valid arg for backwards
+ compatability.
"""
- valids = ('movie', 'show', 'episode', 'person')
- if search_type not in valids:
- raise ValueError('search_type must be one of {}'.format(valids))
- uri = 'search?query={query}&type={type}'.format(
- query=slugify(query), type=search_type)
+ # the new get_search_results expects a list of types, so handle this
+ # conversion to maintain backwards compatability
+ if isinstance(search_type, str):
+ search_type = [search_type]
+ results = get_search_results(query, search_type)
+ return [result.media for result in results]
+
+
+@get
+def get_search_results(query, search_type=None):
+ """Perform a search query against all of trakt's media types
- if year is not None:
- uri += '&year={}'.format(year)
+ :param query: Your search string
+ :param search_type: The types of objects you're looking for. Must be
+ specified as a list of strings containing any of 'movie', 'show',
+ 'episode', or 'person'.
+ """
+ # if no search type was specified, then search everything
+ if search_type is None:
+ search_type = ['movie', 'show', 'episode', 'person']
+ uri = 'search/{type}?query={query}'.format(
+ query=slugify(query), type=','.join(search_type))
data = yield uri
+ # Need to do imports here to prevent circular imports with modules that
+ # need to import Scrobblers
+ results = []
for media_item in data:
extract_ids(media_item)
+ result = SearchResult(media_item['type'], media_item['score'])
+ if media_item['type'] == 'movie':
+ from trakt.movies import Movie
+ result.media = Movie(**media_item.pop('movie'))
+ elif media_item['type'] == 'show':
+ from trakt.tv import TVShow
+ result.media = TVShow(**media_item.pop('show'))
+ elif media_item['type'] == 'episode':
+ from trakt.tv import TVEpisode
+ show = media_item.pop('show')
+ result.media = TVEpisode(show.get('title', None),
+ **media_item.pop('episode'))
+ elif media_item['type'] == 'person':
+ from trakt.people import Person
+ result.media = Person(**media_item.pop('person'))
+ results.append(result)
- # Need to do imports here to prevent circular imports with modules that
- # need to import Scrobblers
- if search_type == 'movie':
- from trakt.movies import Movie
- yield [Movie(**d.pop('movie')) for d in data]
- elif search_type == 'show':
- from trakt.tv import TVShow
- yield [TVShow(**d.pop('show')) for d in data]
- elif search_type == 'episode':
- from trakt.tv import TVEpisode
- episodes = []
- for episode in data:
- show = episode.pop('show')
- extract_ids(episode['episode'])
- episodes.append(TVEpisode(show.get('title', None),
- **episode['episode']))
- yield episodes
- elif search_type == 'person':
- from trakt.people import Person
- yield [Person(**d.pop('person')) for d in data]
+ yield results
@get
@@ -269,3 +285,20 @@ class Scrobbler(object):
scrobbling the :class:`Scrobller`'s *media* object
"""
self.finish()
+
+
+class SearchResult(object):
+ """A SearchResult is an individual result item from the trakt.tv search
+ API. It wraps a single media entity whose type is indicated by the type
+ field.
+ """
+ def __init__(self, type, score, media=None):
+ """Create a new :class:`SearchResult` instance
+
+ :param type: The type of media object contained in this result.
+ :param score: The search result relevancy score of this item.
+ :param media: The wrapped media item returned by a search.
+ """
+ self.type = type
+ self.score = score
+ self.media = media
|
moogar0880/PyTrakt
|
490b465291cb546a903160007aa2eacc85cd4d7c
|
diff --git a/tests/mock_data/search.json b/tests/mock_data/search.json
index 8bd87b2..1cd4a2c 100644
--- a/tests/mock_data/search.json
+++ b/tests/mock_data/search.json
@@ -1,36 +1,21 @@
{
- "search?query=batman&type=movie": {
+ "search/movie?query=batman": {
"GET": [
{"type":"movie","score":85.67655,"movie":{"title":"Batman","overview":"The Dark Knight of Gotham City begins his war on crime with his first major enemy being the clownishly homicidal Joker, who has seized control of Gotham's underworld.","year":1989,"images":{"poster":{"full":"https://walter.trakt.us/images/movies/000/000/224/posters/original/8a5816fc0b.jpg","medium":"https://walter.trakt.us/images/movies/000/000/224/posters/medium/8a5816fc0b.jpg","thumb":"https://walter.trakt.us/images/movies/000/000/224/posters/thumb/8a5816fc0b.jpg"},"fanart":{"full":"https://walter.trakt.us/images/movies/000/000/224/fanarts/original/cbc5557201.jpg","medium":"https://walter.trakt.us/images/movies/000/000/224/fanarts/medium/cbc5557201.jpg","thumb":"https://walter.trakt.us/images/movies/000/000/224/fanarts/thumb/cbc5557201.jpg"}},"ids":{"trakt":224,"slug":"batman-1989","imdb":"tt0096895","tmdb":268}}},
{"type":"movie","score":85.67655,"movie":{"title":"Batman","overview":"The Dynamic Duo faces four super-villains who plan to hold the world for ransom with the help of a secret invention that instantly dehydrates people.","year":1966,"images":{"poster":{"full":"https://walter.trakt.us/images/movies/000/001/794/posters/original/4a4f6031b0.jpg","medium":"https://walter.trakt.us/images/movies/000/001/794/posters/medium/4a4f6031b0.jpg","thumb":"https://walter.trakt.us/images/movies/000/001/794/posters/thumb/4a4f6031b0.jpg"},"fanart":{"full":"https://walter.trakt.us/images/movies/000/001/794/fanarts/original/493d7c70a3.jpg","medium":"https://walter.trakt.us/images/movies/000/001/794/fanarts/medium/493d7c70a3.jpg","thumb":"https://walter.trakt.us/images/movies/000/001/794/fanarts/thumb/493d7c70a3.jpg"}},"ids":{"trakt":1794,"slug":"batman-1966","imdb":"tt0060153","tmdb":2661}}}
]
},
- "search?query=batman&type=movie&year=1966": {
- "GET": [
- {"type":"movie","score":85.67655,"movie":{"title":"Batman","overview":"The Dynamic Duo faces four super-villains who plan to hold the world for ransom with the help of a secret invention that instantly dehydrates people.","year":1966,"images":{"poster":{"full":"https://walter.trakt.us/images/movies/000/001/794/posters/original/4a4f6031b0.jpg","medium":"https://walter.trakt.us/images/movies/000/001/794/posters/medium/4a4f6031b0.jpg","thumb":"https://walter.trakt.us/images/movies/000/001/794/posters/thumb/4a4f6031b0.jpg"},"fanart":{"full":"https://walter.trakt.us/images/movies/000/001/794/fanarts/original/493d7c70a3.jpg","medium":"https://walter.trakt.us/images/movies/000/001/794/fanarts/medium/493d7c70a3.jpg","thumb":"https://walter.trakt.us/images/movies/000/001/794/fanarts/thumb/493d7c70a3.jpg"}},"ids":{"trakt":1794,"slug":"batman-1966","imdb":"tt0060153","tmdb":2661}}}
- ]
- },
- "search?query=batman&type=show": {
+ "search/show?query=batman": {
"GET": [
{"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/002/273/posters/medium/6a2568c755.jpg", "full": "https://walter.trakt.us/images/shows/000/002/273/posters/original/6a2568c755.jpg", "thumb": "https://walter.trakt.us/images/shows/000/002/273/posters/thumb/6a2568c755.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/002/273/fanarts/medium/7d42efbf73.jpg", "full": "https://walter.trakt.us/images/shows/000/002/273/fanarts/original/7d42efbf73.jpg", "thumb": "https://walter.trakt.us/images/shows/000/002/273/fanarts/thumb/7d42efbf73.jpg"}}, "ids": {"trakt": 2273, "tvrage": 2719, "tvdb": 77871, "slug": "batman", "imdb": "tt0059968", "tmdb": 2287}, "overview": "Wealthy entrepreneur Bruce Wayne and his ward Dick Grayson lead a double life: they are actually crime fighting duo Batman and Robin. A secret Batpole in the Wayne mansion leads to the Batcave, where Police Commissioner Gordon often calls with the latest emergency threatening Gotham City. Racing the the scene of the crime in the Batmobile, Batman and Robin must (with the help of their trusty Bat-utility-belt) thwart the efforts of a variety of master criminals, including The Riddler, The Joker, Catwoman, and The Penguin.", "title": "Batman", "year": 1966, "status": "ended"}, "score": 78.2283}, {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/000/512/posters/medium/e953162fe9.jpg", "full": "https://walter.trakt.us/images/shows/000/000/512/posters/original/e953162fe9.jpg", "thumb": "https://walter.trakt.us/images/shows/000/000/512/posters/thumb/e953162fe9.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/000/512/fanarts/medium/d6792a2797.jpg", "full": "https://walter.trakt.us/images/shows/000/000/512/fanarts/original/d6792a2797.jpg", "thumb": "https://walter.trakt.us/images/shows/000/000/512/fanarts/thumb/d6792a2797.jpg"}}, "ids": {"trakt": 512, "tvrage": 2722, "tvdb": 75417, "slug": "batman-beyond", "imdb": "tt0147746", "tmdb": 513}, "overview": "It's been years since Batman was last seen and Bruce Wayne secludes himself away from the resurgence of crime in Gotham. After discovering Bruce's secret identity, troubled teenager Terry McGinnis dons the mantle of Batman. With Bruce supervising him, Terry battles criminals in a futuristic Gotham and brings hope to its citizens.", "title": "Batman Beyond", "year": 1999, "status": "ended"}, "score": 55.877357}, {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/002/009/posters/medium/09023ee66d.jpg", "full": "https://walter.trakt.us/images/shows/000/002/009/posters/original/09023ee66d.jpg", "thumb": "https://walter.trakt.us/images/shows/000/002/009/posters/thumb/09023ee66d.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/002/009/fanarts/medium/256651c6be.jpg", "full": "https://walter.trakt.us/images/shows/000/002/009/fanarts/original/256651c6be.jpg", "thumb": "https://walter.trakt.us/images/shows/000/002/009/fanarts/thumb/256651c6be.jpg"}}, "ids": {"trakt": 2009, "tvrage": 5602, "tvdb": 73180, "slug": "the-batman", "imdb": "tt0398417", "tmdb": 2022}, "overview": "A young Bruce Wayne is in his third year of trying to establish himself as Batman, protector of Gotham City. He is in his mid-twenties, just finding his way as protector, defender and Caped Crusader, while balancing his public persona as billionaire bachelor Bruce Wayne. Living in Gotham, a metropolis where shadows run long and deep, beneath elevated train tracks, this younger Batman will confront updated takes of familiar foes - meeting each member of his classic Rogue\"s Gallery for the first time. From the likes of Joker, Penguin, Catwoman, Mr. Freeze, Riddler and Man-Bat, among others, the war on crime jumps to the next level with a new arsenal at the Dark Knight\"s disposal, all operated and linked by an advanced remote-controlled invention he dubs the \"Bat-Wave.\" ", "title": "The Batman", "year": 2004, "status": "ended"}, "score": 55.877357}, {"type": "show", "show": {"images": {"poster": {"medium": null, "full": null, "thumb": null}, "fanart": {"medium": null, "full": null, "thumb": null}}, "ids": {"trakt": 102664, "tvrage": null, "tvdb": 301558, "slug": "batman-unlimited", "imdb": null, "tmdb": null}, "overview": "A webseries began airing on DC Kids' YouTube channel on May 4, 2015.", "title": "Batman Unlimited", "year": 2015, "status": "returning series"}, "score": 55.877357}, {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/081/374/posters/medium/9f2c978ded.jpg", "full": "https://walter.trakt.us/images/shows/000/081/374/posters/original/9f2c978ded.jpg", "thumb": "https://walter.trakt.us/images/shows/000/081/374/posters/thumb/9f2c978ded.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/081/374/fanarts/medium/9f2c978ded.jpg", "full": "https://walter.trakt.us/images/shows/000/081/374/fanarts/original/9f2c978ded.jpg", "thumb": "https://walter.trakt.us/images/shows/000/081/374/fanarts/thumb/9f2c978ded.jpg"}}, "ids": {"trakt": 81374, "tvrage": null, "tvdb": 287484, "slug": "lego-batman", "imdb": null, "tmdb": null}, "overview": "Batman prides himself on being a loner, a totally self sufficient one-man band. He is understandably irritated when his nightly cleanup of Gotham City villains is interrupted by Superman, who pesters Batman to join his new Super-Hero team, the Justice League. After Batman makes it quite clear to the Man of Steel that his invitation has been declined, Superman flies off disappointed … whereupon he is overcome with a strange energy and vanishes! As costumed Super-Villains begin vanishing one-by-one at the hand of a mysterious enemy, the Dark Knight must free the newly-formed Justice League from a powerful foe. But can Batman learn the value of being a team-player before the Justice League is lost forever?", "title": "Lego Batman", "year": 2014, "status": "returning series"}, "score": 55.877357}, {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/041/472/posters/medium/3211da0751.jpg", "full": "https://walter.trakt.us/images/shows/000/041/472/posters/original/3211da0751.jpg", "thumb": "https://walter.trakt.us/images/shows/000/041/472/posters/thumb/3211da0751.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/041/472/fanarts/medium/cda4ae8fab.jpg", "full": "https://walter.trakt.us/images/shows/000/041/472/fanarts/original/cda4ae8fab.jpg", "thumb": "https://walter.trakt.us/images/shows/000/041/472/fanarts/thumb/cda4ae8fab.jpg"}}, "ids": {"trakt": 41472, "tvrage": null, "tvdb": 258331, "slug": "beware-the-batman", "imdb": "", "tmdb": 41676}, "overview": "The series is set during Bruce Wayne's early years as the Batman, following his initial period of battling organized crime. Over the course of the season, he hones his skills with the assistance of his butler, Alfred Pennyworth. Bruce is introduced to Alfred's goddaughter, Tatsu Yamashiro. Tatsu is a martial arts swordsmaster hired to act as Bruce's bodyguard, but also recruited to act as a superhero partner to Batman.", "title": "Beware the Batman", "year": 2013, "status": "returning series"}, "score": 44.701885}, {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/002/085/posters/medium/391f332b37.jpg", "full": "https://walter.trakt.us/images/shows/000/002/085/posters/original/391f332b37.jpg", "thumb": "https://walter.trakt.us/images/shows/000/002/085/posters/thumb/391f332b37.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/002/085/fanarts/medium/ab8d2d1b46.jpg", "full": "https://walter.trakt.us/images/shows/000/002/085/fanarts/original/ab8d2d1b46.jpg", "thumb": "https://walter.trakt.us/images/shows/000/002/085/fanarts/thumb/ab8d2d1b46.jpg"}}, "ids": {"trakt": 2085, "tvrage": 2721, "tvdb": 76168, "slug": "batman-the-animated-series", "imdb": "tt0103359", "tmdb": 2098}, "overview": "Batman The Animated Series was a cartoon that premiered on September 5, 1992, based on the comic series created by Bob Kane, as well as the Burton movie adaptations. The series focused on the adventures of the alter ego of millionaire Bruce Wayne, Batman, a dark vigilante hero who defends Gotham City from a variety of creative and psychotic villains. The highly successful series merged stylish animation and fantastic storytelling more in the style of radio plays than typical cartoons.", "title": "Batman: The Animated Series", "year": 1992, "status": "ended"}, "score": 39.11415}, {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/004/601/posters/medium/56bb90f61e.jpg", "full": "https://walter.trakt.us/images/shows/000/004/601/posters/original/56bb90f61e.jpg", "thumb": "https://walter.trakt.us/images/shows/000/004/601/posters/thumb/56bb90f61e.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/004/601/fanarts/medium/a3ee2e1ec3.jpg", "full": "https://walter.trakt.us/images/shows/000/004/601/fanarts/original/a3ee2e1ec3.jpg", "thumb": "https://walter.trakt.us/images/shows/000/004/601/fanarts/thumb/a3ee2e1ec3.jpg"}}, "ids": {"trakt": 4601, "tvrage": null, "tvdb": 77084, "slug": "the-new-batman-adventures", "imdb": "tt0118266", "tmdb": 4625}, "overview": "Also known as Batman Gotham Knights, this series takes place two years after the last episode of Batman: The Animated Series. Batman has continued to fight crime in Gotham City, but there have been some changes. Dick Grayson has become Nightwing; Tim Drake has taken over the role of Robin; and Batgirl has become apart of Batman's team. But the Dark Knight's greatest villains continue to plague Gotham City, so not everything has changed. This series aired alongside Superman as part of The New Batman/Superman Adventures on the WB. First Telecast: September 13, 1997Last Telecast: January 16, 1999 Episodes: 24 Color episodes (24 half-hour episodes, 2 Direct-to Video Movies) ", "title": "The New Batman Adventures", "year": 1997, "status": "ended"}, "score": 39.11415}, {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/031/611/posters/medium/d969363d90.jpg", "full": "https://walter.trakt.us/images/shows/000/031/611/posters/original/d969363d90.jpg", "thumb": "https://walter.trakt.us/images/shows/000/031/611/posters/thumb/d969363d90.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/031/611/fanarts/medium/66fab2b401.jpg", "full": "https://walter.trakt.us/images/shows/000/031/611/fanarts/original/66fab2b401.jpg", "thumb": "https://walter.trakt.us/images/shows/000/031/611/fanarts/thumb/66fab2b401.jpg"}}, "ids": {"trakt": 31611, "tvrage": null, "tvdb": 248509, "slug": "the-adventures-of-batman", "imdb": "tt0062544", "tmdb": 31749}, "overview": "The adventures of Batman, with Robin, the Boy Wonder!Batman and Robin, the Dynamic Duo against crime and corruption, whose real identities as millionaire philanthropist Bruce Wayne and his young ward Dick Grayson and known only to Alfred, the faithful butler.Ever alert, they respond swiftly to a signal from the police, and moments later, from the secret Batcave deep beneath Wayne Manor, they roar out to protect life, limb and property as Batman and Robin, caped crimefighters!Batman and Robin, scourge of Gotham City's kooky criminals: The Joker, Clown Prince of Crime - The Penguin, pudgy purveyor of perfidy - and the cool, cruel, Mr. Freeze!Watch out, villains, here come... Batman and Robin!", "title": "The Adventures of Batman", "year": 1968, "status": "ended"}, "score": 39.11415}, {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/061/637/posters/medium/a889cb95b2.jpg", "full": "https://walter.trakt.us/images/shows/000/061/637/posters/original/a889cb95b2.jpg", "thumb": "https://walter.trakt.us/images/shows/000/061/637/posters/thumb/a889cb95b2.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/061/637/fanarts/medium/d873f0ed83.jpg", "full": "https://walter.trakt.us/images/shows/000/061/637/fanarts/original/d873f0ed83.jpg", "thumb": "https://walter.trakt.us/images/shows/000/061/637/fanarts/thumb/d873f0ed83.jpg"}}, "ids": {"trakt": 61637, "tvrage": null, "tvdb": 93341, "slug": "batman-the-1943-serial", "imdb": "tt0035665", "tmdb": null}, "overview": "Batman was a 15-chapter serial released in 1943 by Columbia Pictures. The serial starred Lewis Wilson as Batman and Douglas Croft as Robin. J. Carrol Naish played the villain, an original character named Dr. Daka. Rounding out the cast were Shirley Patterson as Linda Page (Bruce Wayne's love interest), and William Austin as Alfred. The plot is based on Batman, a US government agent, attempting to defeat the Japanese agent Dr. Daka, at the height of World War II.", "title": "Batman: The 1943 Serial", "year": 1943, "status": "ended"}, "score": 39.11415}
]
},
- "search?query=batman&type=show&year=1999": {
- "GET": [
- {"type": "show", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/000/512/posters/medium/e953162fe9.jpg", "full": "https://walter.trakt.us/images/shows/000/000/512/posters/original/e953162fe9.jpg", "thumb": "https://walter.trakt.us/images/shows/000/000/512/posters/thumb/e953162fe9.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/000/512/fanarts/medium/d6792a2797.jpg", "full": "https://walter.trakt.us/images/shows/000/000/512/fanarts/original/d6792a2797.jpg", "thumb": "https://walter.trakt.us/images/shows/000/000/512/fanarts/thumb/d6792a2797.jpg"}}, "ids": {"trakt": 512, "tvrage": 2722, "tvdb": 75417, "slug": "batman-beyond", "imdb": "tt0147746", "tmdb": 513}, "overview": "It's been years since Batman was last seen and Bruce Wayne secludes himself away from the resurgence of crime in Gotham. After discovering Bruce's secret identity, troubled teenager Terry McGinnis dons the mantle of Batman. With Bruce supervising him, Terry battles criminals in a futuristic Gotham and brings hope to its citizens.", "title": "Batman Beyond", "year": 1999, "status": "ended"}, "score": 55.877357}
- ]
- },
- "search?query=batman&type=episode": {
+ "search/episode?query=batman": {
"GET": [
{"type": "episode", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/000/900/posters/medium/d67bbc0a62.jpg", "full": "https://walter.trakt.us/images/shows/000/000/900/posters/original/d67bbc0a62.jpg", "thumb": "https://walter.trakt.us/images/shows/000/000/900/posters/thumb/d67bbc0a62.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/000/900/fanarts/medium/1eae79bc72.jpg", "full": null, "thumb": "https://walter.trakt.us/images/shows/000/000/900/fanarts/thumb/1eae79bc72.jpg"}}, "year": "1987", "ids": {"trakt": 900, "slug": "french-saunders"}}, "episode": {"images": {"screenshot": {"medium": "https://walter.trakt.us/images/episodes/000/059/025/screenshots/medium/5bd7342a6a.jpg", "full": "https://walter.trakt.us/images/episodes/000/059/025/screenshots/original/5bd7342a6a.jpg", "thumb": "https://walter.trakt.us/images/episodes/000/059/025/screenshots/thumb/5bd7342a6a.jpg"}}, "title": "Batman", "season": 5, "number": 4, "ids": {"trakt": 59025, "tvrage": 64781, "tmdb": null, "imdb": "", "tvdb": 165596}}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/063/200/posters/medium/4f5ec381c4.jpg", "full": "https://walter.trakt.us/images/shows/000/063/200/posters/original/4f5ec381c4.jpg", "thumb": "https://walter.trakt.us/images/shows/000/063/200/posters/thumb/4f5ec381c4.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/063/200/fanarts/medium/4f5ec381c4.jpg", "full": null, "thumb": "https://walter.trakt.us/images/shows/000/063/200/fanarts/thumb/4f5ec381c4.jpg"}}, "year": "2008", "ids": {"trakt": 63200, "slug": "hey-ash-whatcha-playin"}}, "episode": {"images": {"screenshot": {"medium": "https://walter.trakt.us/images/episodes/001/058/895/screenshots/medium/5f6e4ee8fe.jpg", "full": "https://walter.trakt.us/images/episodes/001/058/895/screenshots/original/5f6e4ee8fe.jpg", "thumb": "https://walter.trakt.us/images/episodes/001/058/895/screenshots/thumb/5f6e4ee8fe.jpg"}}, "ids": {"trakt": 1058895, "tvrage": null, "tmdb": null, "imdb": null, "tvdb": 4412148}, "overview": "Arkham's criminals don't stand a chance against the world's greatest detective, Ashly Burch.", "number": 15, "season": 4, "title": "Batman"}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/004/968/posters/medium/beec80b1c2.jpg", "full": "https://walter.trakt.us/images/shows/000/004/968/posters/original/beec80b1c2.jpg", "thumb": "https://walter.trakt.us/images/shows/000/004/968/posters/thumb/beec80b1c2.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/004/968/fanarts/medium/0918fab718.jpg", "full": null, "thumb": "https://walter.trakt.us/images/shows/000/004/968/fanarts/thumb/0918fab718.jpg"}}, "ids": {"trakt": 4968, "slug": "biography"}, "year": "1987", "title": "Biography"}, "episode": {"images": {"screenshot": {"medium": null, "full": null, "thumb": null}}, "ids": {"trakt": 1617094, "tvrage": null, "tmdb": 0, "imdb": null, "tvdb": 4358502}, "overview": "A history of the campy classic '60s TV series \"Batman\", starring Adam West and Burt Ward, who are on hand to comment. Included: screen tests and clips of memorable scenes. Also commenting is executive producer William Dozier; and Batmobile customizer George Barris. ", "number": 2, "season": 2003, "title": "Batman"}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/079/142/posters/medium/ecf7fa7ec3.jpg", "full": "https://walter.trakt.us/images/shows/000/079/142/posters/original/ecf7fa7ec3.jpg", "thumb": "https://walter.trakt.us/images/shows/000/079/142/posters/thumb/ecf7fa7ec3.jpg"}, "fanart": {"medium": null, "full": null, "thumb": null}}, "year": "1969", "ids": {"trakt": 79142, "slug": "bad-days"}}, "episode": {"images": {"screenshot": {"medium": null, "full": null, "thumb": null}}, "ids": {"trakt": 1304962, "tvrage": null, "tmdb": null, "imdb": null, "tvdb": 4571070}, "overview": "Batman doesn't really have bad days, but he definitely has bad nights..", "number": 9, "season": 1, "title": "Batman"}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/073/361/posters/medium/df4f1c96c2.jpg", "full": "https://walter.trakt.us/images/shows/000/073/361/posters/original/df4f1c96c2.jpg", "thumb": "https://walter.trakt.us/images/shows/000/073/361/posters/thumb/df4f1c96c2.jpg"}, "fanart": {"medium": null, "full": null, "thumb": null}}, "year": "2005", "ids": {"trakt": 73361, "slug": "snl-digital-shorts"}}, "episode": {"images": {"screenshot": {"medium": null, "full": null, "thumb": null}}, "title": "Batman", "season": 7, "number": 6, "ids": {"trakt": 1227579, "tvrage": null, "tmdb": null, "imdb": null, "tvdb": 4670467}}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": null, "full": null, "thumb": null}, "fanart": {"medium": null, "full": null, "thumb": null}}, "year": "2009", "ids": {"trakt": 94515, "slug": "3-2009"}}, "episode": {"images": {"screenshot": {"medium": "https://walter.trakt.us/images/episodes/001/690/018/screenshots/medium/f333de513d.jpg", "full": "https://walter.trakt.us/images/episodes/001/690/018/screenshots/original/f333de513d.jpg", "thumb": "https://walter.trakt.us/images/episodes/001/690/018/screenshots/thumb/f333de513d.jpg"}}, "title": "BATMAN!!!", "season": 2010, "number": 55, "ids": {"trakt": 1690018, "tvrage": null, "tmdb": null, "imdb": null, "tvdb": 4599451}}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": null, "full": null, "thumb": null}, "fanart": {"medium": null, "full": null, "thumb": null}}, "year": "1998", "ids": {"trakt": 96440, "slug": "joulukalenteri-tonttu-toljanterin-joulupulma"}}, "episode": {"images": {"screenshot": {"medium": null, "full": null, "thumb": null}}, "title": "Batman", "season": 1, "number": 3, "ids": {"trakt": 1766428, "tvrage": null, "tmdb": null, "imdb": null, "tvdb": 4681124}}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": null, "full": null, "thumb": null}, "fanart": {"medium": null, "full": null, "thumb": null}}, "year": "2002", "ids": {"trakt": 14649, "slug": "cheat"}}, "episode": {"images": {"screenshot": {"medium": null, "full": null, "thumb": null}}, "ids": {"trakt": 535228, "tvrage": 356329, "tmdb": 526964, "imdb": "", "tvdb": 143833}, "overview": "Endless summer", "number": 1, "season": 1, "title": "Batman"}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/078/744/posters/medium/ee26d1337b.jpg", "full": "https://walter.trakt.us/images/shows/000/078/744/posters/original/ee26d1337b.jpg", "thumb": "https://walter.trakt.us/images/shows/000/078/744/posters/thumb/ee26d1337b.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/078/744/fanarts/medium/ee26d1337b.jpg", "full": null, "thumb": "https://walter.trakt.us/images/shows/000/078/744/fanarts/thumb/ee26d1337b.jpg"}}, "year": "2012", "ids": {"trakt": 78744, "slug": "revansch"}}, "episode": {"images": {"screenshot": {"medium": "https://walter.trakt.us/images/episodes/001/302/992/screenshots/medium/7b86b4bbe3.jpg", "full": "https://walter.trakt.us/images/episodes/001/302/992/screenshots/original/7b86b4bbe3.jpg", "thumb": "https://walter.trakt.us/images/episodes/001/302/992/screenshots/thumb/7b86b4bbe3.jpg"}}, "ids": {"trakt": 1302992, "tvrage": null, "tmdb": null, "imdb": null, "tvdb": 4770106}, "overview": "As a kid you maybe sold your NES to afford the upcoming SNES. Victor is certainly one of them. 20 years later he visits his parents' attic and finds this game. Is this fate?", "number": 10, "season": 1, "title": "Batman"}, "score": 91.11184}, {"type": "episode", "show": {"images": {"poster": {"medium": null, "full": null, "thumb": null}, "fanart": {"medium": null, "full": null, "thumb": null}}, "ids": {"trakt": 102553, "slug": "you-think-you-know-comics"}, "year": "2014", "title": "You Think You Know Comics"}, "episode": {"images": {"screenshot": {"medium": null, "full": null, "thumb": null}}, "title": "Batman", "season": 2014, "number": 2, "ids": {"trakt": 2015951, "tvrage": null, "tmdb": null, "imdb": null, "tvdb": 5357566}}, "score": 91.11184}
]
},
- "search?query=batman&type=episode&year=1987": {
- "GET": [
- {"type": "episode", "show": {"images": {"poster": {"medium": "https://walter.trakt.us/images/shows/000/000/900/posters/medium/d67bbc0a62.jpg", "full": "https://walter.trakt.us/images/shows/000/000/900/posters/original/d67bbc0a62.jpg", "thumb": "https://walter.trakt.us/images/shows/000/000/900/posters/thumb/d67bbc0a62.jpg"}, "fanart": {"medium": "https://walter.trakt.us/images/shows/000/000/900/fanarts/medium/1eae79bc72.jpg", "full": null, "thumb": "https://walter.trakt.us/images/shows/000/000/900/fanarts/thumb/1eae79bc72.jpg"}}, "year": "1987", "ids": {"trakt": 900, "slug": "french-saunders"}}, "episode": {"images": {"screenshot": {"medium": "https://walter.trakt.us/images/episodes/000/059/025/screenshots/medium/5bd7342a6a.jpg", "full": "https://walter.trakt.us/images/episodes/000/059/025/screenshots/original/5bd7342a6a.jpg", "thumb": "https://walter.trakt.us/images/episodes/000/059/025/screenshots/thumb/5bd7342a6a.jpg"}}, "title": "Batman", "season": 5, "number": 4, "ids": {"trakt": 59025, "tvrage": 64781, "tmdb": null, "imdb": "", "tvdb": 165596}}, "score": 91.11184}
- ]
- },
- "search?query=cranston&type=person": {
+ "search/person?query=cranston": {
"GET": [
{"type": "person", "person": {"images": {"headshot": {"medium": null, "full": null, "thumb": null}}, "ids": {"trakt": 154029, "tvrage": null, "slug": "bob-cranston", "imdb": "", "tmdb": 587197}, "name": "Bob Cranston"}, "score": 94.57829},
{"type": "person", "person": {"images": {"headshot": {"medium": null, "full": null, "thumb": null}}, "ids": {"trakt": 364188, "tvrage": null, "slug": "al-cranston", "imdb": "", "tmdb": 1309602}, "name": "Al Cranston"}, "score": 94.57829},
diff --git a/tests/test_episodes.py b/tests/test_episodes.py
index 0561180..530882e 100644
--- a/tests/test_episodes.py
+++ b/tests/test_episodes.py
@@ -20,7 +20,7 @@ def test_episode_search():
def test_episode_search_with_year():
results = TVEpisode.search('batman', year=1987)
assert isinstance(results, list)
- assert len(results) == 1
+ assert len(results) == 10
assert all(isinstance(m, TVEpisode) for m in results)
diff --git a/tests/test_search.py b/tests/test_search.py
index 785bcba..7e4a2ba 100644
--- a/tests/test_search.py
+++ b/tests/test_search.py
@@ -3,22 +3,12 @@
import pytest
from trakt.movies import Movie
from trakt.people import Person
-from trakt.sync import search, search_by_id
+from trakt.sync import get_search_results, search, search_by_id, SearchResult
from trakt.tv import TVEpisode, TVShow
__author__ = 'Reinier van der Windt'
-def test_invalid_searches():
- """test that the proper exceptions are raised when an invalid search or id
- type is provided to a search function
- """
- functions = [search, search_by_id]
- for fn in functions:
- with pytest.raises(ValueError):
- fn('shouldfail', 'fake')
-
-
def test_search_movie():
"""test that movie search results are successfully returned"""
batman_results = search('batman')
@@ -26,10 +16,11 @@ def test_search_movie():
assert len(batman_results) == 2
assert all(isinstance(m, Movie) for m in batman_results)
+
def test_search_movie_with_year():
batman_results = search('batman', year='1966')
assert isinstance(batman_results, list)
- assert len(batman_results) == 1
+ assert len(batman_results) == 2
assert all(isinstance(m, Movie) for m in batman_results)
@@ -79,3 +70,12 @@ def test_search_person_by_id():
results = search_by_id('nm0186505', id_type='imdb')
assert isinstance(results, list)
assert all(isinstance(p, Person) for p in results)
+
+
+def test_get_search_results():
+ """test that entire results can be returned by get_search_results"""
+ results = get_search_results('batman', search_type=['movie'])
+ assert isinstance(results, list)
+ assert len(results) == 2
+ assert all(isinstance(r, SearchResult) for r in results)
+ assert all([r.score != 0.0 for r in results])
diff --git a/tests/test_shows.py b/tests/test_shows.py
index 518b5d5..a3f5bb5 100644
--- a/tests/test_shows.py
+++ b/tests/test_shows.py
@@ -91,7 +91,7 @@ def test_show_search():
def test_show_search_with_year():
results = TVShow.search('batman', year=1999)
assert isinstance(results, list)
- assert len(results) == 1
+ assert len(results) == 10
assert all(isinstance(m, TVShow) for m in results)
|
score is not added in the Movie class
Hi
I can see there is a `score` field in the response but can't find it in in the `Movie` class in this library
https://trakt.docs.apiary.io/#reference/search/text-query/get-text-query-results
I want this field, is there a way to get it?
|
0.0
|
490b465291cb546a903160007aa2eacc85cd4d7c
|
[
"tests/test_episodes.py::test_get_episodes",
"tests/test_episodes.py::test_episode_search",
"tests/test_episodes.py::test_episode_search_with_year",
"tests/test_episodes.py::test_get_episode",
"tests/test_episodes.py::test_episode_comments",
"tests/test_episodes.py::test_episode_ratings",
"tests/test_episodes.py::test_episode_watching_now",
"tests/test_episodes.py::test_episode_images",
"tests/test_episodes.py::test_episode_ids",
"tests/test_episodes.py::test_rate_episode",
"tests/test_episodes.py::test_oneliners",
"tests/test_episodes.py::test_episode_comment",
"tests/test_episodes.py::test_episode_scrobble",
"tests/test_episodes.py::test_episode_magic_methods",
"tests/test_search.py::test_search_movie",
"tests/test_search.py::test_search_movie_with_year",
"tests/test_search.py::test_search_show",
"tests/test_search.py::test_search_episode",
"tests/test_search.py::test_search_person",
"tests/test_search.py::test_search_movie_by_id",
"tests/test_search.py::test_search_show_by_id",
"tests/test_search.py::test_search_episode_by_id",
"tests/test_search.py::test_search_person_by_id",
"tests/test_search.py::test_get_search_results",
"tests/test_shows.py::test_dismiss_show_recomendation",
"tests/test_shows.py::test_recommended_shows",
"tests/test_shows.py::test_trending_shows",
"tests/test_shows.py::test_popular_shows",
"tests/test_shows.py::test_updated_shows",
"tests/test_shows.py::test_get_show",
"tests/test_shows.py::test_aliases",
"tests/test_shows.py::test_translations",
"tests/test_shows.py::test_get_comments",
"tests/test_shows.py::test_get_people",
"tests/test_shows.py::test_ratings",
"tests/test_shows.py::test_related",
"tests/test_shows.py::test_watching",
"tests/test_shows.py::test_show_search",
"tests/test_shows.py::test_show_search_with_year",
"tests/test_shows.py::test_show_ids",
"tests/test_shows.py::test_oneliners",
"tests/test_shows.py::test_show_comment",
"tests/test_shows.py::test_rate_show"
] |
[] |
{
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2019-06-26 02:06:30+00:00
|
apache-2.0
| 4,027 |
|
moogar0880__PyTrakt-120
|
diff --git a/trakt/core.py b/trakt/core.py
index e03d1a2..5823ce0 100644
--- a/trakt/core.py
+++ b/trakt/core.py
@@ -14,6 +14,7 @@ from collections import namedtuple
from functools import wraps
from requests.compat import urljoin
from requests_oauthlib import OAuth2Session
+from datetime import datetime, timedelta
from trakt import errors
__author__ = 'Jon Nappi'
@@ -44,6 +45,12 @@ CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.pytrakt.json')
#: Your personal Trakt.tv OAUTH Bearer Token
OAUTH_TOKEN = api_key = None
+# OAuth token validity checked
+OAUTH_TOKEN_VALID = None
+
+# Your OAUTH token expiration date
+OAUTH_EXPIRES_AT = None
+
# Your OAUTH refresh token
OAUTH_REFRESH = None
@@ -185,10 +192,13 @@ def oauth_auth(username, client_id=None, client_secret=None, store=False,
# Fetch, assign, and return the access token
oauth.fetch_token(token_url, client_secret=CLIENT_SECRET, code=oauth_pin)
OAUTH_TOKEN = oauth.token['access_token']
+ OAUTH_REFRESH = oauth.token['refresh_token']
+ OAUTH_EXPIRES_AT = oauth.token["created_at"] + oauth.token["expires_in"]
if store:
_store(CLIENT_ID=CLIENT_ID, CLIENT_SECRET=CLIENT_SECRET,
- OAUTH_TOKEN=OAUTH_TOKEN)
+ OAUTH_TOKEN=OAUTH_TOKEN, OAUTH_REFRESH=OAUTH_REFRESH,
+ OAUTH_EXPIRES_AT=OAUTH_EXPIRES_AT)
return OAUTH_TOKEN
@@ -263,11 +273,13 @@ def get_device_token(device_code, client_id=None, client_secret=None,
data = response.json()
OAUTH_TOKEN = data.get('access_token')
OAUTH_REFRESH = data.get('refresh_token')
+ OAUTH_EXPIRES_AT = data.get("created_at") + data.get("expires_in")
if store:
_store(
CLIENT_ID=CLIENT_ID, CLIENT_SECRET=CLIENT_SECRET,
- OAUTH_TOKEN=OAUTH_TOKEN, OAUTH_REFRESH=OAUTH_REFRESH
+ OAUTH_TOKEN=OAUTH_TOKEN, OAUTH_REFRESH=OAUTH_REFRESH,
+ OAUTH_EXPIRES_AT=OAUTH_EXPIRES_AT
)
return response
@@ -351,6 +363,55 @@ Comment = namedtuple('Comment', ['id', 'parent_id', 'created_at', 'comment',
'updated_at', 'likes', 'user_rating'])
+def _validate_token(s):
+ """Check if current OAuth token has not expired"""
+ global OAUTH_TOKEN_VALID
+ current = datetime.utcnow()
+ expires_at = datetime.utcfromtimestamp(OAUTH_EXPIRES_AT)
+ if expires_at - current > timedelta(days=2):
+ OAUTH_TOKEN_VALID = True
+ else:
+ _refresh_token(s)
+
+
+def _refresh_token(s):
+ """Request Trakt API for a new valid OAuth token using refresh_token"""
+ global OAUTH_TOKEN, OAUTH_EXPIRES_AT, OAUTH_REFRESH, OAUTH_TOKEN_VALID
+ s.logger.info("OAuth token has expired, refreshing now...")
+ url = urljoin(BASE_URL, '/oauth/token')
+ data = {
+ 'client_id': CLIENT_ID,
+ 'client_secret': CLIENT_SECRET,
+ 'refresh_token': OAUTH_REFRESH,
+ 'redirect_uri': REDIRECT_URI,
+ 'grant_type': 'refresh_token'
+ }
+ response = requests.post(url, json=data, headers=HEADERS)
+ s.logger.debug('RESPONSE [post] (%s): %s', url, str(response))
+ if response.status_code == 200:
+ data = response.json()
+ OAUTH_TOKEN = data.get("access_token")
+ OAUTH_REFRESH = data.get("refresh_token")
+ OAUTH_EXPIRES_AT = data.get("created_at") + data.get("expires_in")
+ OAUTH_TOKEN_VALID = True
+ s.logger.info(
+ "OAuth token successfully refreshed, valid until",
+ datetime.fromtimestamp(OAUTH_EXPIRES_AT)
+ )
+ _store(
+ CLIENT_ID=CLIENT_ID, CLIENT_SECRET=CLIENT_SECRET,
+ OAUTH_TOKEN=OAUTH_TOKEN, OAUTH_REFRESH=OAUTH_REFRESH,
+ OAUTH_EXPIRES_AT=OAUTH_EXPIRES_AT
+ )
+ elif response.status_code == 401:
+ s.logger.debug(
+ "Rejected - Unable to refresh expired OAuth token, "
+ "refresh_token is invalid"
+ )
+ elif response.status_code in s.error_map:
+ raise s.error_map[response.status_code]()
+
+
def _bootstrapped(f):
"""Bootstrap your authentication environment when authentication is needed
and if a file at `CONFIG_PATH` exists. The process is completed by setting
@@ -358,8 +419,8 @@ def _bootstrapped(f):
"""
@wraps(f)
def inner(*args, **kwargs):
- global CLIENT_ID, CLIENT_SECRET, OAUTH_TOKEN, OAUTH_REFRESH
- global APPLICATION_ID
+ global CLIENT_ID, CLIENT_SECRET, OAUTH_TOKEN, OAUTH_EXPIRES_AT
+ global OAUTH_REFRESH, APPLICATION_ID
if (CLIENT_ID is None or CLIENT_SECRET is None) and \
os.path.exists(CONFIG_PATH):
# Load in trakt API auth data from CONFIG_PATH
@@ -372,11 +433,17 @@ def _bootstrapped(f):
CLIENT_SECRET = config_data.get('CLIENT_SECRET', None)
if OAUTH_TOKEN is None:
OAUTH_TOKEN = config_data.get('OAUTH_TOKEN', None)
+ if OAUTH_EXPIRES_AT is None:
+ OAUTH_EXPIRES_AT = config_data.get('OAUTH_EXPIRES_AT', None)
if OAUTH_REFRESH is None:
OAUTH_REFRESH = config_data.get('OAUTH_REFRESH', None)
if APPLICATION_ID is None:
APPLICATION_ID = config_data.get('APPLICATION_ID', None)
+ # Check token validity and refresh token if needed
+ if (not OAUTH_TOKEN_VALID and OAUTH_EXPIRES_AT is not None and
+ OAUTH_REFRESH is not None):
+ _validate_token(args[0])
# For backwards compatability with trakt<=2.3.0
if api_key is not None and OAUTH_TOKEN is None:
OAUTH_TOKEN = api_key
diff --git a/trakt/errors.py b/trakt/errors.py
index 586af7c..7d69f10 100644
--- a/trakt/errors.py
+++ b/trakt/errors.py
@@ -11,7 +11,7 @@ __all__ = ['TraktException', 'BadRequestException', 'OAuthException',
'TraktUnavailable']
-class TraktException(BaseException):
+class TraktException(Exception):
"""Base Exception type for trakt module"""
http_code = message = None
diff --git a/trakt/users.py b/trakt/users.py
index b75ad6a..d4f48bd 100644
--- a/trakt/users.py
+++ b/trakt/users.py
@@ -295,6 +295,10 @@ class User(object):
data = yield 'users/{username}/lists'.format(
username=self.username
)
+ for ul in data:
+ if "user" in ul:
+ # user will be replaced with the self User object
+ del ul["user"]
self._lists = [UserList(creator=self.username, user=self,
**extract_ids(ul)) for ul in data]
yield self._lists
|
moogar0880/PyTrakt
|
70f5bcc5215272665e2ca6f901d54da9d68e890a
|
diff --git a/tests/mock_data/users.json b/tests/mock_data/users.json
index a1ff93d..f0222c3 100644
--- a/tests/mock_data/users.json
+++ b/tests/mock_data/users.json
@@ -206,7 +206,15 @@
"item_count":5,
"comment_count":0,
"likes":0,
- "ids":{"trakt":55,"slug":"star-wars-in-machete-order"}
+ "ids":{"trakt":55,"slug":"star-wars-in-machete-order"},
+ "user":{
+ "username": "sean",
+ "private": false,
+ "name": "Sean Rudford",
+ "vip": true,
+ "vip_ep": true,
+ "ids":{"slug":"sean"}
+ }
},
{
"name":"Vampires FTW",
@@ -221,7 +229,15 @@
"item_count":5,
"comment_count":0,
"likes":0,
- "ids":{"trakt":52,"slug":"vampires-ftw"}
+ "ids":{"trakt":52,"slug":"vampires-ftw"},
+ "user":{
+ "username": "sean",
+ "private": false,
+ "name": "Sean Rudford",
+ "vip": true,
+ "vip_ep": true,
+ "ids":{"slug":"sean"}
+ }
}
],
"POST": {
|
accessing User.list attribute throws python exception
python version: 3.6.8
trakt version: 2.12.0
when trying to get a list of the users lists an exception is returned
ie
```
import trakt
from trakt.users import User, UserList
from pprint import pprint
trakt.core.CLIENT_ID = cfg['client_id']
trakt.core.CLIENT_SECRET = cfg['client_secret']
trakt.core.OAUTH_TOKEN = cfg['oauth_token']
u = User('my_user')
pprint(u.lists)
```
returns the following exception:
```
Traceback (most recent call last):
File "./tlist.py", line 38, in <module>
pprint(u.lists)
File "/opt/mediascripts/lib/python3.6/site-packages/trakt/core.py", line 474, in inner
return generator.send(json_data)
File "/opt/mediascripts/lib/python3.6/site-packages/trakt/users.py", line 299, in lists
**extract_ids(ul)) for ul in data]
File "/opt/mediascripts/lib/python3.6/site-packages/trakt/users.py", line 299, in <listcomp>
**extract_ids(ul)) for ul in data]
TypeError: type object got multiple values for keyword argument 'user'
```
However, querying a specific list by name does work
`mylist = u.get_list('my-list-name')`
|
0.0
|
70f5bcc5215272665e2ca6f901d54da9d68e890a
|
[
"tests/test_users.py::test_user_list"
] |
[
"tests/test_calendars.py::test_my_shows",
"tests/test_calendars.py::test_my_premiere_calendar",
"tests/test_calendars.py::test_my_season_calendar",
"tests/test_calendars.py::test_my_movie_calendar",
"tests/test_calendars.py::test_show_calendar",
"tests/test_calendars.py::test_premiere_calendar",
"tests/test_calendars.py::test_season_calendar",
"tests/test_calendars.py::test_movie_calendar",
"tests/test_calendars.py::test_calendar_magic_methods",
"tests/test_episodes.py::test_get_episodes",
"tests/test_episodes.py::test_episode_search",
"tests/test_episodes.py::test_episode_search_with_year",
"tests/test_episodes.py::test_get_episode",
"tests/test_episodes.py::test_episode_comments",
"tests/test_episodes.py::test_episode_ratings",
"tests/test_episodes.py::test_episode_watching_now",
"tests/test_episodes.py::test_episode_images",
"tests/test_episodes.py::test_episode_ids",
"tests/test_episodes.py::test_rate_episode",
"tests/test_episodes.py::test_oneliners",
"tests/test_episodes.py::test_episode_comment",
"tests/test_episodes.py::test_episode_scrobble",
"tests/test_episodes.py::test_episode_magic_methods",
"tests/test_episodes.py::test_episode_aired_dates",
"tests/test_errors.py::test_trakt_exception",
"tests/test_errors.py::test_400_exception",
"tests/test_errors.py::test_401_exception",
"tests/test_errors.py::test_403_exception",
"tests/test_errors.py::test_404_exception",
"tests/test_errors.py::test_409_exception",
"tests/test_errors.py::test_422_exception",
"tests/test_errors.py::test_429_exception",
"tests/test_errors.py::test_500_exception",
"tests/test_errors.py::test_503_exception",
"tests/test_genres.py::test_genre_functions",
"tests/test_movies.py::test_trending_movies",
"tests/test_movies.py::test_updated_movies",
"tests/test_movies.py::test_get_movie",
"tests/test_movies.py::test_get_movie_images",
"tests/test_movies.py::test_movie_aliases",
"tests/test_movies.py::test_movie_releases",
"tests/test_movies.py::test_movie_translations",
"tests/test_movies.py::test_movie_comments",
"tests/test_movies.py::test_movie_people",
"tests/test_movies.py::test_movie_ratings",
"tests/test_movies.py::test_movie_related",
"tests/test_movies.py::test_movie_watching",
"tests/test_movies.py::test_get_recommended_movies",
"tests/test_movies.py::test_dismiss_movie_recommendation",
"tests/test_movies.py::test_movie_to_json_singular",
"tests/test_movies.py::test_movie_to_json",
"tests/test_movies.py::test_movie_str",
"tests/test_movies.py::test_movie_search",
"tests/test_movies.py::test_utilities",
"tests/test_movies.py::test_movie_comment",
"tests/test_movies.py::test_rate_movie",
"tests/test_movies.py::test_scrobble_movie",
"tests/test_people.py::test_get_person",
"tests/test_people.py::test_get_person_images",
"tests/test_people.py::test_person_magic_methods",
"tests/test_people.py::test_person_search",
"tests/test_people.py::test_credits_abc",
"tests/test_people.py::test_get_movie_credits",
"tests/test_people.py::test_get_tv_credits",
"tests/test_people.py::test_credit_magic_methods",
"tests/test_scrobble.py::test_scrobble",
"tests/test_scrobble.py::test_scrobbler_context_manager",
"tests/test_search.py::test_search_movie",
"tests/test_search.py::test_search_movie_with_year",
"tests/test_search.py::test_search_show",
"tests/test_search.py::test_search_episode",
"tests/test_search.py::test_search_person",
"tests/test_search.py::test_search_movie_by_id",
"tests/test_search.py::test_search_show_by_id",
"tests/test_search.py::test_search_episode_by_id",
"tests/test_search.py::test_search_person_by_id",
"tests/test_search.py::test_search_show_by_id_with_explicit_type",
"tests/test_search.py::test_search_by_id_with_multiple_results",
"tests/test_search.py::test_get_search_results",
"tests/test_seasons.py::test_get_seasons",
"tests/test_seasons.py::test_get_season",
"tests/test_seasons.py::test_season_comments",
"tests/test_seasons.py::test_season_ratings",
"tests/test_seasons.py::test_season_watching_now",
"tests/test_seasons.py::test_episodes_getter",
"tests/test_seasons.py::test_oneliners",
"tests/test_seasons.py::test_season_to_json",
"tests/test_seasons.py::test_season_magic_methods",
"tests/test_shows.py::test_dismiss_show_recomendation",
"tests/test_shows.py::test_recommended_shows",
"tests/test_shows.py::test_trending_shows",
"tests/test_shows.py::test_popular_shows",
"tests/test_shows.py::test_updated_shows",
"tests/test_shows.py::test_get_show",
"tests/test_shows.py::test_aliases",
"tests/test_shows.py::test_translations",
"tests/test_shows.py::test_get_comments",
"tests/test_shows.py::test_get_people",
"tests/test_shows.py::test_ratings",
"tests/test_shows.py::test_related",
"tests/test_shows.py::test_watching",
"tests/test_shows.py::test_show_search",
"tests/test_shows.py::test_show_search_with_year",
"tests/test_shows.py::test_show_ids",
"tests/test_shows.py::test_oneliners",
"tests/test_shows.py::test_show_comment",
"tests/test_shows.py::test_rate_show",
"tests/test_shows.py::test_next_episode",
"tests/test_shows.py::test_last_episode",
"tests/test_sync.py::test_create_comment",
"tests/test_sync.py::test_create_review",
"tests/test_sync.py::test_forced_review",
"tests/test_sync.py::test_rating",
"tests/test_sync.py::test_add_to_history",
"tests/test_sync.py::test_oneliners",
"tests/test_users.py::test_user_settings",
"tests/test_users.py::test_requests",
"tests/test_users.py::test_user",
"tests/test_users.py::test_user_collections",
"tests/test_users.py::test_follow_user",
"tests/test_users.py::test_get_others",
"tests/test_users.py::test_user_ratings",
"tests/test_users.py::test_user_watchlists",
"tests/test_users.py::test_watching",
"tests/test_users.py::test_watched",
"tests/test_users.py::test_stats",
"tests/test_utils.py::test_slugify",
"tests/test_utils.py::test_airs_date",
"tests/test_utils.py::test_now",
"tests/test_utils.py::test_timestamp",
"tests/test_utils.py::test_extract_ids"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-05-07 18:59:08+00:00
|
apache-2.0
| 4,028 |
|
mopidy__mopidy-local-31
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 32bf2bb..9576cfa 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -10,8 +10,9 @@ v3.1.0 (UNRELEASED)
- Add ``.cue`` to the list of excluded file extensions. (PR: #29)
- Replace ``os.path`` usage with ``pathlib`` to handle arbitrary file path
encodings better. (#20, PR: #30)
+- Add an ``included_files_extensions`` config. (#8, PR: #32)
-
+
v3.0.0 (2019-12-22)
===================
diff --git a/README.rst b/README.rst
index 6adafaa..e32fe4d 100644
--- a/README.rst
+++ b/README.rst
@@ -91,9 +91,16 @@ The following configuration values are available:
library it should try and store its progress so far. Some libraries might not
respect this setting. Set this to zero to disable flushing.
+- ``local/included_file_extensions``: File extensions to include when scanning
+ the media directory. Values should be separated by either comma or newline.
+ Each file extension should start with a dot, .e.g. ``.flac``. Setting any
+ values here will override the existence of ``local/excluded_file_extensions``.
+
- ``local/excluded_file_extensions``: File extensions to exclude when scanning
the media directory. Values should be separated by either comma or newline.
- Each file extension should start with a dot, .e.g. ``.html``.
+ Each file extension should start with a dot, .e.g. ``.html``. Defaults to a
+ list of common non-audio file extensions often found in music collections.
+ This config value has no effect if ``local/included_file_extensions`` is set.
- ``local/directories``: List of top-level directory names and URIs
for browsing.
diff --git a/mopidy_local/__init__.py b/mopidy_local/__init__.py
index d4d881a..225ecd2 100644
--- a/mopidy_local/__init__.py
+++ b/mopidy_local/__init__.py
@@ -26,6 +26,7 @@ class Extension(ext.Extension):
schema["scan_timeout"] = config.Integer(minimum=1000, maximum=1000 * 60 * 60)
schema["scan_flush_threshold"] = config.Integer(minimum=0)
schema["scan_follow_symlinks"] = config.Boolean()
+ schema["included_file_extensions"] = config.List(optional=True)
schema["excluded_file_extensions"] = config.List(optional=True)
schema["directories"] = config.List()
schema["timeout"] = config.Integer(optional=True, minimum=1)
diff --git a/mopidy_local/commands.py b/mopidy_local/commands.py
index 5dc213d..f195614 100644
--- a/mopidy_local/commands.py
+++ b/mopidy_local/commands.py
@@ -81,6 +81,10 @@ class ScanCommand(commands.Command):
media_dir=media_dir,
file_mtimes=file_mtimes,
files_in_library=files_in_library,
+ included_file_exts=[
+ file_ext.lower()
+ for file_ext in config["local"]["included_file_extensions"]
+ ],
excluded_file_exts=[
file_ext.lower()
for file_ext in config["local"]["excluded_file_extensions"]
@@ -143,19 +147,56 @@ class ScanCommand(commands.Command):
return files_to_update, files_in_library
def _find_files_to_scan(
- self, *, media_dir, file_mtimes, files_in_library, excluded_file_exts
+ self,
+ *,
+ media_dir,
+ file_mtimes,
+ files_in_library,
+ included_file_exts,
+ excluded_file_exts,
):
files_to_update = set()
+ def _is_hidden_file(relative_path, file_uri):
+ if any(p.startswith(".") for p in relative_path.parts):
+ logger.debug(f"Skipped {file_uri}: Hidden directory/file")
+ return True
+ else:
+ return False
+
+ def _extension_filters(
+ relative_path, file_uri, included_file_exts, excluded_file_exts
+ ):
+ if included_file_exts:
+ if relative_path.suffix.lower() in included_file_exts:
+ logger.debug(f"Added {file_uri}: File extension on included list")
+ return True
+ else:
+ logger.debug(
+ f"Skipped {file_uri}: File extension not on included list"
+ )
+ return False
+ else:
+ if relative_path.suffix.lower() in excluded_file_exts:
+ logger.debug(f"Skipped {file_uri}: File extension on excluded list")
+ return False
+ else:
+ logger.debug(
+ f"Included {file_uri}: File extension not on excluded list"
+ )
+ return True
+
for absolute_path in file_mtimes:
relative_path = absolute_path.relative_to(media_dir)
file_uri = absolute_path.as_uri()
- if any(p.startswith(".") for p in relative_path.parts):
- logger.debug(f"Skipped {file_uri}: Hidden directory/file")
- elif relative_path.suffix.lower() in excluded_file_exts:
- logger.debug(f"Skipped {file_uri}: File extension excluded")
- elif absolute_path not in files_in_library:
+ if (
+ not _is_hidden_file(relative_path, file_uri)
+ and _extension_filters(
+ relative_path, file_uri, included_file_exts, excluded_file_exts
+ )
+ and absolute_path not in files_in_library
+ ):
files_to_update.add(absolute_path)
logger.info(f"Found {len(files_to_update)} tracks which need to be updated")
diff --git a/mopidy_local/ext.conf b/mopidy_local/ext.conf
index cbe97df..08e1f85 100644
--- a/mopidy_local/ext.conf
+++ b/mopidy_local/ext.conf
@@ -5,6 +5,7 @@ media_dir = $XDG_MUSIC_DIR
scan_timeout = 1000
scan_flush_threshold = 100
scan_follow_symlinks = false
+included_file_extensions =
excluded_file_extensions =
.cue
.directory
@@ -18,6 +19,7 @@ excluded_file_extensions =
.txt
.zip
+
# top-level directories for browsing, as <name> <uri>
directories =
Albums local:directory?type=album
diff --git a/mopidy_local/library.py b/mopidy_local/library.py
index e77460e..61ae109 100644
--- a/mopidy_local/library.py
+++ b/mopidy_local/library.py
@@ -1,4 +1,3 @@
-import hashlib
import logging
import operator
import sqlite3
@@ -203,9 +202,3 @@ class LocalLibraryProvider(backend.LibraryProvider):
return [{"album": uri}]
else:
return []
-
- def _model_uri(self, type, model):
- if model.musicbrainz_id and self._config["use_%s_mbid_uri" % type]:
- return f"local:{type}:mbid:{model.musicbrainz_id}"
- digest = hashlib.md5(str(model)).hexdigest()
- return f"local:{type}:md5:{digest}"
diff --git a/mopidy_local/storage.py b/mopidy_local/storage.py
index d5b28fd..a8679c3 100644
--- a/mopidy_local/storage.py
+++ b/mopidy_local/storage.py
@@ -31,10 +31,7 @@ def get_image_size_gif(data):
def model_uri(type, model):
- # only use valid mbids; TODO: use regex for that?
- if model.musicbrainz_id and len(model.musicbrainz_id) == 36:
- return f"local:{type}:mbid:{model.musicbrainz_id}"
- elif type == "album":
+ if type == "album":
# ignore num_tracks for multi-disc albums
digest = hashlib.md5(str(model.replace(num_tracks=None)).encode())
else:
|
mopidy/mopidy-local
|
6865fac7254674170d1d2a92e3302dcd10b337da
|
diff --git a/tests/test_extension.py b/tests/test_extension.py
index e11c4a1..ff79cc2 100644
--- a/tests/test_extension.py
+++ b/tests/test_extension.py
@@ -23,6 +23,7 @@ def test_get_config_schema():
assert "scan_timeout" in schema
assert "scan_flush_threshold" in schema
assert "scan_follow_symlinks" in schema
+ assert "included_file_extensions" in schema
assert "excluded_file_extensions" in schema
# from mopidy-local-sqlite
assert "directories" in schema
|
Put back the use_album_mbid_uri option that was in local-sqlite
Using MBIDs to create uris can have unintended consequences. With local-sqlite I could switch this off but this option seems to have been removed in the new mopidy-local.
As an example, I have 2 albums that I tagged with Musicbrainz Picard.
One has 'Artist = Brian Eno'
One has 'Artist = Brian Eno & Jah Wobble'
They're also tagged with musicbrainz IDs for the artists. The second album has two artist ID tags even though it only has one artist. (This is the way Musicbrainz reccomend it is done). Since the scanner can only use one mbid to create the artist URI, both albums end up under 'Brian Eno and Jah Wobble'.
With the old local-sqlite setting use_album_mbid_uri = false in mopidy.conf fixed this.
|
0.0
|
6865fac7254674170d1d2a92e3302dcd10b337da
|
[
"tests/test_extension.py::test_get_config_schema"
] |
[
"tests/test_extension.py::test_get_default_config"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-05 15:56:16+00:00
|
apache-2.0
| 4,029 |
|
mopidy__mopidy-local-32
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 32bf2bb..9576cfa 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -10,8 +10,9 @@ v3.1.0 (UNRELEASED)
- Add ``.cue`` to the list of excluded file extensions. (PR: #29)
- Replace ``os.path`` usage with ``pathlib`` to handle arbitrary file path
encodings better. (#20, PR: #30)
+- Add an ``included_files_extensions`` config. (#8, PR: #32)
-
+
v3.0.0 (2019-12-22)
===================
diff --git a/README.rst b/README.rst
index 6adafaa..e32fe4d 100644
--- a/README.rst
+++ b/README.rst
@@ -91,9 +91,16 @@ The following configuration values are available:
library it should try and store its progress so far. Some libraries might not
respect this setting. Set this to zero to disable flushing.
+- ``local/included_file_extensions``: File extensions to include when scanning
+ the media directory. Values should be separated by either comma or newline.
+ Each file extension should start with a dot, .e.g. ``.flac``. Setting any
+ values here will override the existence of ``local/excluded_file_extensions``.
+
- ``local/excluded_file_extensions``: File extensions to exclude when scanning
the media directory. Values should be separated by either comma or newline.
- Each file extension should start with a dot, .e.g. ``.html``.
+ Each file extension should start with a dot, .e.g. ``.html``. Defaults to a
+ list of common non-audio file extensions often found in music collections.
+ This config value has no effect if ``local/included_file_extensions`` is set.
- ``local/directories``: List of top-level directory names and URIs
for browsing.
diff --git a/mopidy_local/__init__.py b/mopidy_local/__init__.py
index d4d881a..225ecd2 100644
--- a/mopidy_local/__init__.py
+++ b/mopidy_local/__init__.py
@@ -26,6 +26,7 @@ class Extension(ext.Extension):
schema["scan_timeout"] = config.Integer(minimum=1000, maximum=1000 * 60 * 60)
schema["scan_flush_threshold"] = config.Integer(minimum=0)
schema["scan_follow_symlinks"] = config.Boolean()
+ schema["included_file_extensions"] = config.List(optional=True)
schema["excluded_file_extensions"] = config.List(optional=True)
schema["directories"] = config.List()
schema["timeout"] = config.Integer(optional=True, minimum=1)
diff --git a/mopidy_local/commands.py b/mopidy_local/commands.py
index 5dc213d..f195614 100644
--- a/mopidy_local/commands.py
+++ b/mopidy_local/commands.py
@@ -81,6 +81,10 @@ class ScanCommand(commands.Command):
media_dir=media_dir,
file_mtimes=file_mtimes,
files_in_library=files_in_library,
+ included_file_exts=[
+ file_ext.lower()
+ for file_ext in config["local"]["included_file_extensions"]
+ ],
excluded_file_exts=[
file_ext.lower()
for file_ext in config["local"]["excluded_file_extensions"]
@@ -143,19 +147,56 @@ class ScanCommand(commands.Command):
return files_to_update, files_in_library
def _find_files_to_scan(
- self, *, media_dir, file_mtimes, files_in_library, excluded_file_exts
+ self,
+ *,
+ media_dir,
+ file_mtimes,
+ files_in_library,
+ included_file_exts,
+ excluded_file_exts,
):
files_to_update = set()
+ def _is_hidden_file(relative_path, file_uri):
+ if any(p.startswith(".") for p in relative_path.parts):
+ logger.debug(f"Skipped {file_uri}: Hidden directory/file")
+ return True
+ else:
+ return False
+
+ def _extension_filters(
+ relative_path, file_uri, included_file_exts, excluded_file_exts
+ ):
+ if included_file_exts:
+ if relative_path.suffix.lower() in included_file_exts:
+ logger.debug(f"Added {file_uri}: File extension on included list")
+ return True
+ else:
+ logger.debug(
+ f"Skipped {file_uri}: File extension not on included list"
+ )
+ return False
+ else:
+ if relative_path.suffix.lower() in excluded_file_exts:
+ logger.debug(f"Skipped {file_uri}: File extension on excluded list")
+ return False
+ else:
+ logger.debug(
+ f"Included {file_uri}: File extension not on excluded list"
+ )
+ return True
+
for absolute_path in file_mtimes:
relative_path = absolute_path.relative_to(media_dir)
file_uri = absolute_path.as_uri()
- if any(p.startswith(".") for p in relative_path.parts):
- logger.debug(f"Skipped {file_uri}: Hidden directory/file")
- elif relative_path.suffix.lower() in excluded_file_exts:
- logger.debug(f"Skipped {file_uri}: File extension excluded")
- elif absolute_path not in files_in_library:
+ if (
+ not _is_hidden_file(relative_path, file_uri)
+ and _extension_filters(
+ relative_path, file_uri, included_file_exts, excluded_file_exts
+ )
+ and absolute_path not in files_in_library
+ ):
files_to_update.add(absolute_path)
logger.info(f"Found {len(files_to_update)} tracks which need to be updated")
diff --git a/mopidy_local/ext.conf b/mopidy_local/ext.conf
index cbe97df..08e1f85 100644
--- a/mopidy_local/ext.conf
+++ b/mopidy_local/ext.conf
@@ -5,6 +5,7 @@ media_dir = $XDG_MUSIC_DIR
scan_timeout = 1000
scan_flush_threshold = 100
scan_follow_symlinks = false
+included_file_extensions =
excluded_file_extensions =
.cue
.directory
@@ -18,6 +19,7 @@ excluded_file_extensions =
.txt
.zip
+
# top-level directories for browsing, as <name> <uri>
directories =
Albums local:directory?type=album
|
mopidy/mopidy-local
|
6865fac7254674170d1d2a92e3302dcd10b337da
|
diff --git a/tests/test_extension.py b/tests/test_extension.py
index e11c4a1..ff79cc2 100644
--- a/tests/test_extension.py
+++ b/tests/test_extension.py
@@ -23,6 +23,7 @@ def test_get_config_schema():
assert "scan_timeout" in schema
assert "scan_flush_threshold" in schema
assert "scan_follow_symlinks" in schema
+ assert "included_file_extensions" in schema
assert "excluded_file_extensions" in schema
# from mopidy-local-sqlite
assert "directories" in schema
|
[Feature request] Opposite of excluded_file_extensions
My music collection has a lot of extra files cluttering it up, so it took me a while to build up the `local/excluded_file_extensions` option to skip all of them. I thought it would be more useful to have an `included_file_extensions` option, because a list of typical music file extensions is smaller. That could give you a bit of a problem if both options are used, but you could probably just deprecate and ignore `excluded_file_extensions`.
|
0.0
|
6865fac7254674170d1d2a92e3302dcd10b337da
|
[
"tests/test_extension.py::test_get_config_schema"
] |
[
"tests/test_extension.py::test_get_default_config"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2020-01-05 18:03:30+00:00
|
apache-2.0
| 4,030 |
|
mopidy__mopidy-local-59
|
diff --git a/mopidy_local/storage.py b/mopidy_local/storage.py
index a8679c3..9f9947c 100644
--- a/mopidy_local/storage.py
+++ b/mopidy_local/storage.py
@@ -58,6 +58,15 @@ def get_image_size_jpeg(data):
return width, height
+def test_jpeg(data, file_handle):
+ # Additional JPEG detection looking for JPEG SOI marker
+ if data[:2] == b"\xff\xd8":
+ return "jpeg"
+
+
+imghdr.tests.append(test_jpeg)
+
+
class LocalStorageProvider:
def __init__(self, config):
self._config = ext_config = config[Extension.ext_name]
|
mopidy/mopidy-local
|
00e3ef4fa95f6ba313455245cde9d1b7baf623e4
|
diff --git a/tests/test_storage.py b/tests/test_storage.py
new file mode 100644
index 0000000..6caed2c
--- /dev/null
+++ b/tests/test_storage.py
@@ -0,0 +1,16 @@
+import pytest
+
+from mopidy_local import storage
+
+
[email protected](
+ "data",
+ [
+ pytest.param("ffd8ffe000104a46494600", id="JFIF"),
+ pytest.param("ffd8ffe100184578696600", id="Exif"),
+ pytest.param("ffd8ffe1095068747470", id="XMP"),
+ ],
+)
+def test_jpeg_detection(data):
+ data_bytes = bytes.fromhex(data)
+ assert storage.imghdr.what(None, data_bytes) is not None
|
Not extracting images from m4a files when scanning
Whenever I execute `mopidy local scan --force` in my terminal, I get an error extracting the image from any m4a file.
Example: `WARNING 2021-02-20 22:42:52,743 [111960:MainThread] mopidy_local.storage
Error extracting images for 'local:track:MDMA/Genie%20%28Deluxe%29/01%20Xccelerate.m4a': ValueError('Unknown image type')`
I can play these files completely fine with ncmpcpp's file browser and they are tagged properly too but I can't scan them into my library.
|
0.0
|
00e3ef4fa95f6ba313455245cde9d1b7baf623e4
|
[
"tests/test_storage.py::test_jpeg_detection[XMP]"
] |
[
"tests/test_storage.py::test_jpeg_detection[JFIF]",
"tests/test_storage.py::test_jpeg_detection[Exif]"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2021-02-23 23:53:29+00:00
|
apache-2.0
| 4,031 |
|
mopidy__mopidy-spotify-365
|
diff --git a/mopidy_spotify/images.py b/mopidy_spotify/images.py
index 01adf2c..7dec2d8 100644
--- a/mopidy_spotify/images.py
+++ b/mopidy_spotify/images.py
@@ -15,7 +15,8 @@ logger = logging.getLogger(__name__)
def get_images(web_client, uris):
result = {}
uri_type_getter = operator.itemgetter("type")
- uris = sorted((_parse_uri(u) for u in uris), key=uri_type_getter)
+ uris = (_parse_uri(u) for u in uris)
+ uris = sorted((u for u in uris if u), key=uri_type_getter)
for uri_type, group in itertools.groupby(uris, uri_type_getter):
batch = []
for uri in group:
@@ -33,25 +34,27 @@ def get_images(web_client, uris):
def _parse_uri(uri):
- parsed_uri = urllib.parse.urlparse(uri)
- uri_type, uri_id = None, None
-
- if parsed_uri.scheme == "spotify":
- uri_type, uri_id = parsed_uri.path.split(":")[:2]
- elif parsed_uri.scheme in ("http", "https"):
- if parsed_uri.netloc in ("open.spotify.com", "play.spotify.com"):
- uri_type, uri_id = parsed_uri.path.split("/")[1:3]
-
- supported_types = ("track", "album", "artist", "playlist")
- if uri_type and uri_type in supported_types and uri_id:
- return {
- "uri": uri,
- "type": uri_type,
- "id": uri_id,
- "key": (uri_type, uri_id),
- }
-
- raise ValueError(f"Could not parse {repr(uri)} as a Spotify URI")
+ try:
+ parsed_uri = urllib.parse.urlparse(uri)
+ uri_type, uri_id = None, None
+
+ if parsed_uri.scheme == "spotify":
+ uri_type, uri_id = parsed_uri.path.split(":")[:2]
+ elif parsed_uri.scheme in ("http", "https"):
+ if parsed_uri.netloc in ("open.spotify.com", "play.spotify.com"):
+ uri_type, uri_id = parsed_uri.path.split("/")[1:3]
+
+ supported_types = ("track", "album", "artist", "playlist")
+ if uri_type and uri_type in supported_types and uri_id:
+ return {
+ "uri": uri,
+ "type": uri_type,
+ "id": uri_id,
+ "key": (uri_type, uri_id),
+ }
+ raise ValueError("Unknown error")
+ except Exception as e:
+ logger.exception(f"Could not parse {repr(uri)} as a Spotify URI ({e})")
def _process_uri(web_client, uri):
@@ -80,7 +83,10 @@ def _process_uris(web_client, uri_type, uris):
if uri["key"] not in _cache:
if uri_type == "track":
- album_key = _parse_uri(item["album"]["uri"])["key"]
+ album = _parse_uri(item["album"]["uri"])
+ if not album:
+ continue
+ album_key = album["key"]
if album_key not in _cache:
_cache[album_key] = tuple(
_translate_image(i) for i in item["album"]["images"]
diff --git a/mopidy_spotify/web.py b/mopidy_spotify/web.py
index a937d06..b5ebea5 100644
--- a/mopidy_spotify/web.py
+++ b/mopidy_spotify/web.py
@@ -196,7 +196,7 @@ class OAuthClient:
# Decide how long to sleep in the next iteration.
backoff_time = backoff_time or (2**i * self._backoff_factor)
- logger.debug(
+ logger.error(
f"Retrying {prepared_request.url} in {backoff_time:.3f} "
"seconds."
)
diff --git a/tox.ini b/tox.ini
index 209e644..a5ad7c1 100644
--- a/tox.ini
+++ b/tox.ini
@@ -5,7 +5,7 @@ envlist = py39, py310, py311, check-manifest, flake8
sitepackages = true
deps = .[test]
commands =
- python -m pytest \
+ python -m pytest -vv \
--basetemp={envtmpdir} \
--cov=mopidy_spotify --cov-report=term-missing \
{posargs}
|
mopidy/mopidy-spotify
|
a82e1b2016dbfeddb4ac9c6027c2cdaf0331b9b1
|
diff --git a/tests/test_images.py b/tests/test_images.py
index 0ead783..cc67e9a 100644
--- a/tests/test_images.py
+++ b/tests/test_images.py
@@ -127,6 +127,27 @@ def test_get_track_images(web_client_mock, img_provider):
assert image.width == 640
+def test_get_track_images_bad_album_uri(web_client_mock, img_provider):
+ uris = ["spotify:track:41shEpOKyyadtG6lDclooa"]
+
+ web_client_mock.get.return_value = {
+ "tracks": [
+ {
+ "id": "41shEpOKyyadtG6lDclooa",
+ "album": {
+ "uri": "spotify:bad-data",
+ "images": [
+ {"height": 640, "url": "img://1/a", "width": 640}
+ ],
+ },
+ }
+ ]
+ }
+
+ result = img_provider.get_images(uris)
+ assert result == {}
+
+
def test_get_relinked_track_images(web_client_mock, img_provider):
uris = ["spotify:track:4nqN0p0FjfH39G3hxeuKad"]
@@ -167,7 +188,7 @@ def test_get_relinked_track_images(web_client_mock, img_provider):
def test_get_playlist_image(web_client_mock, img_provider):
- uris = ["spotify:playlist:41shEpOKyyadtG6lDclooa"]
+ uris = ["spotify:playlist:41shEpOKyyadtG6lDclooa", "foo:bar"]
web_client_mock.get.return_value = {
"id": "41shEpOKyyadtG6lDclooa",
@@ -181,7 +202,7 @@ def test_get_playlist_image(web_client_mock, img_provider):
)
assert len(result) == 1
- assert sorted(result.keys()) == sorted(uris)
+ assert sorted(result.keys()) == ["spotify:playlist:41shEpOKyyadtG6lDclooa"]
assert len(result[uris[0]]) == 1
image = result[uris[0]][0]
@@ -231,11 +252,11 @@ def test_max_50_ids_per_request(web_client_mock, img_provider):
assert request_ids_2 == "50"
-def test_invalid_uri_fails(img_provider):
- with pytest.raises(ValueError) as exc:
- img_provider.get_images(["foo:bar"])
-
- assert str(exc.value) == "Could not parse 'foo:bar' as a Spotify URI"
+def test_invalid_uri(img_provider, caplog):
+ with caplog.at_level(5):
+ result = img_provider.get_images(["foo:bar"])
+ assert result == {}
+ assert "Could not parse 'foo:bar' as a Spotify URI" in caplog.text
def test_no_uris_gives_no_results(img_provider):
diff --git a/tests/test_web.py b/tests/test_web.py
index 90358aa..e589f1d 100644
--- a/tests/test_web.py
+++ b/tests/test_web.py
@@ -620,9 +620,7 @@ def test_cache_normalised_query_string(
assert "tracks/abc?b=bar&f=cat" in cache
[email protected](
- "status,expected", [(304, "spotify:track:abc"), (200, "spotify:track:xyz")]
-)
[email protected]("status,unchanged", [(304, True), (200, False)])
@responses.activate
def test_cache_expired_with_etag(
web_response_mock_etag,
@@ -630,23 +628,24 @@ def test_cache_expired_with_etag(
skip_refresh_token,
oauth_client,
status,
- expected,
+ unchanged,
+ caplog,
):
cache = {"tracks/abc": web_response_mock_etag}
responses.add(
responses.GET,
"https://api.spotify.com/v1/tracks/abc",
- json={"uri": "spotify:track:xyz"},
status=status,
)
- mock_time.return_value = 1001
+ mock_time.return_value = web_response_mock_etag._expires + 1
assert not cache["tracks/abc"].still_valid()
result = oauth_client.get("tracks/abc", cache)
assert len(responses.calls) == 1
assert responses.calls[0].request.headers["If-None-Match"] == '"1234"'
- assert result["uri"] == expected
assert cache["tracks/abc"] == result
+ assert result.status_unchanged is unchanged
+ assert (result.items() == web_response_mock_etag.items()) == unchanged
@responses.activate
|
Browsing in Spotify Library doesn't work
Hey,
im getting an error when browsing Spotify via Iris Webbrowser:
INFO 2023-10-19 13:01:03,083 [9405:SpotifyBackend-6 (_actor_loop)] mopidy_spotify.lookup
Failed to lookup 'spotify:directory': Could not parse 'spotify:directory' as a Spotify URI
ERROR 2023-10-19 13:01:03,116 [9405:Core-8 (_actor_loop)] mopidy.core.library
SpotifyBackend backend caused an exception.
Traceback (most recent call last):
File "/usr/local/lib/python3.11/dist-packages/mopidy/core/library.py", line 17, in _backend_error_handling
yield
File "/usr/local/lib/python3.11/dist-packages/mopidy/core/library.py", line 194, in get_images
if future.get() is None:
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/pykka/_threading.py", line 68, in get
raise exc_value
File "/usr/local/lib/python3.11/dist-packages/pykka/_actor.py", line 238, in _actor_loop_running
response = self._handle_receive(envelope.message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/pykka/_actor.py", line 349, in _handle_receive
return callee(*message.args, **message.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/mopidy_spotify/library.py", line 35, in get_images
return images.get_images(self._backend._web_client, uris)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/mopidy_spotify/images.py", line 18, in get_images
uris = sorted((_parse_uri(u) for u in uris), key=uri_type_getter)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/mopidy_spotify/images.py", line 18, in <genexpr>
uris = sorted((_parse_uri(u) for u in uris), key=uri_type_getter)
^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/mopidy_spotify/images.py", line 40, in _parse_uri
uri_type, uri_id = parsed_uri.path.split(":")[:2]
^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 2, got 1)
ERROR 2023-10-19 13:01:03,135 [9405:Core-8 (_actor_loop)] mopidy.core.library
SpotifyBackend backend caused an exception.
Traceback (most recent call last):
File "/usr/local/lib/python3.11/dist-packages/mopidy/core/library.py", line 17, in _backend_error_handling
yield
File "/usr/local/lib/python3.11/dist-packages/mopidy/core/library.py", line 194, in get_images
if future.get() is None:
^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/pykka/_threading.py", line 68, in get
raise exc_value
File "/usr/local/lib/python3.11/dist-packages/pykka/_actor.py", line 238, in _actor_loop_running
response = self._handle_receive(envelope.message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/pykka/_actor.py", line 349, in _handle_receive
return callee(*message.args, **message.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/mopidy_spotify/library.py", line 35, in get_images
return images.get_images(self._backend._web_client, uris)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/mopidy_spotify/images.py", line 18, in get_images
uris = sorted((_parse_uri(u) for u in uris), key=uri_type_getter)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/mopidy_spotify/images.py", line 18, in <genexpr>
uris = sorted((_parse_uri(u) for u in uris), key=uri_type_getter)
^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dist-packages/mopidy_spotify/images.py", line 40, in _parse_uri
uri_type, uri_id = parsed_uri.path.split(":")[:2]
^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 2, got 1)
the requested URI is:
spotify:directory
|
0.0
|
a82e1b2016dbfeddb4ac9c6027c2cdaf0331b9b1
|
[
"tests/test_images.py::test_get_track_images_bad_album_uri",
"tests/test_images.py::test_get_playlist_image",
"tests/test_images.py::test_invalid_uri"
] |
[
"tests/test_images.py::test_get_artist_images",
"tests/test_images.py::test_get_album_images",
"tests/test_images.py::test_get_track_images",
"tests/test_images.py::test_get_relinked_track_images",
"tests/test_images.py::test_results_are_cached",
"tests/test_images.py::test_max_50_ids_per_request",
"tests/test_images.py::test_no_uris_gives_no_results",
"tests/test_images.py::test_service_returns_empty_result",
"tests/test_web.py::test_initial_refresh_token",
"tests/test_web.py::test_expired_refresh_token",
"tests/test_web.py::test_still_valid_refresh_token",
"tests/test_web.py::test_user_agent",
"tests/test_web.py::test_parse_retry_after[None-0]",
"tests/test_web.py::test_parse_retry_after[-0]",
"tests/test_web.py::test_parse_retry_after[1-1]",
"tests/test_web.py::test_parse_retry_after[-1-0]",
"tests/test_web.py::test_parse_retry_after[",
"tests/test_web.py::test_parse_retry_after[2",
"tests/test_web.py::test_parse_retry_after[foo-0]",
"tests/test_web.py::test_parse_retry_after[Wed,",
"tests/test_web.py::test_parse_retry_after[foobar-0]",
"tests/test_web.py::test_request_exception",
"tests/test_web.py::test_get_uses_new_access_token",
"tests/test_web.py::test_get_uses_existing_access_token",
"tests/test_web.py::test_bad_client_credentials",
"tests/test_web.py::test_auth_returns_invalid_json",
"tests/test_web.py::test_spotify_returns_invalid_json",
"tests/test_web.py::test_auth_offline",
"tests/test_web.py::test_spotify_offline",
"tests/test_web.py::test_auth_missing_access_token",
"tests/test_web.py::test_auth_wrong_token_type",
"tests/test_web.py::test_parse_cache_control[no-store-100]",
"tests/test_web.py::test_parse_cache_control[max-age=1-101]",
"tests/test_web.py::test_parse_cache_control[max-age=2000-2100]",
"tests/test_web.py::test_parse_cache_control[max-age=2000,",
"tests/test_web.py::test_parse_cache_control[stuff,",
"tests/test_web.py::test_parse_cache_control[max-age=junk-100]",
"tests/test_web.py::test_parse_cache_control[-100]",
"tests/test_web.py::test_parse_etag[-None]",
"tests/test_web.py::test_parse_etag[\"",
"tests/test_web.py::test_parse_etag[33a6ff-None]",
"tests/test_web.py::test_parse_etag[\"33a6ff\"-\"33a6ff\"]",
"tests/test_web.py::test_parse_etag[\"33\"a6ff\"-None]",
"tests/test_web.py::test_parse_etag[\"33\\na6ff\"-None]",
"tests/test_web.py::test_parse_etag[W/\"33a6ff\"-\"33a6ff\"]",
"tests/test_web.py::test_parse_etag[\"#aa44-cc1-23==@!\"-\"#aa44-cc1-23==@!\"]",
"tests/test_web.py::test_web_response_status_ok[200-True]",
"tests/test_web.py::test_web_response_status_ok[301-True]",
"tests/test_web.py::test_web_response_status_ok[400-False]",
"tests/test_web.py::test_web_response_status_unchanged[200-False]",
"tests/test_web.py::test_web_response_status_unchanged[301-False]",
"tests/test_web.py::test_web_response_status_unchanged[304-True]",
"tests/test_web.py::test_web_response_status_unchanged[400-False]",
"tests/test_web.py::test_web_response_status_unchanged_from_cache",
"tests/test_web.py::test_web_response_etag_headers[\"1234\"-expected0]",
"tests/test_web.py::test_web_response_etag_headers[fish-expected1]",
"tests/test_web.py::test_web_response_etag_headers[None-expected2]",
"tests/test_web.py::test_web_response_etag_updated[abcd-200-False-abcd-ETag",
"tests/test_web.py::test_web_response_etag_updated[abcd-404-False-abcd-ETag",
"tests/test_web.py::test_web_response_etag_updated[abcd-304-True-efgh-ETag",
"tests/test_web.py::test_web_response_etag_updated[None-304-False-None-]",
"tests/test_web.py::test_web_response_etag_updated_different",
"tests/test_web.py::test_should_cache_response[None-False-False]",
"tests/test_web.py::test_should_cache_response[None-True-False]",
"tests/test_web.py::test_should_cache_response[cache2-False-False]",
"tests/test_web.py::test_should_cache_response[cache3-True-True]",
"tests/test_web.py::test_normalise_query_string[tracks/abc?foo=bar&foo=5-None-tracks/abc?foo=5]",
"tests/test_web.py::test_normalise_query_string[tracks/abc?foo=bar&bar=9-None-tracks/abc?bar=9&foo=bar]",
"tests/test_web.py::test_normalise_query_string[tracks/abc-params2-tracks/abc?foo=bar]",
"tests/test_web.py::test_normalise_query_string[tracks/abc?foo=bar-params3-tracks/abc?bar=foo&foo=bar]",
"tests/test_web.py::test_normalise_query_string[tracks/abc?foo=bar-params4-tracks/abc?foo=foo]",
"tests/test_web.py::test_web_response",
"tests/test_web.py::test_cache_miss",
"tests/test_web.py::test_cache_response_still_valid",
"tests/test_web.py::test_cache_response_expired",
"tests/test_web.py::test_cache_response_ignore_expiry",
"tests/test_web.py::test_dont_cache_bad_status",
"tests/test_web.py::test_cache_key_uses_path",
"tests/test_web.py::test_cache_normalised_query_string",
"tests/test_web.py::test_cache_expired_with_etag[304-True]",
"tests/test_web.py::test_cache_expired_with_etag[200-False]",
"tests/test_web.py::test_cache_miss_no_etag",
"tests/test_web.py::test_increase_expiry",
"tests/test_web.py::test_increase_expiry_skipped_for_bad_status",
"tests/test_web.py::test_increase_expiry_skipped_for_cached_response",
"tests/test_web.py::test_fresh_response_changed",
"tests/test_web.py::test_cached_response_unchanged",
"tests/test_web.py::test_updated_responses_changed",
"tests/test_web.py::TestSpotifyOAuthClient::test_track_required_fields[next]",
"tests/test_web.py::TestSpotifyOAuthClient::test_track_required_fields[items(track]",
"tests/test_web.py::TestSpotifyOAuthClient::test_track_required_fields[type]",
"tests/test_web.py::TestSpotifyOAuthClient::test_track_required_fields[uri]",
"tests/test_web.py::TestSpotifyOAuthClient::test_track_required_fields[name]",
"tests/test_web.py::TestSpotifyOAuthClient::test_track_required_fields[is_playable]",
"tests/test_web.py::TestSpotifyOAuthClient::test_track_required_fields[linked_from]",
"tests/test_web.py::TestSpotifyOAuthClient::test_playlist_required_fields[name0]",
"tests/test_web.py::TestSpotifyOAuthClient::test_playlist_required_fields[type]",
"tests/test_web.py::TestSpotifyOAuthClient::test_playlist_required_fields[uri]",
"tests/test_web.py::TestSpotifyOAuthClient::test_playlist_required_fields[name1]",
"tests/test_web.py::TestSpotifyOAuthClient::test_playlist_required_fields[snapshot_id]",
"tests/test_web.py::TestSpotifyOAuthClient::test_playlist_required_fields[tracks]",
"tests/test_web.py::TestSpotifyOAuthClient::test_configures_auth",
"tests/test_web.py::TestSpotifyOAuthClient::test_configures_proxy",
"tests/test_web.py::TestSpotifyOAuthClient::test_configures_urls",
"tests/test_web.py::TestSpotifyOAuthClient::test_login_alice",
"tests/test_web.py::TestSpotifyOAuthClient::test_login_fails",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_one_error",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_one_cached",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_one_increased_expiry",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_one_retry_header",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_all",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_all_none",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_user_playlists_empty",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_user_playlists_sets_params",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_user_playlists",
"tests/test_web.py::TestSpotifyOAuthClient::test_with_all_tracks_error",
"tests/test_web.py::TestSpotifyOAuthClient::test_with_all_tracks",
"tests/test_web.py::TestSpotifyOAuthClient::test_with_all_tracks_uses_cached_tracks_when_unchanged",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist[spotify:user:alice:playlist:bar-True]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist[spotify:user:alice:playlist:fake-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist[spotify:playlist:bar-True]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist[spotify:track:foo-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist[https://play.spotify.com/foo-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist[total/junk-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist_sets_params_for_playlist",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist_error",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist_sets_params_for_tracks",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist_collates_tracks",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist_error_msg[spotify:artist:foo-Spotify",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_playlist_error_msg[my-bad-uri-Spotify]",
"tests/test_web.py::TestSpotifyOAuthClient::test_clear_cache",
"tests/test_web.py::TestSpotifyOAuthClient::test_logged_in[alice-True]",
"tests/test_web.py::TestSpotifyOAuthClient::test_logged_in[None-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_album",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_album_wrong_linktype",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_artist_albums[True]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_artist_albums[False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_artist_albums_error",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_artist_albums_wrong_linktype",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_artist_albums_value_error",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_track[spotify:track:abc-True]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_track[spotify:track:xyz-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_track[spotify:user:alice:playlist:bar-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_track[spotify:playlist:bar-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_track[spotify:artist:baz-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_track[spotify:album:foo-False]",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_artist_top_tracks",
"tests/test_web.py::TestSpotifyOAuthClient::test_get_artist_top_tracks_invalid_uri",
"tests/test_web.py::test_weblink_from_uri_spotify_uri[spotify:playlist:foo-LinkType.PLAYLIST-foo]",
"tests/test_web.py::test_weblink_from_uri_spotify_uri[spotify:track:bar-LinkType.TRACK-bar]",
"tests/test_web.py::test_weblink_from_uri_spotify_uri[spotify:artist:blah-LinkType.ARTIST-blah]",
"tests/test_web.py::test_weblink_from_uri_spotify_uri[spotify:album:stuff-LinkType.ALBUM-stuff]",
"tests/test_web.py::test_weblink_from_uri_spotify_uri[spotify:your:albums-LinkType.YOUR-None]",
"tests/test_web.py::test_weblink_from_uri_playlist[spotify:user:alice:playlist:foo-foo-alice]",
"tests/test_web.py::test_weblink_from_uri_playlist[spotify:user:alice:starred-None-alice]",
"tests/test_web.py::test_weblink_from_uri_playlist[spotify:playlist:foo-foo-None]",
"tests/test_web.py::test_weblink_from_uri_playlist[http://open.spotify.com/playlist/foo-foo-None]",
"tests/test_web.py::test_weblink_from_uri_playlist[https://open.spotify.com/playlist/foo-foo-None]",
"tests/test_web.py::test_weblink_from_uri_playlist[https://play.spotify.com/playlist/foo-foo-None]",
"tests/test_web.py::test_weblink_from_uri_raises[spotify:user:alice:track:foo]",
"tests/test_web.py::test_weblink_from_uri_raises[local:user:alice:playlist:foo]",
"tests/test_web.py::test_weblink_from_uri_raises[spotify:track:foo:bar]",
"tests/test_web.py::test_weblink_from_uri_raises[spotify:album:]",
"tests/test_web.py::test_weblink_from_uri_raises[https://yahoo.com/playlist/foo]",
"tests/test_web.py::test_weblink_from_uri_raises[https://play.spotify.com/foo]",
"tests/test_web.py::test_weblink_from_uri_raises[total/junk]"
] |
{
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2023-10-19 23:46:27+00:00
|
apache-2.0
| 4,032 |
|
mopidy__mopidy-spotify-376
|
diff --git a/mopidy_spotify/translator.py b/mopidy_spotify/translator.py
index 229730a..00c6fdf 100644
--- a/mopidy_spotify/translator.py
+++ b/mopidy_spotify/translator.py
@@ -236,6 +236,11 @@ def web_to_album(web_album):
return models.Album(uri=ref.uri, name=name, artists=artists)
+def int_or_none(inp):
+ if inp is not None:
+ return int(float(inp))
+
+
def web_to_track(web_track, bitrate=None, album=None):
ref = web_to_track_ref(web_track)
if ref is None:
@@ -254,8 +259,8 @@ def web_to_track(web_track, bitrate=None, album=None):
name=ref.name,
artists=artists,
album=album,
- length=web_track.get("duration_ms"),
- disc_no=web_track.get("disc_number"),
- track_no=web_track.get("track_number"),
+ length=int_or_none(web_track.get("duration_ms")),
+ disc_no=int_or_none(web_track.get("disc_number")),
+ track_no=int_or_none(web_track.get("track_number")),
bitrate=bitrate,
)
|
mopidy/mopidy-spotify
|
fc6ffb3bbbae9224316e2a888db08ef56608966a
|
diff --git a/tests/test_translator.py b/tests/test_translator.py
index ec9e8d6..db778e1 100644
--- a/tests/test_translator.py
+++ b/tests/test_translator.py
@@ -683,3 +683,29 @@ class TestWebToTrack:
assert track.name == "ABC 123"
assert track.album is None
+
+ @pytest.mark.parametrize(
+ "data",
+ [
+ (123),
+ (123.0),
+ ("123"),
+ ("123.0"),
+ ],
+ )
+ def test_int_or_none_number(self, data):
+ assert translator.int_or_none(data) == 123
+
+ def test_int_or_none_none(self):
+ assert translator.int_or_none(None) is None
+
+ def test_ints_might_be_floats(self, web_track_mock):
+ web_track_mock["duration_ms"] = 123.0
+ web_track_mock["disc_number"] = "456.0"
+ web_track_mock["track_number"] = 99.9
+
+ track = translator.web_to_track(web_track_mock)
+
+ assert track.length == 123
+ assert track.disc_no == 456
+ assert track.track_no == 99
|
TypeError: Expected length to be a <class 'int'>, not 156923.0
Today I'm receiving multiple errors when adding tracks to the queue.
```
ERROR 2024-02-27 12:54:10,020 [1:Core-6 (_actor_loop)] mopidy.core.library
SpotifyBackend backend caused an exception.
Traceback (most recent call last):
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy/core/library.py", line 17, in _backend_error_handling
yield
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy/core/library.py", line 230, in lookup
result = future.get()
^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/pykka/_threading.py", line 68, in get
raise exc_value
File "/opt/mopidy/lib64/python3.11/site-packages/pykka/_actor.py", line 238, in _actor_loop_running
response = self._handle_receive(envelope.message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/pykka/_actor.py", line 349, in _handle_receive
return callee(*message.args, **message.kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy_spotify/library.py", line 38, in lookup
return lookup.lookup(self._config, self._backend._web_client, uri)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy_spotify/lookup.py", line 27, in lookup
return list(_lookup_track(config, web_client, link))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy_spotify/lookup.py", line 51, in _lookup_track
track = translator.web_to_track(web_track, bitrate=config["bitrate"])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy_spotify/translator.py", line 252, in web_to_track
return models.Track(
^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy/models/immutable.py", line 159, in __call__
instance = super().__call__(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy/models/immutable.py", line 35, in __init__
self._set_field(key, value)
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy/models/immutable.py", line 188, in _set_field
object.__setattr__(self, name, value)
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy/models/fields.py", line 50, in __set__
value = self.validate(value)
^^^^^^^^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy/models/fields.py", line 133, in validate
value = super().validate(value)
^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/mopidy/lib64/python3.11/site-packages/mopidy/models/fields.py", line 34, in validate
raise TypeError(
TypeError: Expected length to be a <class 'int'>, not 156923.0
```
|
0.0
|
fc6ffb3bbbae9224316e2a888db08ef56608966a
|
[
"tests/test_translator.py::TestWebToTrack::test_int_or_none_number[123_0]",
"tests/test_translator.py::TestWebToTrack::test_int_or_none_number[123.0_0]",
"tests/test_translator.py::TestWebToTrack::test_int_or_none_number[123_1]",
"tests/test_translator.py::TestWebToTrack::test_int_or_none_number[123.0_1]",
"tests/test_translator.py::TestWebToTrack::test_int_or_none_none",
"tests/test_translator.py::TestWebToTrack::test_ints_might_be_floats"
] |
[
"tests/test_translator.py::TestWebToArtistRef::test_returns_none_if_bad_data[web_data0]",
"tests/test_translator.py::TestWebToArtistRef::test_returns_none_if_bad_data[web_data1]",
"tests/test_translator.py::TestWebToArtistRef::test_returns_none_if_bad_data[web_data2]",
"tests/test_translator.py::TestWebToArtistRef::test_successful_translation",
"tests/test_translator.py::TestWebToArtistRef::test_without_name_uses_uri",
"tests/test_translator.py::TestWebToArtistRefs::test_bad_artists_filtered",
"tests/test_translator.py::TestValidWebData::test_returns_false_if_none",
"tests/test_translator.py::TestValidWebData::test_returns_false_if_empty",
"tests/test_translator.py::TestValidWebData::test_returns_false_if_missing_type",
"tests/test_translator.py::TestValidWebData::test_returns_false_if_wrong_type",
"tests/test_translator.py::TestValidWebData::test_returns_false_if_missing_uri",
"tests/test_translator.py::TestValidWebData::test_return_false_if_uri_none",
"tests/test_translator.py::TestValidWebData::test_returns_success",
"tests/test_translator.py::TestWebToAlbumRef::test_returns_none_if_invalid",
"tests/test_translator.py::TestWebToAlbumRef::test_returns_none_if_wrong_type",
"tests/test_translator.py::TestWebToAlbumRef::test_successful_translation",
"tests/test_translator.py::TestWebToAlbumRef::test_without_artists_uses_name",
"tests/test_translator.py::TestWebToAlbumRef::test_without_name_uses_uri",
"tests/test_translator.py::TestWebToAlbumRefs::test_returns_albums",
"tests/test_translator.py::TestWebToAlbumRefs::test_returns_bare_albums",
"tests/test_translator.py::TestWebToAlbumRefs::test_bad_albums_filtered",
"tests/test_translator.py::TestWebToTrackRef::test_returns_none_if_invalid",
"tests/test_translator.py::TestWebToTrackRef::test_returns_none_if_wrong_type",
"tests/test_translator.py::TestWebToTrackRef::test_returns_none_if_not_playable",
"tests/test_translator.py::TestWebToTrackRef::test_ignore_missing_is_playable",
"tests/test_translator.py::TestWebToTrackRef::test_successful_translation",
"tests/test_translator.py::TestWebToTrackRef::test_without_name_uses_uri",
"tests/test_translator.py::TestWebToTrackRef::test_uri_uses_relinked_from_uri",
"tests/test_translator.py::TestWebToTrackRefs::test_returns_playlist_tracks",
"tests/test_translator.py::TestWebToTrackRefs::test_returns_top_list_tracks",
"tests/test_translator.py::TestWebToTrackRefs::test_bad_tracks_filtered",
"tests/test_translator.py::TestWebToTrackRefs::test_check_playable_default",
"tests/test_translator.py::TestWebToTrackRefs::test_dont_check_playable",
"tests/test_translator.py::TestToPlaylist::test_calls_to_playlist_ref",
"tests/test_translator.py::TestToPlaylist::test_returns_none_if_invalid_ref",
"tests/test_translator.py::TestToPlaylist::test_successful_translation",
"tests/test_translator.py::TestToPlaylist::test_no_track_data",
"tests/test_translator.py::TestToPlaylist::test_as_items",
"tests/test_translator.py::TestToPlaylist::test_as_items_no_track_data",
"tests/test_translator.py::TestToPlaylist::test_filters_out_none_tracks",
"tests/test_translator.py::TestToPlaylistRef::test_returns_none_if_invalid",
"tests/test_translator.py::TestToPlaylistRef::test_returns_none_if_wrong_type",
"tests/test_translator.py::TestToPlaylistRef::test_successful_translation",
"tests/test_translator.py::TestToPlaylistRef::test_without_name_uses_uri",
"tests/test_translator.py::TestToPlaylistRef::test_success_without_track_data",
"tests/test_translator.py::TestToPlaylistRef::test_includes_by_owner_in_name_if_owned_by_another_user",
"tests/test_translator.py::TestToPlaylistRefs::test_returns_playlist_refs",
"tests/test_translator.py::TestToPlaylistRefs::test_bad_playlist_filtered",
"tests/test_translator.py::TestToPlaylistRefs::test_passes_username",
"tests/test_translator.py::TestSpotifySearchQuery::test_any_maps_to_no_field",
"tests/test_translator.py::TestSpotifySearchQuery::test_any_maps_to_no_field_exact",
"tests/test_translator.py::TestSpotifySearchQuery::test_artist_maps_to_artist",
"tests/test_translator.py::TestSpotifySearchQuery::test_artist_maps_to_artist_exact",
"tests/test_translator.py::TestSpotifySearchQuery::test_albumartist_maps_to_artist",
"tests/test_translator.py::TestSpotifySearchQuery::test_albumartist_maps_to_artist_exact",
"tests/test_translator.py::TestSpotifySearchQuery::test_album_maps_to_album",
"tests/test_translator.py::TestSpotifySearchQuery::test_album_maps_to_album_exact",
"tests/test_translator.py::TestSpotifySearchQuery::test_track_name_maps_to_track",
"tests/test_translator.py::TestSpotifySearchQuery::test_track_name_maps_to_track_exact",
"tests/test_translator.py::TestSpotifySearchQuery::test_track_number_is_not_supported",
"tests/test_translator.py::TestSpotifySearchQuery::test_date_maps_to_year",
"tests/test_translator.py::TestSpotifySearchQuery::test_date_is_transformed_to_just_the_year",
"tests/test_translator.py::TestSpotifySearchQuery::test_date_is_ignored_if_not_parseable",
"tests/test_translator.py::TestSpotifySearchQuery::test_anything_can_be_combined",
"tests/test_translator.py::TestSpotifySearchQuery::test_anything_can_be_combined_exact",
"tests/test_translator.py::TestWebToArtist::test_calls_web_to_artist_ref",
"tests/test_translator.py::TestWebToArtist::test_returns_none_if_invalid_ref",
"tests/test_translator.py::TestWebToArtist::test_successful_translation",
"tests/test_translator.py::TestWebToAlbum::test_calls_web_to_album_ref",
"tests/test_translator.py::TestWebToAlbum::test_returns_none_if_invalid_ref",
"tests/test_translator.py::TestWebToAlbum::test_successful_translation",
"tests/test_translator.py::TestWebToAlbum::test_ignores_invalid_artists",
"tests/test_translator.py::TestWebToAlbum::test_returns_empty_artists_list_if_artist_is_empty",
"tests/test_translator.py::TestWebToAlbum::test_caches_results",
"tests/test_translator.py::TestWebToAlbum::test_web_to_album_tracks",
"tests/test_translator.py::TestWebToAlbum::test_web_to_album_tracks_empty",
"tests/test_translator.py::TestWebToAlbum::test_web_to_album_tracks_unplayable",
"tests/test_translator.py::TestWebToAlbum::test_web_to_album_tracks_nolist",
"tests/test_translator.py::TestWebToAlbum::test_web_to_album_tracks_none",
"tests/test_translator.py::TestWebToTrack::test_calls_web_to_track_ref",
"tests/test_translator.py::TestWebToTrack::test_returns_none_if_invalid_ref",
"tests/test_translator.py::TestWebToTrack::test_successful_translation",
"tests/test_translator.py::TestWebToTrack::test_sets_bitrate",
"tests/test_translator.py::TestWebToTrack::test_sets_specified_album",
"tests/test_translator.py::TestWebToTrack::test_filters_out_none_artists",
"tests/test_translator.py::TestWebToTrack::test_ignores_missing_album",
"tests/test_translator.py::TestWebToTrack::test_ignores_invalid_album"
] |
{
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
}
|
2024-02-27 14:44:50+00:00
|
apache-2.0
| 4,033 |
|
mosecorg__mosec-205
|
diff --git a/mosec/errors.py b/mosec/errors.py
index d189be1..143bd94 100644
--- a/mosec/errors.py
+++ b/mosec/errors.py
@@ -25,6 +25,17 @@ implemented by users), the `ValidationError` should be raised.
"""
+class EncodingError(Exception):
+ """Serialization error.
+
+ The `EncodingError` should be raised in user-implemented codes when
+ the serialization for the response bytes fails. This error will set
+ to status code to
+ [HTTP 500](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500)
+ in the response.
+ """
+
+
class DecodingError(Exception):
"""De-serialization error.
diff --git a/mosec/mixin/__init__.py b/mosec/mixin/__init__.py
new file mode 100644
index 0000000..fc25af2
--- /dev/null
+++ b/mosec/mixin/__init__.py
@@ -0,0 +1,19 @@
+# Copyright 2022 MOSEC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Provide useful mixin to extend MOSEC."""
+
+from .msgpack_worker import MsgpackMixin
+
+__all__ = ["MsgpackMixin"]
diff --git a/mosec/mixin/msgpack_worker.py b/mosec/mixin/msgpack_worker.py
new file mode 100644
index 0000000..d0a4799
--- /dev/null
+++ b/mosec/mixin/msgpack_worker.py
@@ -0,0 +1,74 @@
+# Copyright 2022 MOSEC Authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""MOSEC msgpack worker mixin.
+
+Features:
+
+ * deserialize request body with msgpack
+ * serialize response body with msgpack
+"""
+
+
+import warnings
+from typing import Any
+
+from ..errors import DecodingError, EncodingError
+
+try:
+ import msgpack # type: ignore
+except ImportError:
+ warnings.warn("msgpack is required for MsgpackWorker", ImportWarning)
+
+
+class MsgpackMixin:
+ """Msgpack worker mixin interface."""
+
+ # pylint: disable=no-self-use
+
+ def serialize(self, data: Any) -> bytes:
+ """Serialize with msgpack for the last stage (egress).
+
+ Arguments:
+ data: the [_*same type_][mosec.worker.Worker--note]
+
+ Returns:
+ the bytes you want to put into the response body
+
+ Raises:
+ EncodingError: if the data cannot be serialized with msgpack
+ """
+ try:
+ data_bytes = msgpack.packb(data)
+ except Exception as err:
+ raise EncodingError from err
+ return data_bytes
+
+ def deserialize(self, data: bytes) -> Any:
+ """Deserialize method for the first stage (ingress).
+
+ Arguments:
+ data: the raw bytes extracted from the request body
+
+ Returns:
+ [_*same type_][mosec.worker.Worker--note]
+
+ Raises:
+ DecodingError: if the data cannot be deserialized with msgpack
+ """
+ try:
+ data_msg = msgpack.unpackb(data, use_list=False)
+ except Exception as err:
+ raise DecodingError from err
+ return data_msg
diff --git a/mosec/worker.py b/mosec/worker.py
index 9ea69f6..c3314d0 100644
--- a/mosec/worker.py
+++ b/mosec/worker.py
@@ -28,7 +28,7 @@ import logging
import pickle
from typing import Any
-from .errors import DecodingError
+from .errors import DecodingError, EncodingError
logger = logging.getLogger(__name__)
@@ -124,12 +124,12 @@ class Worker(abc.ABC):
the bytes you want to put into the response body
Raises:
- ValueError: if the data cannot be serialized with JSON
+ EncodingError: if the data cannot be serialized with JSON
"""
try:
data_bytes = json.dumps(data, indent=2).encode()
except Exception as err:
- raise ValueError from err
+ raise EncodingError from err
return data_bytes
def deserialize(self, data: bytes) -> Any:
diff --git a/requirements/plugin.txt b/requirements/plugin.txt
index 1e60e1c..facba2e 100644
--- a/requirements/plugin.txt
+++ b/requirements/plugin.txt
@@ -1,1 +1,2 @@
pyarrow>=0.6.1
+msgpack>=1.0.2
|
mosecorg/mosec
|
42957d0205b8127279ae78ce6b8a34c064d163a4
|
diff --git a/tests/test_coordinator.py b/tests/test_coordinator.py
index 80ab1b2..49b8174 100644
--- a/tests/test_coordinator.py
+++ b/tests/test_coordinator.py
@@ -29,6 +29,7 @@ import msgpack # type: ignore
import pytest
from mosec.coordinator import PROTOCOL_TIMEOUT, STAGE_EGRESS, STAGE_INGRESS, Coordinator
+from mosec.mixin import MsgpackMixin
from mosec.protocol import Protocol, _recv_all
from mosec.worker import Worker
@@ -65,14 +66,8 @@ class EchoWorkerJSON(Worker):
return data
-class EchoWorkerMSGPACK(EchoWorkerJSON):
- @staticmethod
- def deserialize(data):
- return msgpack.unpackb(data)
-
- @staticmethod
- def serialize(data):
- return msgpack.packb(data)
+class EchoWorkerMSGPACK(MsgpackMixin, EchoWorkerJSON):
+ """"""
@pytest.fixture
|
[FEATURE] Worker with msgpack serialization
|
0.0
|
42957d0205b8127279ae78ce6b8a34c064d163a4
|
[
"tests/test_coordinator.py::test_socket_file_not_found",
"tests/test_coordinator.py::test_incorrect_socket_file",
"tests/test_coordinator.py::test_echo_batch[test_data0-EchoWorkerJSON-loads]",
"tests/test_coordinator.py::test_echo_batch[test_data1-EchoWorkerJSON-loads]",
"tests/test_coordinator.py::test_echo_batch[test_data2-EchoWorkerMSGPACK-unpackb]"
] |
[] |
{
"failed_lite_validators": [
"has_short_problem_statement",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
}
|
2022-08-31 02:14:00+00:00
|
apache-2.0
| 4,034 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.