instance_id
stringlengths 13
56
| base_commit
stringlengths 40
40
| created_at
stringdate 2024-03-21 23:13:34
2024-07-17 15:28:21
| environment_setup_commit
stringlengths 40
40
| hints_text
stringlengths 0
35.9k
| patch
stringlengths 285
745k
| problem_statement
stringlengths 22
28.1k
| repo
stringlengths 8
51
| test_patch
stringlengths 338
236k
| meta
dict | version
stringlengths 2
15
| install_config
dict | requirements
stringlengths 189
27.3k
⌀ | environment
stringlengths 942
15.8k
⌀ | FAIL_TO_PASS
listlengths 1
1.08k
| FAIL_TO_FAIL
listlengths 0
324
| PASS_TO_PASS
listlengths 0
1.96k
| PASS_TO_FAIL
listlengths 0
5
| license_name
stringclasses 21
values | __index_level_0__
int64 18k
19k
| dataset_name
stringclasses 1
value | filtered_from
stringclasses 1
value | total_instances
int64 817
817
| image_name
stringlengths 48
91
| test_cmd
stringlengths 60
2.37k
| eval_cmd
stringlengths 1.11k
243k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PlasmaPy__PlasmaPy-2594
|
221e4b73797c97459f90b5055648075fea9380ad
|
2024-03-21 23:13:34
|
b644951ff8361436b6056dde8e2dcd1d12e1b22e
|
codecov[bot]: ## [Codecov](https://app.codecov.io/gh/PlasmaPy/PlasmaPy/pull/2594?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PlasmaPy) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 96.72%. Comparing base [(`20e60aa`)](https://app.codecov.io/gh/PlasmaPy/PlasmaPy/commit/20e60aa88f7dbb08bea5dc6fb2fd7926cd367905?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PlasmaPy) to head [(`34a7d72`)](https://app.codecov.io/gh/PlasmaPy/PlasmaPy/pull/2594?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PlasmaPy).
> Report is 76 commits behind head on main.
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #2594 +/- ##
==========================================
- Coverage 96.93% 96.72% -0.21%
==========================================
Files 104 104
Lines 9163 9371 +208
==========================================
+ Hits 8882 9064 +182
- Misses 281 307 +26
```
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/PlasmaPy/PlasmaPy/pull/2594?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PlasmaPy).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PlasmaPy).
namurphy: This PR is partially superseded by #2648. I might close this and open a follow-up PR to add the tests from this PR. Ultimately, I think #2648 will make this PR (or its follow-up) easier and cleaner.
|
diff --git a/changelog/2594.bugfix.rst b/changelog/2594.bugfix.rst
new file mode 100644
index 00000000..53f1932f
--- /dev/null
+++ b/changelog/2594.bugfix.rst
@@ -0,0 +1,2 @@
+Fixed a bug in |particle_input| where particle categorization criteria
+had not been applied to arguments that became a |ParticleList|.
diff --git a/src/plasmapy/particles/decorators.py b/src/plasmapy/particles/decorators.py
index 300b95ef..94937a42 100644
--- a/src/plasmapy/particles/decorators.py
+++ b/src/plasmapy/particles/decorators.py
@@ -431,19 +431,11 @@ def verify_particle_categorization(
--------
~plasmapy.particles.particle_class.Particle.is_category
"""
- if isinstance(particle, ParticleList):
- particle_in_category = particle.is_category(
- require=self.require,
- any_of=self.any_of,
- exclude=self.exclude,
- particlewise=True,
- )
- else:
- particle_in_category = particle.is_category(
- require=self.require,
- any_of=self.any_of,
- exclude=self.exclude,
- )
+ particle_in_category = particle.is_category(
+ require=self.require,
+ any_of=self.any_of,
+ exclude=self.exclude,
+ )
if not particle_in_category:
errmsg = self.category_errmsg(
particle,
@@ -468,7 +460,7 @@ def verify_particle_name_criteria(
and not np.isnan(particle.charge)
and particle.mass.value > 0
):
- return
+ return None
name_categorization_exception: list[
tuple[str, dict[str, str | Iterable[str] | None], type]
@@ -964,7 +956,6 @@ def instance_method(self, particle: ParticleLike, B: u.Quantity[u.T]): ...
... return isotope.mass_number
>>> mass_number("D")
2
-
"""
# The following pattern comes from the docs for wrapt, and requires
|
`@particle_input` does not apply categorization criteria when creating a `ParticleList`
### Bug description
The `require`, `exclude`, and `any_of` parameters of `@particle_input` do not get enforced when the decorated function gets passed a `ParticleList`.
### Expected outcome
When we use the `require`, `any_of`, and `exclude` parameters with `@particle_input`, we should make them work with `ParticleLike`.
```Python
@particle_input(require="ion", exclude={"isotope"})
def f(x: ParticleLike):
return x
```
### Minimal complete verifiable example
```Python
>>> from plasmapy.particles import ParticleLike, particle_input
>>>
>>> @particle_input(require="ion")
... def f(particle: ParticleLike):
... return particle
...
>>> f(["e-", "e+"]) # should raise an error because these are not ions
ParticleList(['e-', 'e+'])
```
### Package versions
_No response_
### Additional context
When the decorated parameter is named `ion` (for example), `@particle_input` does indeed check that the list contains only ions.
```pycon
>>> @particle_input
... def g(ion: ParticleLike):
... return ion
...
>>> g(["e-", "e+"])
plasmapy.particles.exceptions.InvalidIonError: The argument ion = ParticleList(['e-', 'e+']) to g does not correspond to a valid ion.
```
However, there's a little singular vs. plural weirdness in the error message that we could fix.
|
PlasmaPy/PlasmaPy
|
diff --git a/tests/particles/test_decorators.py b/tests/particles/test_decorators.py
index 6063da3d..3d7cdc73 100644
--- a/tests/particles/test_decorators.py
+++ b/tests/particles/test_decorators.py
@@ -18,7 +18,7 @@
ParticleError,
)
from plasmapy.particles.particle_class import CustomParticle, Particle, ParticleLike
-from plasmapy.particles.particle_collections import ParticleList
+from plasmapy.particles.particle_collections import ParticleList, ParticleListLike
from plasmapy.utils.code_repr import call_string
from plasmapy.utils.decorators.validators import validate_quantities
from plasmapy.utils.exceptions import PlasmaPyDeprecationWarning
@@ -748,3 +748,31 @@ def function_with_pos_and_var_positional_arguments(
expected = (a, args, Particle(particle))
actual = function_with_pos_and_var_positional_arguments(a, *args, particle=particle)
assert actual == expected
+
+
[email protected](
+ ("criteria", "kwargs", "exception"),
+ [
+ ({"require": "ion"}, {"particle": ["p+", "He"]}, ParticleError),
+ ({"require": "isotope"}, {"particle": ["p+", "He"]}, ParticleError),
+ (
+ {"any_of": {"lepton", "neutrino"}},
+ {"particle": ["p+", "alpha"]},
+ ParticleError,
+ ),
+ ({"exclude": "lepton"}, {"particle": ["p+", "e-"]}, ParticleError),
+ ],
+)
+def test_particle_categorization_of_particle_lists(
+ criteria: dict[str, str | Iterable[str]],
+ kwargs: dict[str, ParticleListLike],
+ exception: Exception,
+) -> None:
+ @particle_input(**criteria) # type: ignore[arg-type]
+ def get_particle(
+ particle: ParticleLike,
+ ) -> Particle | ParticleList | CustomParticle:
+ return particle # type: ignore[return-value]
+
+ with pytest.raises(exception): # type: ignore[call-overload]
+ get_particle(**kwargs)
|
{
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 0,
"test_score": 0
},
"num_modified_files": 1
}
|
2024.2
|
{
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[tests,docs]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.10",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
}
|
alabaster==0.7.16
anyio==4.3.0
argon2-cffi==23.1.0
argon2-cffi-bindings==21.2.0
arrow==1.3.0
asteval==0.9.32
astropy==6.0.1
astropy-iers-data==0.2024.4.29.0.28.48
asttokens==2.4.1
attrs==23.2.0
Babel==2.14.0
beautifulsoup4==4.12.3
bleach==6.1.0
cachetools==5.3.3
certifi==2024.2.2
cffi==1.16.0
cfgv==3.4.0
chardet==5.2.0
charset-normalizer==3.3.2
click==8.1.7
colorama==0.4.6
comm==0.2.2
contourpy==1.2.1
cycler==0.12.1
debugpy==1.8.1
decorator==5.1.1
defusedxml==0.7.1
dill==0.3.8
distlib==0.3.8
docutils==0.20.1
exceptiongroup==1.2.2
execnet==2.1.1
executing==2.0.1
fastjsonschema==2.19.1
filelock==3.13.4
fonttools==4.51.0
fqdn==1.5.1
future==1.0.0
h5py==3.11.0
hypothesis==6.100.2
identify==2.5.36
idna==3.7
imagesize==1.4.1
incremental==22.10.0
iniconfig==2.0.0
ipykernel==6.29.4
ipython==8.24.0
ipywidgets==8.1.2
isoduration==20.11.0
jedi==0.19.1
Jinja2==3.1.3
json5==0.9.25
jsonpointer==2.4
jsonschema==4.21.1
jsonschema-specifications==2023.12.1
jupyter-events==0.10.0
jupyter_client==8.6.1
jupyter_core==5.7.2
jupyter_server==2.14.0
jupyter_server_terminals==0.5.3
jupyterlab_pygments==0.3.0
jupyterlab_server==2.27.1
jupyterlab_widgets==3.0.10
kiwisolver==1.4.5
latexcodec==3.0.0
llvmlite==0.42.0
lmfit==1.3.1
MarkupSafe==2.1.5
matplotlib==3.8.4
matplotlib-inline==0.1.7
mistune==3.0.2
mpmath==1.3.0
nbclient==0.7.4
nbconvert==7.16.3
nbformat==5.10.4
nbsphinx==0.9.3
nest-asyncio==1.6.0
nodeenv==1.8.0
numba==0.59.1
numpy==1.26.4
numpydoc==1.7.0
overrides==7.7.0
packaging==24.0
pandas==2.2.2
pandocfilters==1.5.1
parso==0.8.4
pexpect==4.9.0
pillow==10.3.0
-e git+https://github.com/PlasmaPy/PlasmaPy.git@221e4b73797c97459f90b5055648075fea9380ad#egg=plasmapy
platformdirs==4.2.1
pluggy==1.5.0
pre-commit==3.7.0
prometheus_client==0.20.0
prompt-toolkit==3.0.43
psutil==5.9.8
ptyprocess==0.7.0
pure-eval==0.2.2
pybtex==0.24.0
pybtex-docutils==1.0.3
pycparser==2.22
pyerfa==2.0.1.4
Pygments==2.17.2
pyparsing==3.1.2
pyproject-api==1.6.1
pytest==8.2.0
pytest-datadir==1.5.0
pytest-regressions==2.5.0
pytest-rerunfailures==14.0
pytest-xdist==3.6.1
python-dateutil==2.9.0.post0
python-json-logger==2.0.7
pytz==2024.1
PyYAML==6.0.1
pyzmq==26.0.2
referencing==0.35.0
requests==2.31.0
rfc3339-validator==0.1.4
rfc3986-validator==0.1.1
rpds-py==0.18.0
scipy==1.13.0
Send2Trash==1.8.3
six==1.16.0
sniffio==1.3.1
snowballstemmer==2.2.0
sortedcontainers==2.4.0
soupsieve==2.5
Sphinx==7.3.7
sphinx-codeautolink==0.15.1
sphinx-copybutton==0.5.2
sphinx-gallery==0.16.0
sphinx-hoverxref==1.3.0
sphinx-issues==4.1.0
sphinx-notfound-page==1.0.0
sphinx-reredirects==0.1.3
sphinx-rtd-theme==2.0.0
sphinx-tabs==3.4.5
sphinx_changelog==1.5.0
sphinx_collapse==0.1.3
sphinxcontrib-applehelp==1.0.8
sphinxcontrib-bibtex==2.6.2
sphinxcontrib-devhelp==1.0.6
sphinxcontrib-globalsubs==0.1.1
sphinxcontrib-htmlhelp==2.0.5
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.7
sphinxcontrib-serializinghtml==1.1.10
stack-data==0.6.3
tabulate==0.9.0
terminado==0.18.1
tinycss2==1.3.0
tomli==2.0.1
tornado==6.4
towncrier==23.11.0
tox==4.15.0
tox-uv==1.7.0
tqdm==4.66.2
traitlets==5.14.3
types-python-dateutil==2.9.0.20240316
typing_extensions==4.13.0
tzdata==2024.1
uncertainties==3.1.7
Unidecode==1.3.8
uri-template==1.3.0
urllib3==2.2.1
uv==0.1.39
virtualenv==20.26.0
voila==0.5.6
wcwidth==0.2.13
webcolors==1.13
webencodings==0.5.1
websocket-client==1.8.0
websockets==12.0
widgetsnbextension==4.0.10
wrapt==1.16.0
xarray==2024.3.0
|
name: PlasmaPy
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- bzip2=1.0.8=h5eee18b_6
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- libuuid=1.41.5=h5eee18b_0
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py310h06a4308_0
- python=3.10.16=he870216_1
- readline=8.2=h5eee18b_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py310h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- anyio==4.3.0
- argon2-cffi==23.1.0
- argon2-cffi-bindings==21.2.0
- arrow==1.3.0
- asteval==0.9.32
- astropy==6.0.1
- astropy-iers-data==0.2024.4.29.0.28.48
- asttokens==2.4.1
- attrs==23.2.0
- babel==2.14.0
- beautifulsoup4==4.12.3
- bleach==6.1.0
- cachetools==5.3.3
- certifi==2024.2.2
- cffi==1.16.0
- cfgv==3.4.0
- chardet==5.2.0
- charset-normalizer==3.3.2
- click==8.1.7
- colorama==0.4.6
- comm==0.2.2
- contourpy==1.2.1
- cycler==0.12.1
- debugpy==1.8.1
- decorator==5.1.1
- defusedxml==0.7.1
- dill==0.3.8
- distlib==0.3.8
- docutils==0.20.1
- exceptiongroup==1.2.2
- execnet==2.1.1
- executing==2.0.1
- fastjsonschema==2.19.1
- filelock==3.13.4
- fonttools==4.51.0
- fqdn==1.5.1
- future==1.0.0
- h5py==3.11.0
- hypothesis==6.100.2
- identify==2.5.36
- idna==3.7
- imagesize==1.4.1
- incremental==22.10.0
- iniconfig==2.0.0
- ipykernel==6.29.4
- ipython==8.24.0
- ipywidgets==8.1.2
- isoduration==20.11.0
- jedi==0.19.1
- jinja2==3.1.3
- json5==0.9.25
- jsonpointer==2.4
- jsonschema==4.21.1
- jsonschema-specifications==2023.12.1
- jupyter-client==8.6.1
- jupyter-core==5.7.2
- jupyter-events==0.10.0
- jupyter-server==2.14.0
- jupyter-server-terminals==0.5.3
- jupyterlab-pygments==0.3.0
- jupyterlab-server==2.27.1
- jupyterlab-widgets==3.0.10
- kiwisolver==1.4.5
- latexcodec==3.0.0
- llvmlite==0.42.0
- lmfit==1.3.1
- markupsafe==2.1.5
- matplotlib==3.8.4
- matplotlib-inline==0.1.7
- mistune==3.0.2
- mpmath==1.3.0
- nbclient==0.7.4
- nbconvert==7.16.3
- nbformat==5.10.4
- nbsphinx==0.9.3
- nest-asyncio==1.6.0
- nodeenv==1.8.0
- numba==0.59.1
- numpy==1.26.4
- numpydoc==1.7.0
- overrides==7.7.0
- packaging==24.0
- pandas==2.2.2
- pandocfilters==1.5.1
- parso==0.8.4
- pexpect==4.9.0
- pillow==10.3.0
- plasmapy==2023.1.1.dev958+g221e4b73
- platformdirs==4.2.1
- pluggy==1.5.0
- pre-commit==3.7.0
- prometheus-client==0.20.0
- prompt-toolkit==3.0.43
- psutil==5.9.8
- ptyprocess==0.7.0
- pure-eval==0.2.2
- pybtex==0.24.0
- pybtex-docutils==1.0.3
- pycparser==2.22
- pyerfa==2.0.1.4
- pygments==2.17.2
- pyparsing==3.1.2
- pyproject-api==1.6.1
- pytest==8.2.0
- pytest-datadir==1.5.0
- pytest-regressions==2.5.0
- pytest-rerunfailures==14.0
- pytest-xdist==3.6.1
- python-dateutil==2.9.0.post0
- python-json-logger==2.0.7
- pytz==2024.1
- pyyaml==6.0.1
- pyzmq==26.0.2
- referencing==0.35.0
- requests==2.31.0
- rfc3339-validator==0.1.4
- rfc3986-validator==0.1.1
- rpds-py==0.18.0
- scipy==1.13.0
- send2trash==1.8.3
- setuptools==69.5.1
- six==1.16.0
- sniffio==1.3.1
- snowballstemmer==2.2.0
- sortedcontainers==2.4.0
- soupsieve==2.5
- sphinx==7.3.7
- sphinx-changelog==1.5.0
- sphinx-codeautolink==0.15.1
- sphinx-collapse==0.1.3
- sphinx-copybutton==0.5.2
- sphinx-gallery==0.16.0
- sphinx-hoverxref==1.3.0
- sphinx-issues==4.1.0
- sphinx-notfound-page==1.0.0
- sphinx-reredirects==0.1.3
- sphinx-rtd-theme==2.0.0
- sphinx-tabs==3.4.5
- sphinxcontrib-applehelp==1.0.8
- sphinxcontrib-bibtex==2.6.2
- sphinxcontrib-devhelp==1.0.6
- sphinxcontrib-globalsubs==0.1.1
- sphinxcontrib-htmlhelp==2.0.5
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==1.0.7
- sphinxcontrib-serializinghtml==1.1.10
- stack-data==0.6.3
- tabulate==0.9.0
- terminado==0.18.1
- tinycss2==1.3.0
- tomli==2.0.1
- tornado==6.4
- towncrier==23.11.0
- tox==4.15.0
- tox-uv==1.7.0
- tqdm==4.66.2
- traitlets==5.14.3
- types-python-dateutil==2.9.0.20240316
- typing-extensions==4.13.0
- tzdata==2024.1
- uncertainties==3.1.7
- unidecode==1.3.8
- uri-template==1.3.0
- urllib3==2.2.1
- uv==0.1.39
- virtualenv==20.26.0
- voila==0.5.6
- wcwidth==0.2.13
- webcolors==1.13
- webencodings==0.5.1
- websocket-client==1.8.0
- websockets==12.0
- widgetsnbextension==4.0.10
- wrapt==1.16.0
- xarray==2024.3.0
prefix: /opt/conda/envs/PlasmaPy
|
[
"tests/particles/test_decorators.py::test_particle_categorization_of_particle_lists[criteria0-kwargs0-ParticleError]",
"tests/particles/test_decorators.py::test_particle_categorization_of_particle_lists[criteria1-kwargs1-ParticleError]",
"tests/particles/test_decorators.py::test_particle_categorization_of_particle_lists[criteria2-kwargs2-ParticleError]",
"tests/particles/test_decorators.py::test_particle_categorization_of_particle_lists[criteria3-kwargs3-ParticleError]"
] |
[] |
[
"tests/particles/test_decorators.py::test_particle_input_simple[args0-kwargs0-p+-function_decorated_with_call_of_particle_input]",
"tests/particles/test_decorators.py::test_particle_input_simple[args0-kwargs0-p+-function_decorated_with_particle_input]",
"tests/particles/test_decorators.py::test_particle_input_simple[args1-kwargs1-Fe-56",
"tests/particles/test_decorators.py::test_particle_input_simple[args2-kwargs2-e--function_decorated_with_call_of_particle_input]",
"tests/particles/test_decorators.py::test_particle_input_simple[args2-kwargs2-e--function_decorated_with_particle_input]",
"tests/particles/test_decorators.py::test_particle_input_simple[args3-kwargs3-e--function_decorated_with_call_of_particle_input]",
"tests/particles/test_decorators.py::test_particle_input_simple[args3-kwargs3-e--function_decorated_with_particle_input]",
"tests/particles/test_decorators.py::test_particle_input_errors[function_decorated_with_particle_input-kwargs0-InvalidParticleError]",
"tests/particles/test_decorators.py::test_particle_input_errors[function_decorated_with_particle_input-kwargs1-InvalidParticleError]",
"tests/particles/test_decorators.py::test_particle_input_errors[function_decorated_with_particle_input-kwargs2-InvalidParticleError]",
"tests/particles/test_decorators.py::test_particle_input_errors[function_decorated_with_particle_input-kwargs3-TypeError]",
"tests/particles/test_decorators.py::test_particle_input_classes[muon]",
"tests/particles/test_decorators.py::test_particle_input_classes[He",
"tests/particles/test_decorators.py::test_no_annotations_exception",
"tests/particles/test_decorators.py::test_function_with_ambiguity[args0-kwargs0]",
"tests/particles/test_decorators.py::test_function_with_ambiguity[args1-kwargs1]",
"tests/particles/test_decorators.py::test_function_with_ambiguity[args2-kwargs2]",
"tests/particles/test_decorators.py::test_optional_particle",
"tests/particles/test_decorators.py::test_decorator_categories[categorization0-Fe-ParticleError]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization1-tau--None]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization2-Fe-56+-None]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization3-Fe+-ParticleError]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization4-Fe+-None]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization5-Fe-ChargeError]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization6-Fe-ChargeError]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization7-Fe-ChargeError]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization8-Fe",
"tests/particles/test_decorators.py::test_decorator_categories[categorization9-p+-None]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization10-p+-None]",
"tests/particles/test_decorators.py::test_decorator_categories[categorization11-p+-ParticleError]",
"tests/particles/test_decorators.py::test_optional_particle_annotation_parameter",
"tests/particles/test_decorators.py::test_stacking_decorators[particle_input-validate_quantities]",
"tests/particles/test_decorators.py::test_stacking_decorators[decorator11-validate_quantities]",
"tests/particles/test_decorators.py::test_stacking_decorators[particle_input-decorator22]",
"tests/particles/test_decorators.py::test_stacking_decorators[decorator13-decorator23]",
"tests/particles/test_decorators.py::test_preserving_signature_with_stacked_decorators[particle_input-validate_quantities]",
"tests/particles/test_decorators.py::test_preserving_signature_with_stacked_decorators[decorator11-validate_quantities]",
"tests/particles/test_decorators.py::test_preserving_signature_with_stacked_decorators[particle_input-decorator22]",
"tests/particles/test_decorators.py::test_preserving_signature_with_stacked_decorators[decorator13-decorator23]",
"tests/particles/test_decorators.py::test_annotated_classmethod",
"tests/particles/test_decorators.py::test_self_stacked_decorator[particle_input-particle_input]",
"tests/particles/test_decorators.py::test_self_stacked_decorator[particle_input-outer_decorator1]",
"tests/particles/test_decorators.py::test_self_stacked_decorator[inner_decorator1-particle_input]",
"tests/particles/test_decorators.py::test_self_stacked_decorator[inner_decorator1-outer_decorator1]",
"tests/particles/test_decorators.py::test_class_stacked_decorator[particle_input-particle_input]",
"tests/particles/test_decorators.py::test_class_stacked_decorator[particle_input-outer_decorator1]",
"tests/particles/test_decorators.py::test_class_stacked_decorator[inner_decorator1-particle_input]",
"tests/particles/test_decorators.py::test_class_stacked_decorator[inner_decorator1-outer_decorator1]",
"tests/particles/test_decorators.py::test_annotated_init",
"tests/particles/test_decorators.py::test_particle_input_with_validate_quantities[particle_input-inner_decorator0]",
"tests/particles/test_decorators.py::test_particle_input_with_validate_quantities[outer_decorator1-inner_decorator1]",
"tests/particles/test_decorators.py::test_particle_input_verification[kwargs_to_particle_input0-arg0]",
"tests/particles/test_decorators.py::test_particle_input_verification[kwargs_to_particle_input1-arg1]",
"tests/particles/test_decorators.py::test_particle_input_verification[kwargs_to_particle_input2-arg2]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_individual_particles_not_in_category[case0]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_individual_particles_not_in_category[case1]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_individual_particles_not_in_category[case2]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_not_in_category[case0]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_not_in_category[case1]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_not_in_category[case2]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_some_in_category[case0]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_some_in_category[case1]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_some_in_category[case2]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_individual_particles_all_in_category[case0]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_individual_particles_all_in_category[case1]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_individual_particles_all_in_category[case2]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_all_in_category[case0]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_all_in_category[case1]",
"tests/particles/test_decorators.py::TestParticleInputParameterNames::test_particle_list_all_in_category[case2]",
"tests/particles/test_decorators.py::test_custom_particle_for_parameter_named_ion",
"tests/particles/test_decorators.py::test_creating_mean_particle_for_parameter_named_ion",
"tests/particles/test_decorators.py::test_particle_input_warning_for_integer_z_mean",
"tests/particles/test_decorators.py::test_particle_input_warning_for_float_z_mean",
"tests/particles/test_decorators.py::test_particle_input_with_var_positional_arguments"
] |
[] |
BSD 3-Clause "New" or "Revised" License
| 18,009
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.plasmapy_1776_plasmapy-2594:latest
|
LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/particles/test_decorators.py
|
#!/bin/bash
set -uxo pipefail
source /opt/miniconda3/bin/activate
conda activate testbed
cd /testbed
git config --global --add safe.directory /testbed
cd /testbed
git status
git show
git -c core.fileMode=false diff 221e4b73797c97459f90b5055648075fea9380ad
source /opt/miniconda3/bin/activate
conda activate testbed
LANG=C.UTF-8 LC_ALL=C.UTF-8 pip install -e .[tests,docs]
git checkout 221e4b73797c97459f90b5055648075fea9380ad tests/particles/test_decorators.py
git apply -v - <<'EOF_114329324912'
diff --git a/tests/particles/test_decorators.py b/tests/particles/test_decorators.py
index 6063da3d..3d7cdc73 100644
--- a/tests/particles/test_decorators.py
+++ b/tests/particles/test_decorators.py
@@ -18,7 +18,7 @@
ParticleError,
)
from plasmapy.particles.particle_class import CustomParticle, Particle, ParticleLike
-from plasmapy.particles.particle_collections import ParticleList
+from plasmapy.particles.particle_collections import ParticleList, ParticleListLike
from plasmapy.utils.code_repr import call_string
from plasmapy.utils.decorators.validators import validate_quantities
from plasmapy.utils.exceptions import PlasmaPyDeprecationWarning
@@ -748,3 +748,31 @@ def function_with_pos_and_var_positional_arguments(
expected = (a, args, Particle(particle))
actual = function_with_pos_and_var_positional_arguments(a, *args, particle=particle)
assert actual == expected
+
+
[email protected](
+ ("criteria", "kwargs", "exception"),
+ [
+ ({"require": "ion"}, {"particle": ["p+", "He"]}, ParticleError),
+ ({"require": "isotope"}, {"particle": ["p+", "He"]}, ParticleError),
+ (
+ {"any_of": {"lepton", "neutrino"}},
+ {"particle": ["p+", "alpha"]},
+ ParticleError,
+ ),
+ ({"exclude": "lepton"}, {"particle": ["p+", "e-"]}, ParticleError),
+ ],
+)
+def test_particle_categorization_of_particle_lists(
+ criteria: dict[str, str | Iterable[str]],
+ kwargs: dict[str, ParticleListLike],
+ exception: Exception,
+) -> None:
+ @particle_input(**criteria) # type: ignore[arg-type]
+ def get_particle(
+ particle: ParticleLike,
+ ) -> Particle | ParticleList | CustomParticle:
+ return particle # type: ignore[return-value]
+
+ with pytest.raises(exception): # type: ignore[call-overload]
+ get_particle(**kwargs)
EOF_114329324912
: '>>>>> Start Test Output'
LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/particles/test_decorators.py
: '>>>>> End Test Output'
git checkout 221e4b73797c97459f90b5055648075fea9380ad tests/particles/test_decorators.py
|
posit-dev__posit-sdk-py-123
|
34ec27857ee52c8808eac176d744953a6ace7e05
|
2024-03-22 00:28:04
|
34ec27857ee52c8808eac176d744953a6ace7e05
|
github-actions[bot]: # ☂️ Python Coverage
> current status: ✅
## Overall Coverage
| Lines | Covered | Coverage | Threshold | Status |
| :---: | :-----: | :------: | :-------: | :----: |
| 537 | 449 | 84% | 80% | 🟢 |
## New Files
No new covered files...
## Modified Files
| File | Coverage | Status |
| :------------------------- | :------: | :----: |
| src/posit/connect/users.py | 92% | 🟢 |
| **TOTAL** | **92%** | 🟢 |
> **updated for commit: `ff2b3dc` by [action](https://github.com/marketplace/actions/python-coverage)🐍**
|
diff --git a/src/posit/connect/client.py b/src/posit/connect/client.py
index aee65f8..7f6ad60 100644
--- a/src/posit/connect/client.py
+++ b/src/posit/connect/client.py
@@ -3,7 +3,7 @@ from __future__ import annotations
from requests import Response, Session
from typing import Optional
-from . import hooks, urls
+from . import hooks, me, urls
from .auth import Auth
from .config import Config
@@ -48,9 +48,7 @@ class Client:
@property
def me(self) -> User:
- url = urls.append_path(self.config.url, "v1/user")
- response = self.session.get(url)
- return User(self.config, self.session, **response.json())
+ return me.get(self.config, self.session)
@property
def oauth(self) -> OAuthIntegration:
diff --git a/src/posit/connect/me.py b/src/posit/connect/me.py
new file mode 100644
index 0000000..71ad7e5
--- /dev/null
+++ b/src/posit/connect/me.py
@@ -0,0 +1,22 @@
+import requests
+
+from . import urls
+
+from .config import Config
+from .users import User
+
+
+def get(config: Config, session: requests.Session) -> User:
+ """
+ Gets the current user.
+
+ Args:
+ config (Config): The configuration object containing the URL.
+ session (requests.Session): The session object used for making HTTP requests.
+
+ Returns:
+ User: The current user.
+ """
+ url = urls.append_path(config.url, "v1/user")
+ response = session.get(url)
+ return User(config, session, **response.json())
diff --git a/src/posit/connect/users.py b/src/posit/connect/users.py
index aff680a..ba48be1 100644
--- a/src/posit/connect/users.py
+++ b/src/posit/connect/users.py
@@ -5,7 +5,7 @@ from typing import List, Optional
import requests
-from . import urls
+from . import me, urls
from .config import Config
from .paginator import Paginator
@@ -57,6 +57,40 @@ class User(Resource):
def locked(self) -> bool:
return self.get("locked") # type: ignore
+ def lock(self, *, force: bool = False):
+ """
+ Locks the user account.
+
+ .. warning:: You cannot unlock your own account. Once an account is locked, only an admin can unlock it.
+
+ Args:
+ force (bool, optional): If set to True, overrides lock protection allowing a user to lock their own account. Defaults to False.
+
+ Returns:
+ None
+ """
+ _me = me.get(self.config, self.session)
+ if _me.guid == self.guid and not force:
+ raise RuntimeError(
+ "You cannot lock your own account. Set force=True to override this behavior."
+ )
+ url = urls.append_path(self.config.url, f"v1/users/{self.guid}/lock")
+ body = {"locked": True}
+ self.session.post(url, json=body)
+ super().update(locked=True)
+
+ def unlock(self):
+ """
+ Unlocks the user account.
+
+ Returns:
+ None
+ """
+ url = urls.append_path(self.config.url, f"v1/users/{self.guid}/lock")
+ body = {"locked": False}
+ self.session.post(url, json=body)
+ super().update(locked=False)
+
def _update(self, body):
if len(body) == 0:
return
@@ -126,13 +160,12 @@ class Users(Resources[User]):
return next(users, None)
def get(self, id: str) -> User:
- url = urls.append_path(self.url, id)
+ url = urls.append_path(self.config.url, f"v1/users/{id}")
response = self.session.get(url)
- raw_user = response.json()
return User(
config=self.config,
session=self.session,
- **raw_user,
+ **response.json(),
)
def create(self) -> User:
|
Add User.lock() and .unlock()
In the API, `locked` is not set by PATCHing the User, it is a separate POST endpoint. Seems reasonable to follow that and have lock/unlock methods on the user to do that.
Also may want a bulk edit method on Users, which accepts guids and (for now at least) updates each one at a time.
|
posit-dev/posit-sdk-py
|
diff --git a/tests/posit/connect/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.json b/tests/posit/connect/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.json
new file mode 100644
index 0000000..d01b5f6
--- /dev/null
+++ b/tests/posit/connect/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.json
@@ -0,0 +1,13 @@
+{
+ "email": "[email protected]",
+ "username": "random_username",
+ "first_name": "Random",
+ "last_name": "User",
+ "user_role": "admin",
+ "created_time": "2022-01-01T00:00:00Z",
+ "updated_time": "2022-03-15T12:34:56Z",
+ "active_time": "2022-02-28T18:30:00Z",
+ "confirmed": false,
+ "locked": true,
+ "guid": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6"
+}
diff --git a/tests/posit/connect/test_users.py b/tests/posit/connect/test_users.py
index 237c2d7..c61e8c3 100644
--- a/tests/posit/connect/test_users.py
+++ b/tests/posit/connect/test_users.py
@@ -92,6 +92,87 @@ class TestUser:
user = User(session, url, locked=False)
assert user.locked is False
+ @responses.activate
+ def test_lock(self):
+ responses.get(
+ "https://connect.example/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6",
+ json=load_mock("v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.json"),
+ )
+ c = Client(api_key="12345", url="https://connect.example/")
+ user = c.users.get("a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6")
+ assert user.guid == "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6"
+
+ responses.get(
+ "https://connect.example/__api__/v1/user",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ responses.post(
+ "https://connect.example/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6/lock",
+ match=[responses.matchers.json_params_matcher({"locked": True})],
+ )
+ user.lock()
+ assert user.locked
+
+ @responses.activate
+ def test_lock_self_true(self):
+ responses.get(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ c = Client(api_key="12345", url="https://connect.example/")
+ user = c.users.get("20a79ce3-6e87-4522-9faf-be24228800a4")
+ assert user.guid == "20a79ce3-6e87-4522-9faf-be24228800a4"
+
+ responses.get(
+ "https://connect.example/__api__/v1/user",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ responses.post(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4/lock",
+ match=[responses.matchers.json_params_matcher({"locked": True})],
+ )
+ user.lock(force=True)
+ assert user.locked
+
+ @responses.activate
+ def test_lock_self_false(self):
+ responses.get(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ c = Client(api_key="12345", url="https://connect.example/")
+ user = c.users.get("20a79ce3-6e87-4522-9faf-be24228800a4")
+ assert user.guid == "20a79ce3-6e87-4522-9faf-be24228800a4"
+
+ responses.get(
+ "https://connect.example/__api__/v1/user",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ responses.post(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4/lock",
+ match=[responses.matchers.json_params_matcher({"locked": True})],
+ )
+ with pytest.raises(RuntimeError):
+ user.lock(force=False)
+ assert not user.locked
+
+ @responses.activate
+ def test_unlock(self):
+ responses.get(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ c = Client(api_key="12345", url="https://connect.example/")
+ user = c.users.get("20a79ce3-6e87-4522-9faf-be24228800a4")
+ assert user.guid == "20a79ce3-6e87-4522-9faf-be24228800a4"
+
+ responses.post(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4/lock",
+ match=[responses.matchers.json_params_matcher({"locked": False})],
+ )
+ user.unlock()
+ assert not user.locked
+
class TestUsers:
@responses.activate
|
{
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 0
},
"num_modified_files": 2
}
|
unknown
|
{
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": null,
"python": "3.9",
"reqs_path": [
"requirements.txt",
"requirements-dev.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
}
|
build==1.2.2.post1
certifi==2025.1.31
cfgv==3.4.0
charset-normalizer==3.4.1
coverage==7.8.0
distlib==0.3.9
exceptiongroup==1.2.2
filelock==3.18.0
identify==2.6.9
idna==3.10
importlib_metadata==8.6.1
iniconfig==2.1.0
mypy==1.15.0
mypy-extensions==1.0.0
nodeenv==1.9.1
numpy==2.0.2
packaging==24.2
pandas==2.2.3
platformdirs==4.3.7
pluggy==1.5.0
-e git+https://github.com/posit-dev/posit-sdk-py.git@34ec27857ee52c8808eac176d744953a6ace7e05#egg=posit_sdk
pre_commit==4.2.0
pyproject_hooks==1.2.0
pytest==8.3.5
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.2
requests==2.31.0
responses==0.25.7
ruff==0.11.2
setuptools-scm==8.2.0
six==1.17.0
tomli==2.2.1
typing_extensions==4.13.0
tzdata==2025.2
urllib3==2.3.0
virtualenv==20.29.3
zipp==3.21.0
|
name: posit-sdk-py
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- build==1.2.2.post1
- certifi==2025.1.31
- cfgv==3.4.0
- charset-normalizer==3.4.1
- coverage==7.8.0
- distlib==0.3.9
- exceptiongroup==1.2.2
- filelock==3.18.0
- identify==2.6.9
- idna==3.10
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- mypy==1.15.0
- mypy-extensions==1.0.0
- nodeenv==1.9.1
- numpy==2.0.2
- packaging==24.2
- pandas==2.2.3
- platformdirs==4.3.7
- pluggy==1.5.0
- posit-sdk==0.1.dev67+g34ec278
- pre-commit==4.2.0
- pyproject-hooks==1.2.0
- pytest==8.3.5
- python-dateutil==2.9.0.post0
- pytz==2025.2
- pyyaml==6.0.2
- requests==2.31.0
- responses==0.25.7
- ruff==0.11.2
- setuptools-scm==8.2.0
- six==1.17.0
- tomli==2.2.1
- typing-extensions==4.13.0
- tzdata==2025.2
- urllib3==2.3.0
- virtualenv==20.29.3
- zipp==3.21.0
prefix: /opt/conda/envs/posit-sdk-py
|
[
"tests/posit/connect/test_users.py::TestUser::test_lock",
"tests/posit/connect/test_users.py::TestUser::test_lock_self_true",
"tests/posit/connect/test_users.py::TestUser::test_lock_self_false",
"tests/posit/connect/test_users.py::TestUser::test_unlock"
] |
[] |
[
"tests/posit/connect/test_users.py::TestUser::test_guid",
"tests/posit/connect/test_users.py::TestUser::test_email",
"tests/posit/connect/test_users.py::TestUser::test_username",
"tests/posit/connect/test_users.py::TestUser::test_first_name",
"tests/posit/connect/test_users.py::TestUser::test_last_name",
"tests/posit/connect/test_users.py::TestUser::test_user_role",
"tests/posit/connect/test_users.py::TestUser::test_created_time",
"tests/posit/connect/test_users.py::TestUser::test_updated_time",
"tests/posit/connect/test_users.py::TestUser::test_active_time",
"tests/posit/connect/test_users.py::TestUser::test_confirmed",
"tests/posit/connect/test_users.py::TestUser::test_locked",
"tests/posit/connect/test_users.py::TestUsers::test_users_find",
"tests/posit/connect/test_users.py::TestUsers::test_users_find_one",
"tests/posit/connect/test_users.py::TestUsers::test_users_find_one_only_gets_necessary_pages",
"tests/posit/connect/test_users.py::TestUsers::test_users_find_one_finds_nothing",
"tests/posit/connect/test_users.py::TestUsers::test_users_get",
"tests/posit/connect/test_users.py::TestUsers::test_users_get_extra_fields",
"tests/posit/connect/test_users.py::TestUsers::test_user_update",
"tests/posit/connect/test_users.py::TestUsers::test_user_update_server_error",
"tests/posit/connect/test_users.py::TestUsers::test_user_cant_setattr",
"tests/posit/connect/test_users.py::TestUsers::test_count"
] |
[] |
MIT License
| 18,010
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.posit-dev_1776_posit-sdk-py-123:latest
|
LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/posit/connect/test_users.py
|
#!/bin/bash
set -uxo pipefail
source /opt/miniconda3/bin/activate
conda activate testbed
cd /testbed
git config --global --add safe.directory /testbed
cd /testbed
git status
git show
git -c core.fileMode=false diff 34ec27857ee52c8808eac176d744953a6ace7e05
source /opt/miniconda3/bin/activate
conda activate testbed
LANG=C.UTF-8 LC_ALL=C.UTF-8 pip install -e .
git checkout 34ec27857ee52c8808eac176d744953a6ace7e05 tests/posit/connect/test_users.py
git apply -v - <<'EOF_114329324912'
diff --git a/tests/posit/connect/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.json b/tests/posit/connect/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.json
new file mode 100644
index 0000000..d01b5f6
--- /dev/null
+++ b/tests/posit/connect/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.json
@@ -0,0 +1,13 @@
+{
+ "email": "[email protected]",
+ "username": "random_username",
+ "first_name": "Random",
+ "last_name": "User",
+ "user_role": "admin",
+ "created_time": "2022-01-01T00:00:00Z",
+ "updated_time": "2022-03-15T12:34:56Z",
+ "active_time": "2022-02-28T18:30:00Z",
+ "confirmed": false,
+ "locked": true,
+ "guid": "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6"
+}
diff --git a/tests/posit/connect/test_users.py b/tests/posit/connect/test_users.py
index 237c2d7..c61e8c3 100644
--- a/tests/posit/connect/test_users.py
+++ b/tests/posit/connect/test_users.py
@@ -92,6 +92,87 @@ class TestUser:
user = User(session, url, locked=False)
assert user.locked is False
+ @responses.activate
+ def test_lock(self):
+ responses.get(
+ "https://connect.example/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6",
+ json=load_mock("v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6.json"),
+ )
+ c = Client(api_key="12345", url="https://connect.example/")
+ user = c.users.get("a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6")
+ assert user.guid == "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6"
+
+ responses.get(
+ "https://connect.example/__api__/v1/user",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ responses.post(
+ "https://connect.example/__api__/v1/users/a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6/lock",
+ match=[responses.matchers.json_params_matcher({"locked": True})],
+ )
+ user.lock()
+ assert user.locked
+
+ @responses.activate
+ def test_lock_self_true(self):
+ responses.get(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ c = Client(api_key="12345", url="https://connect.example/")
+ user = c.users.get("20a79ce3-6e87-4522-9faf-be24228800a4")
+ assert user.guid == "20a79ce3-6e87-4522-9faf-be24228800a4"
+
+ responses.get(
+ "https://connect.example/__api__/v1/user",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ responses.post(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4/lock",
+ match=[responses.matchers.json_params_matcher({"locked": True})],
+ )
+ user.lock(force=True)
+ assert user.locked
+
+ @responses.activate
+ def test_lock_self_false(self):
+ responses.get(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ c = Client(api_key="12345", url="https://connect.example/")
+ user = c.users.get("20a79ce3-6e87-4522-9faf-be24228800a4")
+ assert user.guid == "20a79ce3-6e87-4522-9faf-be24228800a4"
+
+ responses.get(
+ "https://connect.example/__api__/v1/user",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ responses.post(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4/lock",
+ match=[responses.matchers.json_params_matcher({"locked": True})],
+ )
+ with pytest.raises(RuntimeError):
+ user.lock(force=False)
+ assert not user.locked
+
+ @responses.activate
+ def test_unlock(self):
+ responses.get(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4",
+ json=load_mock("v1/users/20a79ce3-6e87-4522-9faf-be24228800a4.json"),
+ )
+ c = Client(api_key="12345", url="https://connect.example/")
+ user = c.users.get("20a79ce3-6e87-4522-9faf-be24228800a4")
+ assert user.guid == "20a79ce3-6e87-4522-9faf-be24228800a4"
+
+ responses.post(
+ "https://connect.example/__api__/v1/users/20a79ce3-6e87-4522-9faf-be24228800a4/lock",
+ match=[responses.matchers.json_params_matcher({"locked": False})],
+ )
+ user.unlock()
+ assert not user.locked
+
class TestUsers:
@responses.activate
EOF_114329324912
: '>>>>> Start Test Output'
LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/posit/connect/test_users.py
: '>>>>> End Test Output'
git checkout 34ec27857ee52c8808eac176d744953a6ace7e05 tests/posit/connect/test_users.py
|
canonical__charmcraft-1615
|
0fbe2f8085de31b3997be4877f733f70f650b15e
|
2024-03-22 01:58:46
|
0fbe2f8085de31b3997be4877f733f70f650b15e
|
syu-w: I wonder if this affect reactive charm
|
diff --git a/charmcraft/application/main.py b/charmcraft/application/main.py
index cf4b60a7..cd59750f 100644
--- a/charmcraft/application/main.py
+++ b/charmcraft/application/main.py
@@ -69,6 +69,8 @@ class Charmcraft(Application):
preprocess.add_default_parts(yaml_data)
preprocess.add_bundle_snippet(self.project_dir, yaml_data)
+ preprocess.add_config(self.project_dir, yaml_data)
+ preprocess.add_actions(self.project_dir, yaml_data)
yaml_data = extensions.apply_extensions(self.project_dir, yaml_data)
diff --git a/charmcraft/models/project.py b/charmcraft/models/project.py
index 4ee97e5b..51ae653f 100644
--- a/charmcraft/models/project.py
+++ b/charmcraft/models/project.py
@@ -34,14 +34,10 @@ from typing_extensions import Self, TypedDict
from charmcraft import const, preprocess, utils
from charmcraft.const import (
- JUJU_ACTIONS_FILENAME,
- JUJU_CONFIG_FILENAME,
BaseStr,
BuildBaseStr,
CharmArch,
)
-from charmcraft.metafiles.actions import parse_actions_yaml
-from charmcraft.metafiles.config import parse_config_yaml
from charmcraft.models import charmcraft
from charmcraft.models.charmcraft import (
AnalysisConfig,
@@ -440,24 +436,8 @@ class CharmcraftProject(models.Project, metaclass=abc.ABCMeta):
preprocess.add_default_parts(data)
preprocess.add_bundle_snippet(project_dir, data)
preprocess.add_metadata(project_dir, data)
-
- config_file = project_dir / JUJU_CONFIG_FILENAME
- if config_file.is_file():
- if "config" in data:
- raise errors.CraftValidationError(
- f"Cannot specify 'config' section in 'charmcraft.yaml' when {JUJU_CONFIG_FILENAME!r} exists",
- resolution=f"Move all data from {JUJU_CONFIG_FILENAME!r} to the 'config' section in 'charmcraft.yaml'",
- )
- data["config"] = parse_config_yaml(project_dir, allow_broken=True)
-
- actions_file = project_dir / JUJU_ACTIONS_FILENAME
- if actions_file.is_file():
- if "actions" in data:
- raise errors.CraftValidationError(
- f"Cannot specify 'actions' section in 'charmcraft.yaml' when {JUJU_ACTIONS_FILENAME!r} exists",
- resolution=f"Move all data from {JUJU_ACTIONS_FILENAME!r} to the 'actions' section in 'charmcraft.yaml'",
- )
- data["actions"] = parse_actions_yaml(project_dir).actions
+ preprocess.add_config(project_dir, data)
+ preprocess.add_actions(project_dir, data)
try:
project = cls.unmarshal(data)
diff --git a/charmcraft/preprocess.py b/charmcraft/preprocess.py
index 084fb4d3..08295335 100644
--- a/charmcraft/preprocess.py
+++ b/charmcraft/preprocess.py
@@ -21,9 +21,9 @@ to do pre-processing on a charmcraft.yaml file before applying extensions.
import pathlib
from typing import Any
-from craft_application import util
+from craft_application import errors, util
-from charmcraft import const, errors, utils
+from charmcraft import const, utils
def add_default_parts(yaml_data: dict[str, Any]) -> None:
@@ -54,7 +54,7 @@ def add_metadata(project_dir: pathlib.Path, yaml_data: dict[str, Any]) -> None:
with metadata_path.open() as file:
metadata_yaml = util.safe_yaml_load(file)
if not isinstance(metadata_yaml, dict):
- raise errors.CraftError(
+ raise errors.CraftValidationError(
"Invalid file: 'metadata.yaml'",
resolution="Ensure metadata.yaml meets the juju metadata.yaml specification.",
docs_url="https://juju.is/docs/sdk/metadata-yaml",
@@ -66,7 +66,7 @@ def add_metadata(project_dir: pathlib.Path, yaml_data: dict[str, Any]) -> None:
duplicate_fields.append(field)
yaml_data.setdefault(field, metadata_yaml.get(field))
if duplicate_fields:
- raise errors.CraftError(
+ raise errors.CraftValidationError(
"Fields in charmcraft.yaml cannot be duplicated in metadata.yaml",
details=f"Duplicate fields: {utils.humanize_list(duplicate_fields, 'and')}",
resolution="Remove the duplicate fields from metadata.yaml.",
@@ -74,7 +74,7 @@ def add_metadata(project_dir: pathlib.Path, yaml_data: dict[str, Any]) -> None:
)
-def add_bundle_snippet(project_dir: pathlib.Path, yaml_data: dict[str, Any]):
+def add_bundle_snippet(project_dir: pathlib.Path, yaml_data: dict[str, Any]) -> None:
"""Add metadata from bundle.yaml to a bundle.
:param yaml_data: The raw YAML dictionary of the project.
@@ -86,7 +86,7 @@ def add_bundle_snippet(project_dir: pathlib.Path, yaml_data: dict[str, Any]):
bundle_file = project_dir / const.BUNDLE_FILENAME
if not bundle_file.is_file():
- raise errors.CraftError(
+ raise errors.CraftValidationError(
f"Missing 'bundle.yaml' file: {str(bundle_file)!r}",
resolution="Create a 'bundle.yaml' file in the same directory as 'charmcraft.yaml'.",
docs_url="https://juju.is/docs/sdk/create-a-charm-bundle",
@@ -97,7 +97,7 @@ def add_bundle_snippet(project_dir: pathlib.Path, yaml_data: dict[str, Any]):
with bundle_file.open() as bf:
bundle = util.safe_yaml_load(bf)
if not isinstance(bundle, dict):
- raise errors.CraftError(
+ raise errors.CraftValidationError(
"Incorrectly formatted 'bundle.yaml' file",
resolution="Ensure 'bundle.yaml' matches the Juju 'bundle.yaml' format.",
docs_url="https://juju.is/docs/sdk/charm-bundles",
@@ -105,3 +105,50 @@ def add_bundle_snippet(project_dir: pathlib.Path, yaml_data: dict[str, Any]):
retcode=65, # EX_DATAERR from sysexits.h
)
yaml_data["bundle"] = bundle
+
+
+def add_config(project_dir: pathlib.Path, yaml_data: dict[str, Any]) -> None:
+ """Add configuration options from config.yaml to existing YAML data.
+
+ :param project_dir: The Path to the directory containing charmcraft.yaml
+ :param yaml_data: The raw YAML dictionary of the project.
+ :returns: The same dictionary passed in, with necessary mutations.
+ """
+ config_file = project_dir / const.JUJU_CONFIG_FILENAME
+ if not config_file.exists():
+ return
+
+ if "config" in yaml_data:
+ raise errors.CraftValidationError(
+ f"Cannot specify 'config' section in 'charmcraft.yaml' when {const.JUJU_CONFIG_FILENAME!r} exists",
+ resolution=f"Move all data from {const.JUJU_CONFIG_FILENAME!r} to the 'config' section in 'charmcraft.yaml'",
+ docs_url="https://juju.is/docs/sdk/charmcraft-yaml",
+ retcode=65, # Data error, per sysexits.h
+ )
+
+ with config_file.open() as f:
+ yaml_data["config"] = util.safe_yaml_load(f)
+
+
+def add_actions(project_dir: pathlib.Path, yaml_data: dict[str, Any]) -> None:
+ """Add actions from actions.yaml to existing YAML data.
+
+ :param project_dir: The Path to the directory containing charmcraft.yaml
+ :param yaml_data: The raw YAML dictionary of the project.
+ :returns: The same dictionary passed in, with necessary mutations.
+ """
+ actions_file = project_dir / const.JUJU_ACTIONS_FILENAME
+ if not actions_file.exists():
+ return
+
+ if "actions" in yaml_data:
+ raise errors.CraftValidationError(
+ f"Cannot specify 'actions' section in 'charmcraft.yaml' when {const.JUJU_ACTIONS_FILENAME!r} exists",
+ resolution=f"Move all data from {const.JUJU_ACTIONS_FILENAME!r} to the 'actions' section in 'charmcraft.yaml'",
+ docs_url="https://juju.is/docs/sdk/charmcraft-yaml",
+ retcode=65, # Data error, per sysexits.h
+ )
+ with actions_file.open() as f:
+ actions = util.safe_yaml_load(f)
+ if actions and isinstance(actions, dict):
+ yaml_data["actions"] = actions
|
Move additional YAML file loads into _extra_yaml_transform
### What needs to get done
Instead of using the CharmcraftProject model's `from_yaml_file` method to do everything, preprocess the following files in functions called from _extra_yaml_transform:
- [ ] bundle.yaml (this can be added to the `_bundle` extension)
- [ ] metadata.yaml
- [ ] config.yaml
- [ ] actions.yaml
### Why it needs to get done
That's a very long method that really should be broken up and moved to craft-application 2.0 standards
|
canonical/charmcraft
|
diff --git a/tests/integration/sample-charms/actions-included/charmcraft.yaml b/tests/integration/sample-charms/actions-included/charmcraft.yaml
new file mode 100644
index 00000000..23239d7b
--- /dev/null
+++ b/tests/integration/sample-charms/actions-included/charmcraft.yaml
@@ -0,0 +1,38 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
+
+actions:
+ pause:
+ description: Pause the database.
+ resume:
+ description: Resume a paused database.
+ snapshot:
+ description: Take a snapshot of the database.
+ params:
+ filename:
+ type: string
+ description: The name of the snapshot file.
+ compression:
+ type: object
+ description: The type of compression to use.
+ properties:
+ kind:
+ type: string
+ enum: [gzip, bzip2, xz]
+ quality:
+ description: Compression quality
+ type: integer
+ minimum: 0
+ maximum: 9
+ required: [filename]
+ additionalProperties: false
diff --git a/tests/integration/sample-charms/actions-included/expected.yaml b/tests/integration/sample-charms/actions-included/expected.yaml
new file mode 100644
index 00000000..074bf477
--- /dev/null
+++ b/tests/integration/sample-charms/actions-included/expected.yaml
@@ -0,0 +1,46 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+actions:
+ pause:
+ description: Pause the database.
+ resume:
+ description: Resume a paused database.
+ snapshot:
+ description: Take a snapshot of the database.
+ params:
+ filename:
+ type: string
+ description: The name of the snapshot file.
+ compression:
+ type: object
+ description: The type of compression to use.
+ properties:
+ kind:
+ type: string
+ enum:
+ - gzip
+ - bzip2
+ - xz
+ quality:
+ description: Compression quality
+ type: integer
+ minimum: 0
+ maximum: 9
+ required:
+ - filename
+ additionalProperties: false
diff --git a/tests/integration/sample-charms/actions-separate/actions.yaml b/tests/integration/sample-charms/actions-separate/actions.yaml
new file mode 100644
index 00000000..b155d4b8
--- /dev/null
+++ b/tests/integration/sample-charms/actions-separate/actions.yaml
@@ -0,0 +1,24 @@
+pause:
+ description: Pause the database.
+resume:
+ description: Resume a paused database.
+snapshot:
+ description: Take a snapshot of the database.
+ params:
+ filename:
+ type: string
+ description: The name of the snapshot file.
+ compression:
+ type: object
+ description: The type of compression to use.
+ properties:
+ kind:
+ type: string
+ enum: [gzip, bzip2, xz]
+ quality:
+ description: Compression quality
+ type: integer
+ minimum: 0
+ maximum: 9
+ required: [filename]
+ additionalProperties: false
diff --git a/tests/integration/sample-charms/actions-separate/charmcraft.yaml b/tests/integration/sample-charms/actions-separate/charmcraft.yaml
new file mode 100644
index 00000000..d681da9a
--- /dev/null
+++ b/tests/integration/sample-charms/actions-separate/charmcraft.yaml
@@ -0,0 +1,12 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
diff --git a/tests/integration/sample-charms/actions-separate/expected.yaml b/tests/integration/sample-charms/actions-separate/expected.yaml
new file mode 100644
index 00000000..074bf477
--- /dev/null
+++ b/tests/integration/sample-charms/actions-separate/expected.yaml
@@ -0,0 +1,46 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+actions:
+ pause:
+ description: Pause the database.
+ resume:
+ description: Resume a paused database.
+ snapshot:
+ description: Take a snapshot of the database.
+ params:
+ filename:
+ type: string
+ description: The name of the snapshot file.
+ compression:
+ type: object
+ description: The type of compression to use.
+ properties:
+ kind:
+ type: string
+ enum:
+ - gzip
+ - bzip2
+ - xz
+ quality:
+ description: Compression quality
+ type: integer
+ minimum: 0
+ maximum: 9
+ required:
+ - filename
+ additionalProperties: false
diff --git a/tests/integration/sample-charms/basic-bases/charmcraft.yaml b/tests/integration/sample-charms/basic-bases/charmcraft.yaml
new file mode 100644
index 00000000..3e078462
--- /dev/null
+++ b/tests/integration/sample-charms/basic-bases/charmcraft.yaml
@@ -0,0 +1,12 @@
+name: example-charm
+summary: An example charm with bases
+description: |
+ A description for an example charm with bases.
+type: charm
+bases:
+ - name: ubuntu
+ channel: "22.04"
+
+parts:
+ charm:
+ plugin: charm
diff --git a/tests/integration/sample-charms/basic-bases/expected.yaml b/tests/integration/sample-charms/basic-bases/expected.yaml
new file mode 100644
index 00000000..a7f02d3d
--- /dev/null
+++ b/tests/integration/sample-charms/basic-bases/expected.yaml
@@ -0,0 +1,21 @@
+name: example-charm
+summary: An example charm with bases
+description: |
+ A description for an example charm with bases.
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+bases:
+- build-on:
+ - name: ubuntu
+ channel: '22.04'
+ run-on:
+ - name: ubuntu
+ channel: '22.04'
diff --git a/tests/integration/sample-charms/basic-platforms/charmcraft.yaml b/tests/integration/sample-charms/basic-platforms/charmcraft.yaml
new file mode 100644
index 00000000..d681da9a
--- /dev/null
+++ b/tests/integration/sample-charms/basic-platforms/charmcraft.yaml
@@ -0,0 +1,12 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
diff --git a/tests/integration/sample-charms/basic-platforms/expected.yaml b/tests/integration/sample-charms/basic-platforms/expected.yaml
new file mode 100644
index 00000000..95213900
--- /dev/null
+++ b/tests/integration/sample-charms/basic-platforms/expected.yaml
@@ -0,0 +1,17 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
diff --git a/tests/integration/sample-charms/config-included/charmcraft.yaml b/tests/integration/sample-charms/config-included/charmcraft.yaml
new file mode 100644
index 00000000..44a0837a
--- /dev/null
+++ b/tests/integration/sample-charms/config-included/charmcraft.yaml
@@ -0,0 +1,33 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
+
+config:
+ options:
+ admins:
+ description: 'Comma-separated list of admin users to create: user:pass[,user:pass]+'
+ type: string
+ debug:
+ default: false
+ description: turn on debugging features of mediawiki
+ type: boolean
+ logo:
+ description: URL to fetch logo from
+ type: string
+ name:
+ default: Wiki
+ description: The name, or Title of the Wiki
+ type: string
+ skin:
+ default: vector
+ description: skin for the Wiki
+ type: string
diff --git a/tests/integration/sample-charms/config-included/expected.yaml b/tests/integration/sample-charms/config-included/expected.yaml
new file mode 100644
index 00000000..ac875e8e
--- /dev/null
+++ b/tests/integration/sample-charms/config-included/expected.yaml
@@ -0,0 +1,37 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+config:
+ options:
+ admins:
+ description: 'Comma-separated list of admin users to create: user:pass[,user:pass]+'
+ type: string
+ debug:
+ default: false
+ description: turn on debugging features of mediawiki
+ type: boolean
+ logo:
+ description: URL to fetch logo from
+ type: string
+ name:
+ default: Wiki
+ description: The name, or Title of the Wiki
+ type: string
+ skin:
+ default: vector
+ description: skin for the Wiki
+ type: string
diff --git a/tests/integration/sample-charms/config-separate/charmcraft.yaml b/tests/integration/sample-charms/config-separate/charmcraft.yaml
new file mode 100644
index 00000000..d681da9a
--- /dev/null
+++ b/tests/integration/sample-charms/config-separate/charmcraft.yaml
@@ -0,0 +1,12 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
diff --git a/tests/integration/sample-charms/config-separate/config.yaml b/tests/integration/sample-charms/config-separate/config.yaml
new file mode 100644
index 00000000..4700abb9
--- /dev/null
+++ b/tests/integration/sample-charms/config-separate/config.yaml
@@ -0,0 +1,19 @@
+options:
+ admins:
+ description: 'Comma-separated list of admin users to create: user:pass[,user:pass]+'
+ type: string
+ debug:
+ default: false
+ description: turn on debugging features of mediawiki
+ type: boolean
+ logo:
+ description: URL to fetch logo from
+ type: string
+ name:
+ default: Wiki
+ description: The name, or Title of the Wiki
+ type: string
+ skin:
+ default: vector
+ description: skin for the Wiki
+ type: string
diff --git a/tests/integration/sample-charms/config-separate/expected.yaml b/tests/integration/sample-charms/config-separate/expected.yaml
new file mode 100644
index 00000000..ac875e8e
--- /dev/null
+++ b/tests/integration/sample-charms/config-separate/expected.yaml
@@ -0,0 +1,37 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+config:
+ options:
+ admins:
+ description: 'Comma-separated list of admin users to create: user:pass[,user:pass]+'
+ type: string
+ debug:
+ default: false
+ description: turn on debugging features of mediawiki
+ type: boolean
+ logo:
+ description: URL to fetch logo from
+ type: string
+ name:
+ default: Wiki
+ description: The name, or Title of the Wiki
+ type: string
+ skin:
+ default: vector
+ description: skin for the Wiki
+ type: string
diff --git a/tests/integration/test_application.py b/tests/integration/test_application.py
new file mode 100644
index 00000000..d8fe7aea
--- /dev/null
+++ b/tests/integration/test_application.py
@@ -0,0 +1,37 @@
+# Copyright 2024 Canonical Ltd.
+#
+# 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.
+#
+# For further info, check https://github.com/canonical/charmcraft
+"""Integration tests for the Charmcraft class."""
+import pathlib
+
+import pytest
+from craft_application import util
+
+from charmcraft import models
+
+
[email protected](
+ "charm_dir", sorted((pathlib.Path(__file__).parent / "sample-charms").iterdir())
+)
+def test_load_charm(app, charm_dir):
+ app.project_dir = charm_dir
+
+ project = app.get_project()
+ with (charm_dir / "expected.yaml").open() as f:
+ expected_data = util.safe_yaml_load(f)
+ expected_project = models.CharmcraftProject.unmarshal(expected_data)
+
+ assert project == expected_project
+ assert util.dump_yaml(project.marshal()) == (charm_dir / "expected.yaml").read_text()
diff --git a/tests/unit/test_preprocess.py b/tests/unit/test_preprocess.py
index 8bc4618a..c7fb429f 100644
--- a/tests/unit/test_preprocess.py
+++ b/tests/unit/test_preprocess.py
@@ -142,3 +142,40 @@ def test_add_bundle_snippet_invalid_file(fs, contents):
preprocess.add_bundle_snippet(pathlib.Path("project"), {"type": "bundle"})
assert exc_info.value.retcode == 65
+
+
[email protected](
+ ("yaml_data", "config_yaml", "expected"),
+ [
+ ({}, "{}", {"config": {}}),
+ ({}, "options:\n boop:\n type: int", {"config": {"options": {"boop": {"type": "int"}}}}),
+ ],
+)
+def test_add_config_success(fs, yaml_data, config_yaml, expected):
+ project_dir = pathlib.Path("project")
+ fs.create_file(project_dir / const.JUJU_CONFIG_FILENAME, contents=config_yaml)
+
+ preprocess.add_config(project_dir, yaml_data)
+
+ assert yaml_data == expected
+
+
[email protected](
+ ("yaml_data", "actions_yaml", "expected"),
+ [
+ ({}, "", {}),
+ ({}, "{}", {}),
+ (
+ {},
+ "boop:\n description: Boop in the snoot",
+ {"actions": {"boop": {"description": "Boop in the snoot"}}},
+ ),
+ ],
+)
+def test_add_actions_success(fs, yaml_data, actions_yaml, expected):
+ project_dir = pathlib.Path("project")
+ fs.create_file(project_dir / const.JUJU_ACTIONS_FILENAME, contents=actions_yaml)
+
+ preprocess.add_actions(project_dir, yaml_data)
+
+ assert yaml_data == expected
|
{
"commit_name": "merge_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 1,
"issue_text_score": 1,
"test_score": 2
},
"num_modified_files": 3
}
|
3.0
|
{
"env_vars": null,
"env_yml_path": null,
"install": "pip install -r requirements-dev.txt -e .",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest",
"pytest-cov",
"pytest-xdist",
"pytest-mock",
"pytest-asyncio"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.10",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
}
|
attrs==23.2.0
certifi==2024.2.2
cffi==1.16.0
-e git+https://github.com/canonical/charmcraft.git@0fbe2f8085de31b3997be4877f733f70f650b15e#egg=charmcraft
charset-normalizer==3.3.2
coverage==7.4.4
craft-application==2.0.0
craft-archives==1.1.3
craft-cli==2.5.1
craft-grammar==1.1.2
craft-parts==1.28.0
craft-providers==1.23.1
craft-store==2.6.0
cryptography==42.0.5
Deprecated==1.2.14
distro==1.9.0
exceptiongroup==1.2.2
execnet==2.1.1
flake8==7.0.0
freezegun==1.4.0
httplib2==0.22.0
humanize==4.9.0
hypothesis==6.99.6
idna==3.6
importlib_metadata==7.0.2
iniconfig==2.0.0
jaraco.classes==3.3.1
jeepney==0.8.0
Jinja2==3.1.3
jsonschema==4.21.1
jsonschema-specifications==2023.12.1
keyring==24.3.1
launchpadlib==1.11.0
lazr.restfulclient==0.14.6
lazr.uri==1.0.6
macaroonbakery==1.3.4
MarkupSafe==2.1.5
mccabe==0.7.0
more-itertools==10.2.0
oauthlib==3.2.2
overrides==7.7.0
packaging==24.0
platformdirs==4.2.0
pluggy==1.4.0
protobuf==3.20.3
pycodestyle==2.11.1
pycparser==2.21
pydantic==1.10.14
pydantic-yaml==0.11.2
pydocstyle==6.3.0
pyfakefs==5.3.5
pyflakes==3.2.0
pygit2==1.14.1
pymacaroons==0.13.0
PyNaCl==1.5.0
pyparsing==3.1.2
pyRFC3339==1.1
pytest==8.1.1
pytest-asyncio==0.26.0
pytest-check==2.3.1
pytest-cov==4.1.0
pytest-mock==3.12.0
pytest-subprocess==1.5.0
pytest-xdist==3.6.1
python-dateutil==2.9.0.post0
pytz==2024.1
pyxdg==0.28
PyYAML==6.0.1
referencing==0.33.0
requests==2.31.0
requests-toolbelt==1.0.0
requests-unixsocket==0.3.0
responses==0.25.0
rpds-py==0.18.0
SecretStorage==3.3.3
six==1.16.0
snap-helpers==0.4.2
snowballstemmer==2.2.0
sortedcontainers==2.4.0
tabulate==0.9.0
tomli==2.2.1
types-Deprecated==1.2.9.20240311
types-PyYAML==6.0.12.20240311
typing_extensions==4.10.0
urllib3==1.26.18
wadllib==1.3.6
wrapt==1.16.0
zipp==3.18.0
|
name: charmcraft
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- bzip2=1.0.8=h5eee18b_6
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- libuuid=1.41.5=h5eee18b_0
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py310h06a4308_0
- python=3.10.16=he870216_1
- readline=8.2=h5eee18b_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py310h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- attrs==23.2.0
- certifi==2024.2.2
- cffi==1.16.0
- charmcraft==3.0.0.post6+g0fbe2f80
- charset-normalizer==3.3.2
- coverage==7.4.4
- craft-application==2.0.0
- craft-archives==1.1.3
- craft-cli==2.5.1
- craft-grammar==1.1.2
- craft-parts==1.28.0
- craft-providers==1.23.1
- craft-store==2.6.0
- cryptography==42.0.5
- deprecated==1.2.14
- distro==1.9.0
- exceptiongroup==1.2.2
- execnet==2.1.1
- flake8==7.0.0
- freezegun==1.4.0
- httplib2==0.22.0
- humanize==4.9.0
- hypothesis==6.99.6
- idna==3.6
- importlib-metadata==7.0.2
- iniconfig==2.0.0
- jaraco-classes==3.3.1
- jeepney==0.8.0
- jinja2==3.1.3
- jsonschema==4.21.1
- jsonschema-specifications==2023.12.1
- keyring==24.3.1
- launchpadlib==1.11.0
- lazr-restfulclient==0.14.6
- lazr-uri==1.0.6
- macaroonbakery==1.3.4
- markupsafe==2.1.5
- mccabe==0.7.0
- more-itertools==10.2.0
- oauthlib==3.2.2
- overrides==7.7.0
- packaging==24.0
- platformdirs==4.2.0
- pluggy==1.4.0
- protobuf==3.20.3
- pycodestyle==2.11.1
- pycparser==2.21
- pydantic==1.10.14
- pydantic-yaml==0.11.2
- pydocstyle==6.3.0
- pyfakefs==5.3.5
- pyflakes==3.2.0
- pygit2==1.14.1
- pymacaroons==0.13.0
- pynacl==1.5.0
- pyparsing==3.1.2
- pyrfc3339==1.1
- pytest==8.1.1
- pytest-asyncio==0.26.0
- pytest-check==2.3.1
- pytest-cov==4.1.0
- pytest-mock==3.12.0
- pytest-subprocess==1.5.0
- pytest-xdist==3.6.1
- python-dateutil==2.9.0.post0
- pytz==2024.1
- pyxdg==0.28
- pyyaml==6.0.1
- referencing==0.33.0
- requests==2.31.0
- requests-toolbelt==1.0.0
- requests-unixsocket==0.3.0
- responses==0.25.0
- rpds-py==0.18.0
- secretstorage==3.3.3
- setuptools==69.2.0
- six==1.16.0
- snap-helpers==0.4.2
- snowballstemmer==2.2.0
- sortedcontainers==2.4.0
- tabulate==0.9.0
- tomli==2.2.1
- types-deprecated==1.2.9.20240311
- types-pyyaml==6.0.12.20240311
- typing-extensions==4.10.0
- urllib3==1.26.18
- wadllib==1.3.6
- wrapt==1.16.0
- zipp==3.18.0
prefix: /opt/conda/envs/charmcraft
|
[
"tests/unit/test_preprocess.py::test_add_config_success[yaml_data0-{}-expected0]",
"tests/unit/test_preprocess.py::test_add_config_success[yaml_data1-options:\\n",
"tests/unit/test_preprocess.py::test_add_actions_success[yaml_data0--expected0]",
"tests/unit/test_preprocess.py::test_add_actions_success[yaml_data1-{}-expected1]",
"tests/unit/test_preprocess.py::test_add_actions_success[yaml_data2-boop:\\n"
] |
[] |
[
"tests/unit/test_preprocess.py::test_add_default_parts_correct[no-type]",
"tests/unit/test_preprocess.py::test_add_default_parts_correct[empty-bundle]",
"tests/unit/test_preprocess.py::test_add_default_parts_correct[prefilled-bundle]",
"tests/unit/test_preprocess.py::test_add_metadata_success[nonexistent]",
"tests/unit/test_preprocess.py::test_add_metadata_success[empty]",
"tests/unit/test_preprocess.py::test_add_metadata_success[merge]",
"tests/unit/test_preprocess.py::test_add_metadata_success[only-from-metadata]",
"tests/unit/test_preprocess.py::test_extra_yaml_transform_failure[yaml_data0--Invalid",
"tests/unit/test_preprocess.py::test_extra_yaml_transform_failure[yaml_data1-name:",
"tests/unit/test_preprocess.py::test_add_bundle_snippet_success[non-bundle]",
"tests/unit/test_preprocess.py::test_add_bundle_snippet_success[empty-bundle]",
"tests/unit/test_preprocess.py::test_add_bundle_snippet_no_file",
"tests/unit/test_preprocess.py::test_add_bundle_snippet_invalid_file[]",
"tests/unit/test_preprocess.py::test_add_bundle_snippet_invalid_file[A",
"tests/unit/test_preprocess.py::test_add_bundle_snippet_invalid_file[0]",
"tests/unit/test_preprocess.py::test_add_bundle_snippet_invalid_file[[]]"
] |
[] |
Apache License 2.0
| 18,011
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.canonical_1776_charmcraft-1615:latest
|
LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/integration/test_application.py tests/unit/test_preprocess.py
|
#!/bin/bash
set -uxo pipefail
source /opt/miniconda3/bin/activate
conda activate testbed
cd /testbed
git config --global --add safe.directory /testbed
cd /testbed
git status
git show
git -c core.fileMode=false diff 0fbe2f8085de31b3997be4877f733f70f650b15e
source /opt/miniconda3/bin/activate
conda activate testbed
LANG=C.UTF-8 LC_ALL=C.UTF-8 pip install -r requirements-dev.txt -e .
git checkout 0fbe2f8085de31b3997be4877f733f70f650b15e tests/unit/test_preprocess.py
git apply -v - <<'EOF_114329324912'
diff --git a/tests/integration/sample-charms/actions-included/charmcraft.yaml b/tests/integration/sample-charms/actions-included/charmcraft.yaml
new file mode 100644
index 00000000..23239d7b
--- /dev/null
+++ b/tests/integration/sample-charms/actions-included/charmcraft.yaml
@@ -0,0 +1,38 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
+
+actions:
+ pause:
+ description: Pause the database.
+ resume:
+ description: Resume a paused database.
+ snapshot:
+ description: Take a snapshot of the database.
+ params:
+ filename:
+ type: string
+ description: The name of the snapshot file.
+ compression:
+ type: object
+ description: The type of compression to use.
+ properties:
+ kind:
+ type: string
+ enum: [gzip, bzip2, xz]
+ quality:
+ description: Compression quality
+ type: integer
+ minimum: 0
+ maximum: 9
+ required: [filename]
+ additionalProperties: false
diff --git a/tests/integration/sample-charms/actions-included/expected.yaml b/tests/integration/sample-charms/actions-included/expected.yaml
new file mode 100644
index 00000000..074bf477
--- /dev/null
+++ b/tests/integration/sample-charms/actions-included/expected.yaml
@@ -0,0 +1,46 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+actions:
+ pause:
+ description: Pause the database.
+ resume:
+ description: Resume a paused database.
+ snapshot:
+ description: Take a snapshot of the database.
+ params:
+ filename:
+ type: string
+ description: The name of the snapshot file.
+ compression:
+ type: object
+ description: The type of compression to use.
+ properties:
+ kind:
+ type: string
+ enum:
+ - gzip
+ - bzip2
+ - xz
+ quality:
+ description: Compression quality
+ type: integer
+ minimum: 0
+ maximum: 9
+ required:
+ - filename
+ additionalProperties: false
diff --git a/tests/integration/sample-charms/actions-separate/actions.yaml b/tests/integration/sample-charms/actions-separate/actions.yaml
new file mode 100644
index 00000000..b155d4b8
--- /dev/null
+++ b/tests/integration/sample-charms/actions-separate/actions.yaml
@@ -0,0 +1,24 @@
+pause:
+ description: Pause the database.
+resume:
+ description: Resume a paused database.
+snapshot:
+ description: Take a snapshot of the database.
+ params:
+ filename:
+ type: string
+ description: The name of the snapshot file.
+ compression:
+ type: object
+ description: The type of compression to use.
+ properties:
+ kind:
+ type: string
+ enum: [gzip, bzip2, xz]
+ quality:
+ description: Compression quality
+ type: integer
+ minimum: 0
+ maximum: 9
+ required: [filename]
+ additionalProperties: false
diff --git a/tests/integration/sample-charms/actions-separate/charmcraft.yaml b/tests/integration/sample-charms/actions-separate/charmcraft.yaml
new file mode 100644
index 00000000..d681da9a
--- /dev/null
+++ b/tests/integration/sample-charms/actions-separate/charmcraft.yaml
@@ -0,0 +1,12 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
diff --git a/tests/integration/sample-charms/actions-separate/expected.yaml b/tests/integration/sample-charms/actions-separate/expected.yaml
new file mode 100644
index 00000000..074bf477
--- /dev/null
+++ b/tests/integration/sample-charms/actions-separate/expected.yaml
@@ -0,0 +1,46 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+actions:
+ pause:
+ description: Pause the database.
+ resume:
+ description: Resume a paused database.
+ snapshot:
+ description: Take a snapshot of the database.
+ params:
+ filename:
+ type: string
+ description: The name of the snapshot file.
+ compression:
+ type: object
+ description: The type of compression to use.
+ properties:
+ kind:
+ type: string
+ enum:
+ - gzip
+ - bzip2
+ - xz
+ quality:
+ description: Compression quality
+ type: integer
+ minimum: 0
+ maximum: 9
+ required:
+ - filename
+ additionalProperties: false
diff --git a/tests/integration/sample-charms/basic-bases/charmcraft.yaml b/tests/integration/sample-charms/basic-bases/charmcraft.yaml
new file mode 100644
index 00000000..3e078462
--- /dev/null
+++ b/tests/integration/sample-charms/basic-bases/charmcraft.yaml
@@ -0,0 +1,12 @@
+name: example-charm
+summary: An example charm with bases
+description: |
+ A description for an example charm with bases.
+type: charm
+bases:
+ - name: ubuntu
+ channel: "22.04"
+
+parts:
+ charm:
+ plugin: charm
diff --git a/tests/integration/sample-charms/basic-bases/expected.yaml b/tests/integration/sample-charms/basic-bases/expected.yaml
new file mode 100644
index 00000000..a7f02d3d
--- /dev/null
+++ b/tests/integration/sample-charms/basic-bases/expected.yaml
@@ -0,0 +1,21 @@
+name: example-charm
+summary: An example charm with bases
+description: |
+ A description for an example charm with bases.
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+bases:
+- build-on:
+ - name: ubuntu
+ channel: '22.04'
+ run-on:
+ - name: ubuntu
+ channel: '22.04'
diff --git a/tests/integration/sample-charms/basic-platforms/charmcraft.yaml b/tests/integration/sample-charms/basic-platforms/charmcraft.yaml
new file mode 100644
index 00000000..d681da9a
--- /dev/null
+++ b/tests/integration/sample-charms/basic-platforms/charmcraft.yaml
@@ -0,0 +1,12 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
diff --git a/tests/integration/sample-charms/basic-platforms/expected.yaml b/tests/integration/sample-charms/basic-platforms/expected.yaml
new file mode 100644
index 00000000..95213900
--- /dev/null
+++ b/tests/integration/sample-charms/basic-platforms/expected.yaml
@@ -0,0 +1,17 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
diff --git a/tests/integration/sample-charms/config-included/charmcraft.yaml b/tests/integration/sample-charms/config-included/charmcraft.yaml
new file mode 100644
index 00000000..44a0837a
--- /dev/null
+++ b/tests/integration/sample-charms/config-included/charmcraft.yaml
@@ -0,0 +1,33 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
+
+config:
+ options:
+ admins:
+ description: 'Comma-separated list of admin users to create: user:pass[,user:pass]+'
+ type: string
+ debug:
+ default: false
+ description: turn on debugging features of mediawiki
+ type: boolean
+ logo:
+ description: URL to fetch logo from
+ type: string
+ name:
+ default: Wiki
+ description: The name, or Title of the Wiki
+ type: string
+ skin:
+ default: vector
+ description: skin for the Wiki
+ type: string
diff --git a/tests/integration/sample-charms/config-included/expected.yaml b/tests/integration/sample-charms/config-included/expected.yaml
new file mode 100644
index 00000000..ac875e8e
--- /dev/null
+++ b/tests/integration/sample-charms/config-included/expected.yaml
@@ -0,0 +1,37 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+config:
+ options:
+ admins:
+ description: 'Comma-separated list of admin users to create: user:pass[,user:pass]+'
+ type: string
+ debug:
+ default: false
+ description: turn on debugging features of mediawiki
+ type: boolean
+ logo:
+ description: URL to fetch logo from
+ type: string
+ name:
+ default: Wiki
+ description: The name, or Title of the Wiki
+ type: string
+ skin:
+ default: vector
+ description: skin for the Wiki
+ type: string
diff --git a/tests/integration/sample-charms/config-separate/charmcraft.yaml b/tests/integration/sample-charms/config-separate/charmcraft.yaml
new file mode 100644
index 00000000..d681da9a
--- /dev/null
+++ b/tests/integration/sample-charms/config-separate/charmcraft.yaml
@@ -0,0 +1,12 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+type: charm
+base: [email protected]
+platforms:
+ amd64:
+
+parts:
+ charm:
+ plugin: charm
diff --git a/tests/integration/sample-charms/config-separate/config.yaml b/tests/integration/sample-charms/config-separate/config.yaml
new file mode 100644
index 00000000..4700abb9
--- /dev/null
+++ b/tests/integration/sample-charms/config-separate/config.yaml
@@ -0,0 +1,19 @@
+options:
+ admins:
+ description: 'Comma-separated list of admin users to create: user:pass[,user:pass]+'
+ type: string
+ debug:
+ default: false
+ description: turn on debugging features of mediawiki
+ type: boolean
+ logo:
+ description: URL to fetch logo from
+ type: string
+ name:
+ default: Wiki
+ description: The name, or Title of the Wiki
+ type: string
+ skin:
+ default: vector
+ description: skin for the Wiki
+ type: string
diff --git a/tests/integration/sample-charms/config-separate/expected.yaml b/tests/integration/sample-charms/config-separate/expected.yaml
new file mode 100644
index 00000000..ac875e8e
--- /dev/null
+++ b/tests/integration/sample-charms/config-separate/expected.yaml
@@ -0,0 +1,37 @@
+name: example-charm
+summary: An example charm with platforms
+description: |
+ A description for an example charm with platforms.
+base: [email protected]
+platforms:
+ amd64: null
+parts:
+ charm:
+ source: .
+ charm-entrypoint: src/charm.py
+ charm-binary-python-packages: []
+ charm-python-packages: []
+ charm-requirements: []
+ charm-strict-dependencies: false
+ plugin: charm
+type: charm
+config:
+ options:
+ admins:
+ description: 'Comma-separated list of admin users to create: user:pass[,user:pass]+'
+ type: string
+ debug:
+ default: false
+ description: turn on debugging features of mediawiki
+ type: boolean
+ logo:
+ description: URL to fetch logo from
+ type: string
+ name:
+ default: Wiki
+ description: The name, or Title of the Wiki
+ type: string
+ skin:
+ default: vector
+ description: skin for the Wiki
+ type: string
diff --git a/tests/integration/test_application.py b/tests/integration/test_application.py
new file mode 100644
index 00000000..d8fe7aea
--- /dev/null
+++ b/tests/integration/test_application.py
@@ -0,0 +1,37 @@
+# Copyright 2024 Canonical Ltd.
+#
+# 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.
+#
+# For further info, check https://github.com/canonical/charmcraft
+"""Integration tests for the Charmcraft class."""
+import pathlib
+
+import pytest
+from craft_application import util
+
+from charmcraft import models
+
+
[email protected](
+ "charm_dir", sorted((pathlib.Path(__file__).parent / "sample-charms").iterdir())
+)
+def test_load_charm(app, charm_dir):
+ app.project_dir = charm_dir
+
+ project = app.get_project()
+ with (charm_dir / "expected.yaml").open() as f:
+ expected_data = util.safe_yaml_load(f)
+ expected_project = models.CharmcraftProject.unmarshal(expected_data)
+
+ assert project == expected_project
+ assert util.dump_yaml(project.marshal()) == (charm_dir / "expected.yaml").read_text()
diff --git a/tests/unit/test_preprocess.py b/tests/unit/test_preprocess.py
index 8bc4618a..c7fb429f 100644
--- a/tests/unit/test_preprocess.py
+++ b/tests/unit/test_preprocess.py
@@ -142,3 +142,40 @@ def test_add_bundle_snippet_invalid_file(fs, contents):
preprocess.add_bundle_snippet(pathlib.Path("project"), {"type": "bundle"})
assert exc_info.value.retcode == 65
+
+
[email protected](
+ ("yaml_data", "config_yaml", "expected"),
+ [
+ ({}, "{}", {"config": {}}),
+ ({}, "options:\n boop:\n type: int", {"config": {"options": {"boop": {"type": "int"}}}}),
+ ],
+)
+def test_add_config_success(fs, yaml_data, config_yaml, expected):
+ project_dir = pathlib.Path("project")
+ fs.create_file(project_dir / const.JUJU_CONFIG_FILENAME, contents=config_yaml)
+
+ preprocess.add_config(project_dir, yaml_data)
+
+ assert yaml_data == expected
+
+
[email protected](
+ ("yaml_data", "actions_yaml", "expected"),
+ [
+ ({}, "", {}),
+ ({}, "{}", {}),
+ (
+ {},
+ "boop:\n description: Boop in the snoot",
+ {"actions": {"boop": {"description": "Boop in the snoot"}}},
+ ),
+ ],
+)
+def test_add_actions_success(fs, yaml_data, actions_yaml, expected):
+ project_dir = pathlib.Path("project")
+ fs.create_file(project_dir / const.JUJU_ACTIONS_FILENAME, contents=actions_yaml)
+
+ preprocess.add_actions(project_dir, yaml_data)
+
+ assert yaml_data == expected
EOF_114329324912
: '>>>>> Start Test Output'
LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/integration/test_application.py tests/unit/test_preprocess.py
: '>>>>> End Test Output'
git checkout 0fbe2f8085de31b3997be4877f733f70f650b15e tests/unit/test_preprocess.py
|
JonathonReinhart__scuba-250
|
b4bfd81ff1b939079d24aa8d4cd62fccc2e6ad9a
|
2024-03-22 05:45:05
|
b4bfd81ff1b939079d24aa8d4cd62fccc2e6ad9a
|
diff --git a/docs/configuration.rst b/docs/configuration.rst
index 841626a..4569a86 100644
--- a/docs/configuration.rst
+++ b/docs/configuration.rst
@@ -147,25 +147,40 @@ style <https://yaml.org/spec/1.2/spec.html#id2788097>`_:
The optional ``volumes`` node *(added in v2.9.0)* allows additional
`bind-mounts <https://docs.docker.com/storage/bind-mounts/>`_ to be specified.
+As of v2.13.0, `named volumes <https://docs.docker.com/storage/volumes/>`_
+are also supported.
+
``volumes`` is a mapping (dictionary) where each key is the container-path.
-In the simple form, the value is a string, the host-path to be bind-mounted:
+In the simple form, the value is a string, which can be:
+
+* An absolute or relative path which results in a bind-mount.
+* A Docker volume name.
.. code-block:: yaml
+ :caption: Example of simple-form volumes
volumes:
- /var/lib/foo: /host/foo
- /var/lib/bar: ./bar
+ /var/lib/foo: /host/foo # bind-mount: absolute path
+ /var/lib/bar: ./bar # bind-mount: path relative to .scuba.yml dir
+ /var/log: persist-logs # named volume
+
+In the complex form, the value is a mapping with the following supported keys:
+
+* ``hostpath``: An absolute or relative path specifying a host bind-mount.
+* ``name``: The name of a named Docker volume.
+* ``options``: A comma-separated list of volume options.
-In the complex form, the value is a mapping which must contain a ``hostpath``
-subkey. It can also contain an ``options`` subkey with a comma-separated list
-of volume options:
+``hostpath`` and ``name`` are mutually-exclusive and one must be specified.
.. code-block:: yaml
+ :caption: Example of complex-form volumes
volumes:
/var/lib/foo:
- hostpath: /host/foo
+ hostpath: /host/foo # bind-mount
options: ro,cached
+ /var/log:
+ name: persist-logs # named volume
The paths (host or container) used in volume mappings can contain environment
variables **which are expanded in the host environment**. For example, this
@@ -182,18 +197,32 @@ configuration error.
Volume container paths must be absolute.
-Volume host paths can be absolute or relative. If a relative path is used, it
-is interpreted as relative to the directory in which ``.scuba.yml`` is found.
-To avoid ambiguity, relative paths must start with ``./`` or ``../``.
+Bind-mount host paths can be absolute or relative. If a relative path is used,
+it is interpreted as relative to the directory in which ``.scuba.yml`` is
+found. To avoid ambiguity with a named volume, relative paths must start with
+``./`` or ``../``.
-Volume host directories which do not already exist are created as the current
-user before creating the container.
+Bind-mount host directories which do not already exist are created as the
+current user before creating the container.
.. note::
Because variable expansion is now applied to all volume paths, if one
desires to use a literal ``$`` character in a path, it must be written as
``$$``.
+.. note::
+ Docker named volumes are created with ``drwxr-xr-x`` (0755) permissions.
+ If scuba is not run with ``--root``, the scuba user will be unable to write
+ to this directory. As a workaround, one can use a :ref:`root hook
+ <conf_hooks>` to change permissions on the directory.
+
+ .. code-block:: yaml
+
+ volumes:
+ /foo: foo-volume
+ hooks:
+ root: chmod 777 /foo
+
.. _conf_aliases:
diff --git a/scuba/config.py b/scuba/config.py
index 4e1ecb4..ba4a507 100644
--- a/scuba/config.py
+++ b/scuba/config.py
@@ -11,7 +11,7 @@ import yaml
import yaml.nodes
from .constants import DEFAULT_SHELL, SCUBA_YML
-from .utils import expand_env_vars, parse_env_var
+from . import utils
from .dockerutil import make_vol_opt
CfgNode = Any
@@ -19,6 +19,8 @@ CfgData = Dict[str, CfgNode]
Environment = Dict[str, str]
_T = TypeVar("_T")
+VOLUME_NAME_PATTERN = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]+$")
+
class ConfigError(Exception):
pass
@@ -190,6 +192,32 @@ def find_config() -> Tuple[Path, Path, ScubaConfig]:
)
+def _expand_env_vars(in_str: str) -> str:
+ """Wraps utils.expand_env_vars() to convert errors
+
+ Args:
+ in_str: Input string.
+
+ Returns:
+ The input string with environment variables expanded.
+
+ Raises:
+ ConfigError: If a referenced environment variable is not set.
+ ConfigError: An environment variable reference could not be parsed.
+ """
+ try:
+ return utils.expand_env_vars(in_str)
+ except KeyError as err:
+ # pylint: disable=raise-missing-from
+ raise ConfigError(
+ f"Unset environment variable {err.args[0]!r} used in {in_str!r}"
+ )
+ except ValueError as ve:
+ raise ConfigError(
+ f"Unable to expand string '{in_str}' due to parsing errors"
+ ) from ve
+
+
def _process_script_node(node: CfgNode, name: str) -> List[str]:
"""Process a script-type node
@@ -236,7 +264,7 @@ def _process_environment(node: CfgNode, name: str) -> Environment:
result[k] = str(v)
elif isinstance(node, list):
for e in node:
- k, v = parse_env_var(e)
+ k, v = utils.parse_env_var(e)
result[k] = v
else:
raise ConfigError(
@@ -332,18 +360,16 @@ def _get_volumes(
vols = {}
for cpath_str, v in voldata.items():
- cpath = _expand_path(cpath_str) # no base_dir; container path must be absolute.
+ cpath_str = _expand_env_vars(cpath_str)
+ cpath = _absoluteify_path(cpath_str) # container path must be absolute.
vols[cpath] = ScubaVolume.from_dict(cpath, v, scuba_root)
return vols
-def _expand_path(in_str: str, base_dir: Optional[Path] = None) -> Path:
- """Expand variables in a path string and make it absolute.
-
- Environment variable references (e.g. $FOO and ${FOO}) are expanded using
- the host environment.
+def _absoluteify_path(in_str: str, base_dir: Optional[Path] = None) -> Path:
+ """Take a path string and make it absolute.
- After environment variable expansion, absolute paths are returned as-is.
+ Absolute paths are returned as-is.
Relative paths must start with ./ or ../ and are joined to base_dir, if
provided.
@@ -356,26 +382,13 @@ def _expand_path(in_str: str, base_dir: Optional[Path] = None) -> Path:
Raises:
ValueError: If base_dir is provided but not absolute.
- ConfigError: If a referenced environment variable is not set.
- ConfigError: An environment variable reference could not be parsed.
ConfigError: A relative path does not start with "./" or "../".
ConfigError: A relative path is given when base_dir is not provided.
"""
if base_dir is not None and not base_dir.is_absolute():
raise ValueError(f"base_dir is not absolute: {base_dir}")
- try:
- path_str = expand_env_vars(in_str)
- except KeyError as ke:
- # pylint: disable=raise-missing-from
- raise ConfigError(
- f"Unset environment variable {ke.args[0]!r} used in {in_str!r}"
- )
- except ValueError as ve:
- raise ConfigError(
- f"Unable to expand string '{in_str}' due to parsing errors"
- ) from ve
-
+ path_str = _expand_env_vars(in_str)
path = Path(path_str)
if not path.is_absolute():
@@ -399,9 +412,14 @@ def _expand_path(in_str: str, base_dir: Optional[Path] = None) -> Path:
@dataclasses.dataclass(frozen=True)
class ScubaVolume:
container_path: Path
- host_path: Path # TODO: Optional for anonymous volume
+ host_path: Optional[Path] = None
+ volume_name: Optional[str] = None
options: List[str] = dataclasses.field(default_factory=list)
+ def __post_init__(self) -> None:
+ if sum(bool(x) for x in (self.host_path, self.volume_name)) != 1:
+ raise ValueError("Exactly one of host_path, volume_name must be set")
+
@classmethod
def from_dict(
cls, cpath: Path, node: CfgNode, scuba_root: Optional[Path]
@@ -412,11 +430,26 @@ class ScubaVolume:
# Simple form:
# volumes:
- # /foo: /host/foo
+ # /foo: foo-volume # volume name
+ # /bar: /host/bar # absolute path
+ # /snap: ./snap # relative path
if isinstance(node, str):
+ node = _expand_env_vars(node)
+
+ # Absolute or relative path
+ valid_prefixes = ("/", "./", "../")
+ if any(node.startswith(pfx) for pfx in valid_prefixes):
+ return cls(
+ container_path=cpath,
+ host_path=_absoluteify_path(node, scuba_root),
+ )
+
+ # Volume name
+ if not VOLUME_NAME_PATTERN.match(node):
+ raise ConfigError(f"Invalid volume name: {node!r}")
return cls(
container_path=cpath,
- host_path=_expand_path(node, scuba_root),
+ volume_name=node,
)
# Complex form
@@ -424,20 +457,42 @@ class ScubaVolume:
# /foo:
# hostpath: /host/foo
# options: ro,z
+ # /bar:
+ # name: bar-volume
if isinstance(node, dict):
hpath = node.get("hostpath")
- if hpath is None:
- raise ConfigError(f"Volume {cpath} must have a 'hostpath' subkey")
- return cls(
- container_path=cpath,
- host_path=_expand_path(hpath, scuba_root),
- options=_get_delimited_str_list(node, "options", ","),
- )
+ name = node.get("name")
+ options = _get_delimited_str_list(node, "options", ",")
+
+ if sum(bool(x) for x in (hpath, name)) != 1:
+ raise ConfigError(
+ f"Volume {cpath} must have exactly one of"
+ " 'hostpath' or 'name' subkey"
+ )
+
+ if hpath is not None:
+ hpath = _expand_env_vars(hpath)
+ return cls(
+ container_path=cpath,
+ host_path=_absoluteify_path(hpath, scuba_root),
+ options=options,
+ )
+
+ if name is not None:
+ return cls(
+ container_path=cpath,
+ volume_name=_expand_env_vars(name),
+ options=options,
+ )
raise ConfigError(f"{cpath}: must be string or dict")
def get_vol_opt(self) -> str:
- return make_vol_opt(self.host_path, self.container_path, self.options)
+ if self.host_path:
+ return make_vol_opt(self.host_path, self.container_path, self.options)
+ if self.volume_name:
+ return make_vol_opt(self.volume_name, self.container_path, self.options)
+ raise Exception("host_path or volume_name must be set")
@dataclasses.dataclass(frozen=True)
diff --git a/scuba/dockerutil.py b/scuba/dockerutil.py
index a2b1ac4..6ecd30d 100644
--- a/scuba/dockerutil.py
+++ b/scuba/dockerutil.py
@@ -132,17 +132,22 @@ def get_image_entrypoint(image: str) -> Optional[Sequence[str]]:
def make_vol_opt(
- hostdir: Path,
+ hostdir_or_volname: Union[Path, str],
contdir: Path,
options: Optional[Sequence[str]] = None,
) -> str:
"""Generate a docker volume option"""
- if not hostdir.is_absolute():
- raise ValueError(f"hostdir not absolute: {hostdir}")
+ if isinstance(hostdir_or_volname, Path):
+ hostdir: Path = hostdir_or_volname
+ if not hostdir.is_absolute():
+ # NOTE: As of Docker Engine version 23, you can use relative paths
+ # on the host. But we have no minimum Docker version, so we don't
+ # rely on this.
+ raise ValueError(f"hostdir not absolute: {hostdir}")
if not contdir.is_absolute():
raise ValueError(f"contdir not absolute: {contdir}")
- vol = f"--volume={hostdir}:{contdir}"
+ vol = f"--volume={hostdir_or_volname}:{contdir}"
if options:
assert not isinstance(options, str)
vol += ":" + ",".join(options)
diff --git a/scuba/scuba.py b/scuba/scuba.py
index 0642388..6b14961 100644
--- a/scuba/scuba.py
+++ b/scuba/scuba.py
@@ -165,7 +165,7 @@ class ScubaDive:
return
for vol in self.context.volumes.values():
- if vol.host_path.exists():
+ if vol.host_path is None or vol.host_path.exists():
continue
try:
|
Restore ability to use named volumes
Prior to #227, you could, as a not-officially-support feature map a named volume at a container path:
```yaml
volumes:
/foo: foo-volume
```
```console
$ scuba --root --image debian:8.2 /bin/bash -c "echo yes > /foo/does-it-persist"
$ scuba --root --image debian:8.2 /bin/bash -c "cat /foo/does-it-persist"
yes
$ docker volume ls
DRIVER VOLUME NAME
local foo-volume
```
Since #227, this no longer works.
```
scuba: Config error: Relative path must start with ./ or ../: foo-volume
```
*Reported https://github.com/JonathonReinhart/scuba/pull/227#issuecomment-2005067223 by @haboustak.*
|
JonathonReinhart/scuba
|
diff --git a/tests/test_config.py b/tests/test_config.py
index d07b481..65aa924 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -10,6 +10,7 @@ from unittest import mock
from .utils import assert_paths_equal, assert_vol
import scuba.config
+from scuba.config import ScubaVolume
def load_config() -> scuba.config.ScubaConfig:
@@ -878,7 +879,7 @@ class TestConfig:
self._invalid_config("hostpath")
- def test_volumes_simple_volume(self) -> None:
+ def test_volumes_simple_bind(self) -> None:
"""volumes can be set using the simple form"""
with open(".scuba.yml", "w") as f:
f.write(
@@ -895,7 +896,7 @@ class TestConfig:
assert_vol(config.volumes, "/cpath", "/hpath")
- def test_volumes_complex(self) -> None:
+ def test_volumes_complex_bind(self) -> None:
"""volumes can be set using the complex form"""
with open(".scuba.yml", "w") as f:
f.write(
@@ -920,6 +921,27 @@ class TestConfig:
assert_vol(vols, "/bar", "/host/bar")
assert_vol(vols, "/snap", "/host/snap", ["z", "ro"])
+ def test_volumes_complex_named_volume(self) -> None:
+ """volumes complex form can specify a named volume"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ name: foo-volume
+ """
+ )
+
+ config = load_config()
+ assert config.volumes is not None
+ assert len(config.volumes) == 1
+ vol = config.volumes[Path("/foo")]
+
+ assert isinstance(vol, ScubaVolume)
+ assert_paths_equal(vol.container_path, "/foo")
+ assert vol.volume_name == "foo-volume"
+
def test_alias_volumes_set(self) -> None:
"""docker_args can be set via alias"""
with open(".scuba.yml", "w") as f:
@@ -1076,20 +1098,6 @@ class TestConfig:
assert config.volumes is not None
assert_vol(config.volumes, "/foo", in_tmp_path / "foo_up_here")
- def test_volumes_hostpath_rel_req_dot_simple(
- self, monkeypatch, in_tmp_path
- ) -> None:
- """relaitve volume hostpath (simple form) must start with ./ or ../"""
- with open(".scuba.yml", "w") as f:
- f.write(
- r"""
- image: na
- volumes:
- /one: foo # Forbidden
- """
- )
- self._invalid_config("Relative path must start with ./ or ../")
-
def test_volumes_hostpath_rel_requires_dot_complex(
self, monkeypatch, in_tmp_path
) -> None:
@@ -1134,3 +1142,124 @@ class TestConfig:
"""
)
self._invalid_config("Relative path not allowed: foo")
+
+ def test_volumes_simple_named_volume(self) -> None:
+ """volumes simple form can specify a named volume"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo: foo-volume
+ """
+ )
+
+ config = load_config()
+ assert config.volumes is not None
+ assert len(config.volumes) == 1
+ vol = config.volumes[Path("/foo")]
+
+ assert isinstance(vol, ScubaVolume)
+ assert_paths_equal(vol.container_path, "/foo")
+ assert vol.volume_name == "foo-volume"
+
+ def test_volumes_simple_named_volume_env(self, monkeypatch) -> None:
+ """volumes simple form can specify a named volume via env var"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo: $FOO_VOLUME
+ """
+ )
+
+ monkeypatch.setenv("FOO_VOLUME", "foo-volume")
+
+ config = load_config()
+ assert config.volumes is not None
+ assert len(config.volumes) == 1
+ vol = config.volumes[Path("/foo")]
+
+ assert isinstance(vol, ScubaVolume)
+ assert_paths_equal(vol.container_path, "/foo")
+ assert vol.volume_name == "foo-volume"
+
+ def test_volumes_complex_named_volume_env(self, monkeypatch) -> None:
+ """volumes complex form can specify a named volume via env var"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ name: $FOO_VOLUME
+ """
+ )
+
+ monkeypatch.setenv("FOO_VOLUME", "foo-volume")
+
+ config = load_config()
+ assert config.volumes is not None
+ assert len(config.volumes) == 1
+ vol = config.volumes[Path("/foo")]
+
+ assert isinstance(vol, ScubaVolume)
+ assert_paths_equal(vol.container_path, "/foo")
+ assert vol.volume_name == "foo-volume"
+
+ def test_volumes_complex_named_volume_env_unset(self) -> None:
+ """volumes complex form fails on unset env var"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ name: $FOO_VOLUME
+ """
+ )
+ self._invalid_config("Unset environment variable")
+
+ def test_volumes_complex_invalid_hostpath(self) -> None:
+ """volumes complex form cannot specify an invalid hostpath"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ hostpath: foo-volume
+ """
+ )
+ self._invalid_config("Relative path must start with ./ or ../")
+
+ def test_volumes_complex_hostpath_and_name(self) -> None:
+ """volumes complex form cannot specify a named volume and hostpath"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ hostpath: /bar
+ name: foo-volume
+ """
+ )
+ self._invalid_config(
+ "Volume /foo must have exactly one of 'hostpath' or 'name' subkey"
+ )
+
+ def test_volumes_complex_empty(self) -> None:
+ """volumes complex form cannot be empty"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ """
+ )
+ self._invalid_config(
+ "Volume /foo must have exactly one of 'hostpath' or 'name' subkey"
+ )
diff --git a/tests/test_main.py b/tests/test_main.py
index 5e77b32..7b242fb 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -29,7 +29,7 @@ SCUBAINIT_EXIT_FAIL = 99
@pytest.mark.usefixtures("in_tmp_path")
-class TestMain:
+class TestMainBase:
def run_scuba(self, args, exp_retval=0, mock_isatty=False, stdin=None):
"""Run scuba, checking its return value
@@ -87,6 +87,8 @@ class TestMain:
sys.stdout = old_stdout
sys.stderr = old_stderr
+
+class TestMain(TestMainBase):
def test_basic(self) -> None:
"""Verify basic scuba functionality"""
@@ -1133,3 +1135,47 @@ class TestMain:
out, _ = self.run_scuba(["cat", "/userdir/test.txt"])
assert out == test_message
+
+
+class TestMainNamedVolumes(TestMainBase):
+ VOLUME_NAME = "foo-volume"
+
+ def _rm_volume(self) -> None:
+ result = subprocess.run(
+ ["docker", "volume", "rm", self.VOLUME_NAME],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode == 1 and re.match(r".*no such volume.*", result.stderr):
+ return
+ result.check_returncode()
+
+ def setup_method(self, method) -> None:
+ self._rm_volume()
+
+ def teardown_method(self, method) -> None:
+ self._rm_volume()
+
+ def test_volumes_named(self) -> None:
+ """Verify named volumes can be used"""
+ VOL_PATH = Path("/foo")
+ TEST_PATH = VOL_PATH / "test.txt"
+ TEST_STR = "it works!"
+
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ f"""
+ image: {DOCKER_IMAGE}
+ hooks:
+ root: chmod 777 {VOL_PATH}
+ volumes:
+ {VOL_PATH}: {self.VOLUME_NAME}
+ """
+ )
+
+ # Inoke scuba once: Write a file to the named volume
+ self.run_scuba(["/bin/sh", "-c", f"echo {TEST_STR} > {TEST_PATH}"])
+
+ # Invoke scuba again: Verify the file is still there
+ out, _ = self.run_scuba(["/bin/sh", "-c", f"cat {TEST_PATH}"])
+ assert_str_equalish(out, TEST_STR)
diff --git a/tests/utils.py b/tests/utils.py
index efe7036..8e78fea 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -48,6 +48,8 @@ def assert_vol(
v = vols[cpath]
assert isinstance(v, ScubaVolume)
assert_paths_equal(v.container_path, cpath)
+ assert v.volume_name is None
+ assert v.host_path is not None
assert_paths_equal(v.host_path, hpath)
assert v.options == options
|
{
"commit_name": "head_commit",
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false,
"llm_score": {
"difficulty_score": 2,
"issue_text_score": 0,
"test_score": 2
},
"num_modified_files": 4
}
|
2.12
|
{
"env_vars": null,
"env_yml_path": null,
"install": "pip install -e .[argcomplete]",
"log_parser": "parse_log_pytest",
"no_use_env": null,
"packages": "requirements.txt",
"pip_packages": [
"pytest"
],
"pre_install": [
"apt-get update",
"apt-get install -y gcc"
],
"python": "3.9",
"reqs_path": [
"requirements.txt"
],
"test_cmd": "pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning"
}
|
alabaster==0.7.16
argcomplete==3.6.1
babel==2.17.0
black==23.12.1
build==1.2.2.post1
certifi==2025.1.31
charset-normalizer==3.4.1
click==8.1.8
coverage==7.8.0
docutils==0.21.2
exceptiongroup==1.2.2
idna==3.10
imagesize==1.4.1
importlib_metadata==8.6.1
iniconfig==2.1.0
Jinja2==3.1.6
markdown-it-py==3.0.0
MarkupSafe==3.0.2
mdit-py-plugins==0.4.2
mdurl==0.1.2
mypy==1.2.0
mypy-extensions==1.0.0
myst-parser==3.0.1
packaging==24.2
pathspec==0.12.1
platformdirs==4.3.7
pluggy==1.5.0
Pygments==2.19.1
pyproject_hooks==1.2.0
pytest==8.3.5
pytest-cov==6.0.0
PyYAML==6.0.2
requests==2.32.3
-e git+https://github.com/JonathonReinhart/scuba.git@b4bfd81ff1b939079d24aa8d4cd62fccc2e6ad9a#egg=scuba
snowballstemmer==2.2.0
Sphinx==7.4.7
sphinx-rtd-theme==3.0.2
sphinxcontrib-applehelp==2.0.0
sphinxcontrib-devhelp==2.0.0
sphinxcontrib-htmlhelp==2.1.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==2.0.0
sphinxcontrib-serializinghtml==2.0.0
tomli==2.2.1
types-PyYAML==6.0.12.20250326
typing_extensions==4.13.0
urllib3==2.3.0
zipp==3.21.0
|
name: scuba
channels:
- defaults
- https://repo.anaconda.com/pkgs/main
- https://repo.anaconda.com/pkgs/r
- conda-forge
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- ca-certificates=2025.2.25=h06a4308_0
- ld_impl_linux-64=2.40=h12ee557_0
- libffi=3.4.4=h6a678d5_1
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libstdcxx-ng=11.2.0=h1234567_1
- ncurses=6.4=h6a678d5_0
- openssl=3.0.16=h5eee18b_0
- pip=25.0=py39h06a4308_0
- python=3.9.21=he870216_1
- readline=8.2=h5eee18b_0
- setuptools=75.8.0=py39h06a4308_0
- sqlite=3.45.3=h5eee18b_0
- tk=8.6.14=h39e8969_0
- tzdata=2025a=h04d1e81_0
- wheel=0.45.1=py39h06a4308_0
- xz=5.6.4=h5eee18b_1
- zlib=1.2.13=h5eee18b_1
- pip:
- alabaster==0.7.16
- argcomplete==3.6.1
- babel==2.17.0
- black==23.12.1
- build==1.2.2.post1
- certifi==2025.1.31
- charset-normalizer==3.4.1
- click==8.1.8
- coverage==7.8.0
- docutils==0.21.2
- exceptiongroup==1.2.2
- idna==3.10
- imagesize==1.4.1
- importlib-metadata==8.6.1
- iniconfig==2.1.0
- jinja2==3.1.6
- markdown-it-py==3.0.0
- markupsafe==3.0.2
- mdit-py-plugins==0.4.2
- mdurl==0.1.2
- mypy==1.2.0
- mypy-extensions==1.0.0
- myst-parser==3.0.1
- packaging==24.2
- pathspec==0.12.1
- platformdirs==4.3.7
- pluggy==1.5.0
- pygments==2.19.1
- pyproject-hooks==1.2.0
- pytest==8.3.5
- pytest-cov==6.0.0
- pyyaml==6.0.2
- requests==2.32.3
- scuba==2.12.0+28.gb4bfd81
- snowballstemmer==2.2.0
- sphinx==7.4.7
- sphinx-rtd-theme==3.0.2
- sphinxcontrib-applehelp==2.0.0
- sphinxcontrib-devhelp==2.0.0
- sphinxcontrib-htmlhelp==2.1.0
- sphinxcontrib-jquery==4.1
- sphinxcontrib-jsmath==1.0.1
- sphinxcontrib-qthelp==2.0.0
- sphinxcontrib-serializinghtml==2.0.0
- tomli==2.2.1
- types-pyyaml==6.0.12.20250326
- typing-extensions==4.13.0
- urllib3==2.3.0
- zipp==3.21.0
prefix: /opt/conda/envs/scuba
|
[
"tests/test_config.py::TestConfig::test_volumes_simple_bind",
"tests/test_config.py::TestConfig::test_volumes_complex_bind",
"tests/test_config.py::TestConfig::test_volumes_complex_named_volume",
"tests/test_config.py::TestConfig::test_alias_volumes_set",
"tests/test_config.py::TestConfig::test_volumes_with_env_vars_simple",
"tests/test_config.py::TestConfig::test_volumes_with_env_vars_complex",
"tests/test_config.py::TestConfig::test_volumes_hostpath_rel",
"tests/test_config.py::TestConfig::test_volumes_hostpath_rel_above",
"tests/test_config.py::TestConfig::test_volumes_hostpath_rel_in_env",
"tests/test_config.py::TestConfig::test_volumes_simple_named_volume",
"tests/test_config.py::TestConfig::test_volumes_simple_named_volume_env",
"tests/test_config.py::TestConfig::test_volumes_complex_named_volume_env",
"tests/test_config.py::TestConfig::test_volumes_complex_named_volume_env_unset",
"tests/test_config.py::TestConfig::test_volumes_complex_hostpath_and_name",
"tests/test_config.py::TestConfig::test_volumes_complex_empty"
] |
[
"tests/test_main.py::TestMain::test_basic",
"tests/test_main.py::TestMain::test_no_cmd",
"tests/test_main.py::TestMain::test_no_docker",
"tests/test_main.py::TestMain::test_dry_run",
"tests/test_main.py::TestMain::test_args",
"tests/test_main.py::TestMain::test_created_file_ownership",
"tests/test_main.py::TestMain::test_redirect_stdin",
"tests/test_main.py::TestMain::test_user_scubauser",
"tests/test_main.py::TestMain::test_user_root",
"tests/test_main.py::TestMain::test_user_run_as_root",
"tests/test_main.py::TestMain::test_user_root_alias",
"tests/test_main.py::TestMain::test_home_writable_scubauser",
"tests/test_main.py::TestMain::test_home_writable_root",
"tests/test_main.py::TestMain::test_arbitrary_docker_args",
"tests/test_main.py::TestMain::test_arbitrary_docker_args_merge_config",
"tests/test_main.py::TestMain::test_nested_sript",
"tests/test_main.py::TestMain::test_image_entrypoint",
"tests/test_main.py::TestMain::test_image_entrypoint_multiline",
"tests/test_main.py::TestMain::test_entrypoint_override",
"tests/test_main.py::TestMain::test_entrypoint_override_none",
"tests/test_main.py::TestMain::test_yaml_entrypoint_override",
"tests/test_main.py::TestMain::test_yaml_entrypoint_override_none",
"tests/test_main.py::TestMain::test_image_override",
"tests/test_main.py::TestMain::test_image_override_with_alias",
"tests/test_main.py::TestMain::test_yml_not_needed_with_image_override",
"tests/test_main.py::TestMain::test_complex_commands_in_alias",
"tests/test_main.py::TestMain::test_user_hook_runs_as_user",
"tests/test_main.py::TestMain::test_root_hook_runs_as_root",
"tests/test_main.py::TestMain::test_hook_failure_shows_correct_status",
"tests/test_main.py::TestMain::test_env_var_keyval",
"tests/test_main.py::TestMain::test_env_var_key_only",
"tests/test_main.py::TestMain::test_env_var_sources",
"tests/test_main.py::TestMain::test_builtin_env__SCUBA_ROOT",
"tests/test_main.py::TestMain::test_use_top_level_shell_override",
"tests/test_main.py::TestMain::test_alias_level_shell_override",
"tests/test_main.py::TestMain::test_cli_shell_override",
"tests/test_main.py::TestMain::test_shell_override_precedence",
"tests/test_main.py::TestMain::test_volumes_basic",
"tests/test_main.py::TestMain::test_volumes_alias_override",
"tests/test_main.py::TestMain::test_volumes_host_path_create",
"tests/test_main.py::TestMain::test_volumes_host_path_permissions",
"tests/test_main.py::TestMain::test_volumes_host_path_rel",
"tests/test_main.py::TestMain::test_volumes_hostpath_rel_above"
] |
[
"tests/test_config.py::TestCommonScriptSchema::test_simple",
"tests/test_config.py::TestCommonScriptSchema::test_script_key_string",
"tests/test_config.py::TestCommonScriptSchema::test_script_key_list",
"tests/test_config.py::TestCommonScriptSchema::test_script_key_mapping_invalid",
"tests/test_config.py::TestConfig::test_find_config_cur_dir",
"tests/test_config.py::TestConfig::test_find_config_parent_dir",
"tests/test_config.py::TestConfig::test_find_config_way_up",
"tests/test_config.py::TestConfig::test_find_config_nonexist",
"tests/test_config.py::TestConfig::test_load_config_no_image",
"tests/test_config.py::TestConfig::test_load_unexpected_node",
"tests/test_config.py::TestConfig::test_load_config_minimal",
"tests/test_config.py::TestConfig::test_load_config_with_aliases",
"tests/test_config.py::TestConfig::test_load_config__no_spaces_in_aliases",
"tests/test_config.py::TestConfig::test_load_config_image_from_yaml",
"tests/test_config.py::TestConfig::test_load_config_image_from_yaml_nested_keys",
"tests/test_config.py::TestConfig::test_load_config_image_from_yaml_nested_keys_with_escaped_characters",
"tests/test_config.py::TestConfig::test_load_config_from_yaml_cached_file",
"tests/test_config.py::TestConfig::test_load_config_image_from_yaml_nested_key_missing",
"tests/test_config.py::TestConfig::test_load_config_image_from_yaml_missing_file",
"tests/test_config.py::TestConfig::test_load_config_image_from_yaml_unicode_args",
"tests/test_config.py::TestConfig::test_load_config_image_from_yaml_missing_arg",
"tests/test_config.py::TestConfig::test_load_config_safe",
"tests/test_config.py::TestConfig::test_load_config_safe_external",
"tests/test_config.py::TestConfig::test_hooks_mixed",
"tests/test_config.py::TestConfig::test_hooks_invalid_list",
"tests/test_config.py::TestConfig::test_hooks_missing_script",
"tests/test_config.py::TestConfig::test_env_invalid",
"tests/test_config.py::TestConfig::test_env_top_dict",
"tests/test_config.py::TestConfig::test_env_top_list",
"tests/test_config.py::TestConfig::test_env_alias",
"tests/test_config.py::TestConfig::test_entrypoint_not_set",
"tests/test_config.py::TestConfig::test_entrypoint_null",
"tests/test_config.py::TestConfig::test_entrypoint_invalid",
"tests/test_config.py::TestConfig::test_entrypoint_emptry_string",
"tests/test_config.py::TestConfig::test_entrypoint_set",
"tests/test_config.py::TestConfig::test_alias_entrypoint_null",
"tests/test_config.py::TestConfig::test_alias_entrypoint_empty_string",
"tests/test_config.py::TestConfig::test_alias_entrypoint",
"tests/test_config.py::TestConfig::test_docker_args_not_set",
"tests/test_config.py::TestConfig::test_docker_args_invalid",
"tests/test_config.py::TestConfig::test_docker_args_null",
"tests/test_config.py::TestConfig::test_docker_args_set_empty_string",
"tests/test_config.py::TestConfig::test_docker_args_set",
"tests/test_config.py::TestConfig::test_docker_args_set_multi",
"tests/test_config.py::TestConfig::test_alias_docker_args_null",
"tests/test_config.py::TestConfig::test_alias_docker_args_empty_string",
"tests/test_config.py::TestConfig::test_alias_docker_args_set",
"tests/test_config.py::TestConfig::test_alias_docker_args_override",
"tests/test_config.py::TestConfig::test_alias_docker_args_override_implicit_null",
"tests/test_config.py::TestConfig::test_alias_docker_args_override_from_yaml",
"tests/test_config.py::TestConfig::test_alias_docker_args_from_yaml_override",
"tests/test_config.py::TestConfig::test_volumes_not_set",
"tests/test_config.py::TestConfig::test_volumes_null",
"tests/test_config.py::TestConfig::test_volumes_invalid",
"tests/test_config.py::TestConfig::test_volumes_invalid_volume_type",
"tests/test_config.py::TestConfig::test_volumes_null_volume_type",
"tests/test_config.py::TestConfig::test_volume_as_dict_missing_hostpath",
"tests/test_config.py::TestConfig::test_volumes_with_invalid_env_vars",
"tests/test_config.py::TestConfig::test_volumes_hostpath_rel_requires_dot_complex",
"tests/test_config.py::TestConfig::test_volumes_contpath_rel",
"tests/test_config.py::TestConfig::test_volumes_complex_invalid_hostpath",
"tests/test_main.py::TestMain::test_no_image_cmd",
"tests/test_main.py::TestMain::test_handle_get_image_command_error",
"tests/test_main.py::TestMain::test_config_error",
"tests/test_main.py::TestMain::test_multiline_alias_no_args_error",
"tests/test_main.py::TestMain::test_version",
"tests/test_main.py::TestMain::test_volumes_host_path_failure"
] |
[] |
MIT License
| 18,012
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.jonathonreinhart_1776_scuba-250:latest
|
LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/test_config.py tests/test_main.py tests/utils.py
|
#!/bin/bash
set -uxo pipefail
source /opt/miniconda3/bin/activate
conda activate testbed
cd /testbed
git config --global --add safe.directory /testbed
cd /testbed
git status
git show
git -c core.fileMode=false diff b4bfd81ff1b939079d24aa8d4cd62fccc2e6ad9a
source /opt/miniconda3/bin/activate
conda activate testbed
LANG=C.UTF-8 LC_ALL=C.UTF-8 pip install -e .[argcomplete]
git checkout b4bfd81ff1b939079d24aa8d4cd62fccc2e6ad9a tests/test_config.py tests/test_main.py tests/utils.py
git apply -v - <<'EOF_114329324912'
diff --git a/tests/test_config.py b/tests/test_config.py
index d07b481..65aa924 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -10,6 +10,7 @@ from unittest import mock
from .utils import assert_paths_equal, assert_vol
import scuba.config
+from scuba.config import ScubaVolume
def load_config() -> scuba.config.ScubaConfig:
@@ -878,7 +879,7 @@ class TestConfig:
self._invalid_config("hostpath")
- def test_volumes_simple_volume(self) -> None:
+ def test_volumes_simple_bind(self) -> None:
"""volumes can be set using the simple form"""
with open(".scuba.yml", "w") as f:
f.write(
@@ -895,7 +896,7 @@ class TestConfig:
assert_vol(config.volumes, "/cpath", "/hpath")
- def test_volumes_complex(self) -> None:
+ def test_volumes_complex_bind(self) -> None:
"""volumes can be set using the complex form"""
with open(".scuba.yml", "w") as f:
f.write(
@@ -920,6 +921,27 @@ class TestConfig:
assert_vol(vols, "/bar", "/host/bar")
assert_vol(vols, "/snap", "/host/snap", ["z", "ro"])
+ def test_volumes_complex_named_volume(self) -> None:
+ """volumes complex form can specify a named volume"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ name: foo-volume
+ """
+ )
+
+ config = load_config()
+ assert config.volumes is not None
+ assert len(config.volumes) == 1
+ vol = config.volumes[Path("/foo")]
+
+ assert isinstance(vol, ScubaVolume)
+ assert_paths_equal(vol.container_path, "/foo")
+ assert vol.volume_name == "foo-volume"
+
def test_alias_volumes_set(self) -> None:
"""docker_args can be set via alias"""
with open(".scuba.yml", "w") as f:
@@ -1076,20 +1098,6 @@ class TestConfig:
assert config.volumes is not None
assert_vol(config.volumes, "/foo", in_tmp_path / "foo_up_here")
- def test_volumes_hostpath_rel_req_dot_simple(
- self, monkeypatch, in_tmp_path
- ) -> None:
- """relaitve volume hostpath (simple form) must start with ./ or ../"""
- with open(".scuba.yml", "w") as f:
- f.write(
- r"""
- image: na
- volumes:
- /one: foo # Forbidden
- """
- )
- self._invalid_config("Relative path must start with ./ or ../")
-
def test_volumes_hostpath_rel_requires_dot_complex(
self, monkeypatch, in_tmp_path
) -> None:
@@ -1134,3 +1142,124 @@ class TestConfig:
"""
)
self._invalid_config("Relative path not allowed: foo")
+
+ def test_volumes_simple_named_volume(self) -> None:
+ """volumes simple form can specify a named volume"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo: foo-volume
+ """
+ )
+
+ config = load_config()
+ assert config.volumes is not None
+ assert len(config.volumes) == 1
+ vol = config.volumes[Path("/foo")]
+
+ assert isinstance(vol, ScubaVolume)
+ assert_paths_equal(vol.container_path, "/foo")
+ assert vol.volume_name == "foo-volume"
+
+ def test_volumes_simple_named_volume_env(self, monkeypatch) -> None:
+ """volumes simple form can specify a named volume via env var"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo: $FOO_VOLUME
+ """
+ )
+
+ monkeypatch.setenv("FOO_VOLUME", "foo-volume")
+
+ config = load_config()
+ assert config.volumes is not None
+ assert len(config.volumes) == 1
+ vol = config.volumes[Path("/foo")]
+
+ assert isinstance(vol, ScubaVolume)
+ assert_paths_equal(vol.container_path, "/foo")
+ assert vol.volume_name == "foo-volume"
+
+ def test_volumes_complex_named_volume_env(self, monkeypatch) -> None:
+ """volumes complex form can specify a named volume via env var"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ name: $FOO_VOLUME
+ """
+ )
+
+ monkeypatch.setenv("FOO_VOLUME", "foo-volume")
+
+ config = load_config()
+ assert config.volumes is not None
+ assert len(config.volumes) == 1
+ vol = config.volumes[Path("/foo")]
+
+ assert isinstance(vol, ScubaVolume)
+ assert_paths_equal(vol.container_path, "/foo")
+ assert vol.volume_name == "foo-volume"
+
+ def test_volumes_complex_named_volume_env_unset(self) -> None:
+ """volumes complex form fails on unset env var"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ name: $FOO_VOLUME
+ """
+ )
+ self._invalid_config("Unset environment variable")
+
+ def test_volumes_complex_invalid_hostpath(self) -> None:
+ """volumes complex form cannot specify an invalid hostpath"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ hostpath: foo-volume
+ """
+ )
+ self._invalid_config("Relative path must start with ./ or ../")
+
+ def test_volumes_complex_hostpath_and_name(self) -> None:
+ """volumes complex form cannot specify a named volume and hostpath"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ hostpath: /bar
+ name: foo-volume
+ """
+ )
+ self._invalid_config(
+ "Volume /foo must have exactly one of 'hostpath' or 'name' subkey"
+ )
+
+ def test_volumes_complex_empty(self) -> None:
+ """volumes complex form cannot be empty"""
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ r"""
+ image: na
+ volumes:
+ /foo:
+ """
+ )
+ self._invalid_config(
+ "Volume /foo must have exactly one of 'hostpath' or 'name' subkey"
+ )
diff --git a/tests/test_main.py b/tests/test_main.py
index 5e77b32..7b242fb 100644
--- a/tests/test_main.py
+++ b/tests/test_main.py
@@ -29,7 +29,7 @@ SCUBAINIT_EXIT_FAIL = 99
@pytest.mark.usefixtures("in_tmp_path")
-class TestMain:
+class TestMainBase:
def run_scuba(self, args, exp_retval=0, mock_isatty=False, stdin=None):
"""Run scuba, checking its return value
@@ -87,6 +87,8 @@ class TestMain:
sys.stdout = old_stdout
sys.stderr = old_stderr
+
+class TestMain(TestMainBase):
def test_basic(self) -> None:
"""Verify basic scuba functionality"""
@@ -1133,3 +1135,47 @@ class TestMain:
out, _ = self.run_scuba(["cat", "/userdir/test.txt"])
assert out == test_message
+
+
+class TestMainNamedVolumes(TestMainBase):
+ VOLUME_NAME = "foo-volume"
+
+ def _rm_volume(self) -> None:
+ result = subprocess.run(
+ ["docker", "volume", "rm", self.VOLUME_NAME],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode == 1 and re.match(r".*no such volume.*", result.stderr):
+ return
+ result.check_returncode()
+
+ def setup_method(self, method) -> None:
+ self._rm_volume()
+
+ def teardown_method(self, method) -> None:
+ self._rm_volume()
+
+ def test_volumes_named(self) -> None:
+ """Verify named volumes can be used"""
+ VOL_PATH = Path("/foo")
+ TEST_PATH = VOL_PATH / "test.txt"
+ TEST_STR = "it works!"
+
+ with open(".scuba.yml", "w") as f:
+ f.write(
+ f"""
+ image: {DOCKER_IMAGE}
+ hooks:
+ root: chmod 777 {VOL_PATH}
+ volumes:
+ {VOL_PATH}: {self.VOLUME_NAME}
+ """
+ )
+
+ # Inoke scuba once: Write a file to the named volume
+ self.run_scuba(["/bin/sh", "-c", f"echo {TEST_STR} > {TEST_PATH}"])
+
+ # Invoke scuba again: Verify the file is still there
+ out, _ = self.run_scuba(["/bin/sh", "-c", f"cat {TEST_PATH}"])
+ assert_str_equalish(out, TEST_STR)
diff --git a/tests/utils.py b/tests/utils.py
index efe7036..8e78fea 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -48,6 +48,8 @@ def assert_vol(
v = vols[cpath]
assert isinstance(v, ScubaVolume)
assert_paths_equal(v.container_path, cpath)
+ assert v.volume_name is None
+ assert v.host_path is not None
assert_paths_equal(v.host_path, hpath)
assert v.options == options
EOF_114329324912
: '>>>>> Start Test Output'
LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning tests/test_config.py tests/test_main.py tests/utils.py
: '>>>>> End Test Output'
git checkout b4bfd81ff1b939079d24aa8d4cd62fccc2e6ad9a tests/test_config.py tests/test_main.py tests/utils.py
|
|
polsys__ennemi-120
|
cbae2737ca5d5244df94a5a769b4d55a58971bca
|
2024-03-22 07:53:12
|
cbae2737ca5d5244df94a5a769b4d55a58971bca
| "diff --git a/.github/workflows/continuous-integration.yml b/.github/workflows/continuous-integratio(...TRUNCATED)
| "Add support for NumPy 2.0\n- [ ] Modify `setup.py` to accept NumPy 2.0\r\n- [ ] Add prerelease NumP(...TRUNCATED)
|
polsys/ennemi
| "diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml\nind(...TRUNCATED)
| {"commit_name":"merge_commit","failed_lite_validators":["has_short_problem_statement","has_added_fil(...TRUNCATED)
|
1.3
| {"env_vars":null,"env_yml_path":null,"install":"pip install -e .[dev]","log_parser":"parse_log_pytes(...TRUNCATED)
| "attrs==25.3.0\n-e git+https://github.com/polsys/ennemi.git@cbae2737ca5d5244df94a5a769b4d55a58971bca(...TRUNCATED)
| "name: ennemi\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.an(...TRUNCATED)
| ["tests/unit/test_driver.py::TestEstimateMi::test_normalize_with_discrete_warns","tests/unit/test_dr(...TRUNCATED)
|
[] | ["tests/unit/test_driver.py::TestEstimateEntropy::test_cond_has_wrong_dimension","tests/unit/test_dr(...TRUNCATED)
|
[] |
MIT License
| 18,014
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.polsys_1776_ennemi-120:latest
| "LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W igno(...TRUNCATED)
| "#!/bin/bash\nset -uxo pipefail\nsource /opt/miniconda3/bin/activate\nconda activate testbed\ncd /te(...TRUNCATED)
|
|
regionmask__regionmask-521
|
6d77660f0365b1986262492477976ee12bc78c29
|
2024-03-22 09:28:55
|
f5b52bc1ae795b727c15fc75adf68c6ec7d7d87f
| "codecov[bot]: ## [Codecov](https://app.codecov.io/gh/regionmask/regionmask/pull/521?dropdown=covera(...TRUNCATED)
| "diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml\nindex 5d3452a..e485cfb 100644\n(...TRUNCATED)
| "drop support for pygeos and shapely < 2.0\nDropping pygeos and shapely 1.8 will allow considerable (...TRUNCATED)
|
regionmask/regionmask
| "diff --git a/regionmask/tests/__init__.py b/regionmask/tests/__init__.py\nindex ad704d1..27ca2bf 10(...TRUNCATED)
| {"commit_name":"merge_commit","failed_lite_validators":["has_removed_files","has_many_modified_files(...TRUNCATED)
|
0.12
| {"env_vars":null,"env_yml_path":["ci/requirements/environment.yml"],"install":"pip install -e .","lo(...TRUNCATED)
| "affine @ file:///home/conda/feedstock_root/build_artifacts/affine_1733762038348/work\nattrs @ file:(...TRUNCATED)
| "name: regionmask\nchannels:\n - https://repo.anaconda.com/pkgs/main\n - https://repo.anaconda.com(...TRUNCATED)
| ["regionmask/tests/test_mask.py::test_determine_method[lat0-0-lon4-3]","regionmask/tests/test_mask.p(...TRUNCATED)
|
[] | ["regionmask/tests/test_mask.py::test_mask_func[_mask_rasterize]","regionmask/tests/test_mask.py::te(...TRUNCATED)
|
[] |
MIT License
| 18,016
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.regionmask_1776_regionmask-521:latest
| "LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W igno(...TRUNCATED)
| "#!/bin/bash\nset -uxo pipefail\nsource /opt/miniconda3/bin/activate\nconda activate testbed\ncd /te(...TRUNCATED)
|
tobymao__sqlglot-3198
|
0dd9ba5ef57d29b6406a5d2a7e381eb6e6f56221
|
2024-03-22 12:04:25
|
2f6a2f13bbd40f3d5348b0ed1b8cf6736ef9d1c5
| "diff --git a/sqlglot/dataframe/sql/functions.py b/sqlglot/dataframe/sql/functions.py\nindex ca117e1(...TRUNCATED)
| "ex.convert(b\"\\x00\\x00\\x00\\x00\\x00\\x00\\x07\\xd3\") throws, but should be HexString\nThe beha(...TRUNCATED)
|
tobymao/sqlglot
| "diff --git a/tests/dialects/test_snowflake.py b/tests/dialects/test_snowflake.py\nindex 4d7d97c5..4(...TRUNCATED)
| {"commit_name":"merge_commit","failed_lite_validators":["has_many_modified_files","has_many_hunks"],(...TRUNCATED)
|
23.0
| {"env_vars":null,"env_yml_path":null,"install":"pip install -e .[dev]","log_parser":"parse_log_pytes(...TRUNCATED)
| "cfgv==3.4.0\ncoverage==7.8.0\ndistlib==0.3.9\nduckdb==1.2.1\nexceptiongroup==1.2.2\nexecnet==2.1.1\(...TRUNCATED)
| "name: sqlglot\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.a(...TRUNCATED)
| ["tests/dialects/test_snowflake.py::TestSnowflake::test_snowflake","tests/test_expressions.py::TestE(...TRUNCATED)
|
[] | ["tests/dialects/test_snowflake.py::TestSnowflake::test_ddl","tests/dialects/test_snowflake.py::Test(...TRUNCATED)
|
[] |
MIT License
| 18,017
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.tobymao_1776_sqlglot-3198:latest
| "LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W igno(...TRUNCATED)
| "#!/bin/bash\nset -uxo pipefail\nsource /opt/miniconda3/bin/activate\nconda activate testbed\ncd /te(...TRUNCATED)
|
|
conan-io__conan-15924
|
82765f2ba80a3f07d21de4c27d73203081017694
|
2024-03-22 12:53:10
|
aa52f656c2ee45b01920ffbc5c8b250e5204c142
| "CLAassistant: [](https://cla-(...TRUNCATED)
| "diff --git a/conan/tools/cmake/toolchain/blocks.py b/conan/tools/cmake/toolchain/blocks.py\nindex 3(...TRUNCATED)
| "[bug] `tools.build:defines` is broken in multiconfig setting\n### Describe the bug\r\n\r\n`tools.bu(...TRUNCATED)
|
conan-io/conan
| "diff --git a/conans/test/functional/toolchains/cmake/test_cmake_toolchain.py b/conans/test/function(...TRUNCATED)
| {"commit_name":"merge_commit","failed_lite_validators":["has_many_modified_files"],"has_test_patch":(...TRUNCATED)
|
2.2
| {"env_vars":null,"env_yml_path":null,"install":"pip install -e .[dev]","log_parser":"parse_log_pytes(...TRUNCATED)
| "attrs==25.3.0\nbeautifulsoup4==4.13.3\nbottle==0.12.25\ncertifi==2025.1.31\ncharset-normalizer==3.4(...TRUNCATED)
| "name: conan\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.ana(...TRUNCATED)
|
[
"conans/test/unittests/model/conanfile_test.py::ConanFileTest::test_conanfile_new_print_save"
] | ["conans/test/functional/toolchains/cmake/test_cmake_toolchain.py::test_cmake_toolchain_user_toolcha(...TRUNCATED)
| ["conans/test/functional/toolchains/cmake/test_cmake_toolchain.py::test_cmake_toolchain_user_toolcha(...TRUNCATED)
|
[] |
MIT License
| 18,018
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.conan-io_1776_conan-15924:latest
| "LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W igno(...TRUNCATED)
| "#!/bin/bash\nset -uxo pipefail\nsource /opt/miniconda3/bin/activate\nconda activate testbed\ncd /te(...TRUNCATED)
|
tobymao__sqlglot-3201
|
a18444dbd7ccfc05b189dcb2005c85a1048cc8de
|
2024-03-22 15:26:52
|
2f6a2f13bbd40f3d5348b0ed1b8cf6736ef9d1c5
| "diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py\nindex a41b6ea8..70066677 (...TRUNCATED)
| "Inconsistent formatting when leading_comma=True\nHi! This is something I noticed when trying out th(...TRUNCATED)
|
tobymao/sqlglot
| "diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py\nindex 896ee451..7af(...TRUNCATED)
| {"commit_name":"merge_commit","failed_lite_validators":["has_hyperlinks","has_many_modified_files","(...TRUNCATED)
|
23.0
| {"env_vars":null,"env_yml_path":null,"install":"pip install -e .[dev]","log_parser":"parse_log_pytes(...TRUNCATED)
| "cfgv==3.4.0\ndistlib==0.3.9\nduckdb==1.2.1\nexceptiongroup==1.2.2\nfilelock==3.18.0\nidentify==2.6.(...TRUNCATED)
| "name: sqlglot\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.a(...TRUNCATED)
| ["tests/dialects/test_redshift.py::TestRedshift::test_redshift","tests/test_expressions.py::TestExpr(...TRUNCATED)
|
[] | ["tests/dialects/test_redshift.py::TestRedshift::test_column_unnesting","tests/dialects/test_redshif(...TRUNCATED)
|
[] |
MIT License
| 18,020
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.tobymao_1776_sqlglot-3201:latest
| "LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W igno(...TRUNCATED)
| "#!/bin/bash\nset -uxo pipefail\nsource /opt/miniconda3/bin/activate\nconda activate testbed\ncd /te(...TRUNCATED)
|
|
tobymao__sqlglot-3203
|
3620b9974c28df7d4d189ebd5fdcb675f41a275d
|
2024-03-22 16:17:57
|
2f6a2f13bbd40f3d5348b0ed1b8cf6736ef9d1c5
| "diff --git a/sqlglot/dialects/redshift.py b/sqlglot/dialects/redshift.py\nindex a41b6ea8..70066677 (...TRUNCATED)
| "Unable to parse view definition with schemabinding\nParsing mssql view definitions for lineage info(...TRUNCATED)
|
tobymao/sqlglot
| "diff --git a/tests/dialects/test_redshift.py b/tests/dialects/test_redshift.py\nindex 896ee451..7af(...TRUNCATED)
| {"commit_name":"merge_commit","failed_lite_validators":["has_hyperlinks","has_many_modified_files","(...TRUNCATED)
|
23.0
| {"env_vars":null,"env_yml_path":null,"install":"pip install -e .[dev]","log_parser":"parse_log_pytes(...TRUNCATED)
| "cfgv==3.4.0\ndistlib==0.3.9\nduckdb==1.2.1\nexceptiongroup @ file:///croot/exceptiongroup_170603138(...TRUNCATED)
| "name: sqlglot\nchannels:\n - defaults\n - https://repo.anaconda.com/pkgs/main\n - https://repo.a(...TRUNCATED)
| ["tests/dialects/test_redshift.py::TestRedshift::test_redshift","tests/test_tokens.py::TestTokens::t(...TRUNCATED)
|
[] | ["tests/dialects/test_redshift.py::TestRedshift::test_column_unnesting","tests/dialects/test_redshif(...TRUNCATED)
|
[] |
MIT License
| 18,021
|
swerebench_p19_817
|
SWE-rebench
| 817
|
jierun/sweb.eval.x86_64.tobymao_1776_sqlglot-3203:latest
| "LANG=C.UTF-8 LC_ALL=C.UTF-8 pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W igno(...TRUNCATED)
| "#!/bin/bash\nset -uxo pipefail\nsource /opt/miniconda3/bin/activate\nconda activate testbed\ncd /te(...TRUNCATED)
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 18