hc99 commited on
Commit
fc0f7bd
·
verified ·
1 Parent(s): 09d8e80

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/facebookresearch__hydra/.circleci/config.yml +277 -0
  2. testbed/facebookresearch__hydra/.coveragerc +16 -0
  3. testbed/facebookresearch__hydra/.flake8 +7 -0
  4. testbed/facebookresearch__hydra/.gitattributes +29 -0
  5. testbed/facebookresearch__hydra/.gitignore +16 -0
  6. testbed/facebookresearch__hydra/.isort.cfg +10 -0
  7. testbed/facebookresearch__hydra/.pre-commit-config.yaml +17 -0
  8. testbed/facebookresearch__hydra/.yamllint +34 -0
  9. testbed/facebookresearch__hydra/CHANGELOG.md +1 -0
  10. testbed/facebookresearch__hydra/CODE_OF_CONDUCT.md +2 -0
  11. testbed/facebookresearch__hydra/CONTRIBUTING.md +32 -0
  12. testbed/facebookresearch__hydra/LICENSE +21 -0
  13. testbed/facebookresearch__hydra/MANIFEST.in +5 -0
  14. testbed/facebookresearch__hydra/NEWS.md +323 -0
  15. testbed/facebookresearch__hydra/README.md +49 -0
  16. testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/MANIFEST.in +3 -0
  17. testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/README.md +5 -0
  18. testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/__init__.py +88 -0
  19. testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/py.typed +0 -0
  20. testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/setup.py +35 -0
  21. testbed/facebookresearch__hydra/lgtm.yml +2 -0
  22. testbed/facebookresearch__hydra/noxfile.py +379 -0
  23. testbed/facebookresearch__hydra/pyproject.toml +49 -0
  24. testbed/facebookresearch__hydra/pytest.ini +8 -0
  25. testbed/facebookresearch__hydra/setup.cfg +3 -0
  26. testbed/facebookresearch__hydra/setup.py +115 -0
  27. testbed/facebookresearch__hydra/tests/__init__.py +4 -0
  28. testbed/facebookresearch__hydra/tests/scripts/test_bash_completion.exp +46 -0
  29. testbed/facebookresearch__hydra/tests/test_apps/app_with_cfg_groups/conf/dataset/imagenet.yaml +4 -0
  30. testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/config.yaml +3 -0
  31. testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/group/opt1.yaml +2 -0
  32. testbed/facebookresearch__hydra/tests/test_basic_launcher.py +45 -0
  33. testbed/facebookresearch__hydra/tests/test_completion.py +314 -0
  34. testbed/facebookresearch__hydra/tests/test_config_loader.py +1194 -0
  35. testbed/facebookresearch__hydra/tests/test_config_repository.py +179 -0
  36. testbed/facebookresearch__hydra/tests/test_config_search_path.py +175 -0
  37. testbed/facebookresearch__hydra/tests/test_core_utils.py +25 -0
  38. testbed/facebookresearch__hydra/tests/test_hydra.py +814 -0
  39. testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/setup.py +12 -0
  40. testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/level1/level2/nested1.yaml +2 -0
  41. testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/explicit.yaml +2 -0
  42. testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/group_name.yaml +2 -0
  43. testbed/facebookresearch__hydra/tests/test_utils.py +322 -0
  44. testbed/facebookresearch__hydra/website/.gitignore +20 -0
  45. testbed/facebookresearch__hydra/website/.yarnclean +45 -0
  46. testbed/facebookresearch__hydra/website/README.md +34 -0
  47. testbed/facebookresearch__hydra/website/blog/2020-05-04-New-blog.md +20 -0
  48. testbed/facebookresearch__hydra/website/docs/advanced/command_line_overrides.md +56 -0
  49. testbed/facebookresearch__hydra/website/docs/advanced/overriding_packages.md +135 -0
  50. testbed/facebookresearch__hydra/website/docs/advanced/packaging.md +34 -0
testbed/facebookresearch__hydra/.circleci/config.yml ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2.1
2
+
3
+ jobs:
4
+ # Mac
5
+ py36_mac:
6
+ macos:
7
+ xcode: "10.0.0"
8
+ steps:
9
+ - checkout
10
+ - run:
11
+ name: "Installing Conda"
12
+ command: |
13
+ curl -o Miniconda3-latest-MacOSX-x86_64.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh
14
+ bash ./Miniconda3-latest-MacOSX-x86_64.sh -b
15
+ ~/miniconda3/bin/conda init bash
16
+ - run:
17
+ name: "Preparing environment"
18
+ command: |
19
+ brew update
20
+ brew install fish
21
+ conda create -n hydra python=3.6 -yq
22
+ conda run -n hydra pip install nox
23
+ - run:
24
+ name: "Testing Hydra"
25
+ no_output_timeout: 10m
26
+ command: |
27
+ export NOX_PYTHON_VERSIONS=3.6
28
+ conda activate hydra
29
+ pip install nox dataclasses
30
+ nox
31
+
32
+ py37_mac:
33
+ macos:
34
+ xcode: "10.0.0"
35
+ steps:
36
+ - checkout
37
+ - run:
38
+ name: "Installing Conda"
39
+ command: |
40
+ curl -o Miniconda3-latest-MacOSX-x86_64.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh
41
+ bash ./Miniconda3-latest-MacOSX-x86_64.sh -b
42
+ ~/miniconda3/bin/conda init bash
43
+ - run:
44
+ name: "Preparing environment"
45
+ command: |
46
+ brew update
47
+ brew install fish
48
+ conda create -n hydra python=3.7 -yq
49
+ conda run -n hydra pip install nox
50
+ - run:
51
+ name: "Testing Hydra"
52
+ no_output_timeout: 10m
53
+ command: |
54
+ export NOX_PYTHON_VERSIONS=3.7
55
+ conda activate hydra
56
+ pip install nox
57
+ nox
58
+
59
+ py38_mac:
60
+ macos:
61
+ xcode: "10.0.0"
62
+ steps:
63
+ - checkout
64
+ - run:
65
+ name: "Installing Conda"
66
+ command: |
67
+ curl -o Miniconda3-latest-MacOSX-x86_64.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh
68
+ bash ./Miniconda3-latest-MacOSX-x86_64.sh -b
69
+ ~/miniconda3/bin/conda init bash
70
+ - run:
71
+ name: "Preparing environment"
72
+ command: |
73
+ brew update
74
+ brew install fish
75
+ conda create -n hydra python=3.8 -yq
76
+ conda run -n hydra pip install nox
77
+ - run:
78
+ name: "Testing Hydra"
79
+ no_output_timeout: 10m
80
+ command: |
81
+ export NOX_PYTHON_VERSIONS=3.8
82
+ conda activate hydra
83
+ pip install nox
84
+ nox
85
+
86
+ # Linux
87
+ py36_linux:
88
+ docker:
89
+ - image: circleci/python:3.6
90
+ steps:
91
+ - checkout
92
+ - run:
93
+ name: "Preparing environment"
94
+ command: |
95
+ sudo apt-get update
96
+ sudo apt-get install -y expect fish
97
+ sudo pip install nox
98
+ - run:
99
+ name: "Testing Hydra"
100
+ command: |
101
+ export NOX_PYTHON_VERSIONS=3.6
102
+ pip install nox dataclasses
103
+ nox
104
+
105
+ py37_linux:
106
+ docker:
107
+ - image: circleci/python:3.7
108
+ steps:
109
+ - checkout
110
+ - run:
111
+ name: "Preparing environment"
112
+ command: |
113
+ sudo apt-get update
114
+ sudo apt-get install -y expect fish
115
+ sudo pip install nox
116
+ - run:
117
+ name: "Testing Hydra"
118
+ command: |
119
+ export NOX_PYTHON_VERSIONS=3.7
120
+ pip install nox
121
+ nox
122
+
123
+ py38_linux:
124
+ docker:
125
+ - image: circleci/python:3.8
126
+ steps:
127
+ - checkout
128
+ - run:
129
+ name: "Preparing environment"
130
+ command: |
131
+ sudo apt-get update
132
+ sudo apt-get install -y expect fish
133
+ sudo pip install nox
134
+ - run:
135
+ name: "Testing Hydra"
136
+ command: |
137
+ export NOX_PYTHON_VERSIONS=3.8
138
+ pip install nox
139
+ nox
140
+
141
+ # windows
142
+ py36_win:
143
+ executor: win/default
144
+ steps:
145
+ - checkout
146
+ - run:
147
+ name: Installing Conda
148
+ command: |
149
+ choco install miniconda3 -y
150
+ C:\tools\miniconda3\Scripts\conda.exe init powershell
151
+ choco install openssl -y
152
+ - run:
153
+ name: Preparing conda environment
154
+ command: |
155
+ conda create -n hydra python=3.6 pywin32 -qy
156
+ conda activate hydra
157
+ pip install nox dataclasses
158
+ - run:
159
+ name: Testing Hydra
160
+ no_output_timeout: 20m
161
+ command: |
162
+ $env:NOX_PYTHON_VERSIONS=3.6
163
+ $env:PYTHONIOENCODING="utf_8"
164
+ conda activate hydra
165
+ nox
166
+ exit $LASTEXITCODE
167
+
168
+ py37_win:
169
+ executor: win/default
170
+ steps:
171
+ - checkout
172
+ - run:
173
+ name: Installing Conda
174
+ command: |
175
+ choco install miniconda3 -y
176
+ C:\tools\miniconda3\Scripts\conda.exe init powershell
177
+ choco install openssl -y
178
+ - run:
179
+ name: Preparing conda environment
180
+ command: |
181
+ conda create -n hydra python=3.7 pywin32 -qy
182
+ conda activate hydra
183
+ pip install nox
184
+ - run:
185
+ name: Testing Hydra
186
+ no_output_timeout: 20m
187
+ command: |
188
+ $env:NOX_PYTHON_VERSIONS=3.7
189
+ $env:PYTHONIOENCODING="utf_8"
190
+ conda activate hydra
191
+ nox
192
+ exit $LASTEXITCODE
193
+
194
+ py38_win:
195
+ executor: win/default
196
+ steps:
197
+ - checkout
198
+ - run:
199
+ name: Installing Conda
200
+ command: |
201
+ choco install miniconda3 -y
202
+ C:\tools\miniconda3\Scripts\conda.exe init powershell
203
+ choco install openssl -y
204
+ - run:
205
+ name: Preparing conda environment
206
+ command: |
207
+ conda create -n hydra python=3.8 pywin32 -qy
208
+ conda activate hydra
209
+ pip install nox
210
+ - run:
211
+ name: Testing Hydra
212
+ no_output_timeout: 20m
213
+ command: |
214
+ $env:NOX_PYTHON_VERSIONS=3.8
215
+ $env:PYTHONIOENCODING="utf_8"
216
+ conda activate hydra
217
+ nox
218
+ exit $LASTEXITCODE
219
+ # Misc
220
+ coverage:
221
+ docker:
222
+ - image: circleci/python:3.6
223
+ steps:
224
+ - checkout
225
+ - run: sudo pip install nox
226
+ - run: nox -s coverage
227
+
228
+ deploy-website:
229
+ docker:
230
+ - image: circleci/node:12
231
+ steps:
232
+ - checkout
233
+ - deploy:
234
+ name: Deploying to GitHub Pages
235
+ command: |
236
+ SUBDIR=website
237
+ REV=$(git log -5 --pretty=oneline origin/gh-pages | grep "Deploy website" | awk 'NF>1{print $NF}' | head -1)
238
+ # This condition passes in 2 conditions:
239
+ # 1. The revision does not exist (squash/force push happened)
240
+ # 2. There are changes between last deployed revision and HEAD
241
+ if [[ ! $(git rev-parse --verify -q "$REV^{commit}") || $(git diff-index $REV -- $SUBDIR) ]]; then
242
+ echo "Changes detected in directory $SUBDIR between origin/master and this diff"
243
+
244
+ cd $SUBDIR
245
+ yarn --no-progress
246
+
247
+ git config --global user.email omry@users.noreply.github.com
248
+ git config --global user.name omry
249
+ echo "machine github.com login docusaurus-bot password $GITHUB_TOKEN" > ~/.netrc
250
+ yarn install && GIT_USER=docusaurus-bot yarn deploy
251
+ else
252
+ echo "No changes detected in directory $SUBDIR between origin/master and this diff"
253
+ fi
254
+
255
+ workflows:
256
+ version: 2
257
+ build:
258
+ jobs:
259
+ # linux
260
+ - py36_linux
261
+ - py37_linux
262
+ - py38_linux
263
+ # mac
264
+ - py36_mac
265
+ - py37_mac
266
+ - py38_mac
267
+ # windows
268
+ - py36_win
269
+ - py37_win
270
+ - py38_win
271
+ - deploy-website:
272
+ filters:
273
+ branches:
274
+ only: master
275
+
276
+ orbs:
277
+ win: circleci/windows@1.0.0
testbed/facebookresearch__hydra/.coveragerc ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [run]
2
+ omit =
3
+ ${COVERAGE_HOME}/.nox/*
4
+ ${COVERAGE_HOME}/*tests*
5
+ ${COVERAGE_HOME}/plugins/*
6
+
7
+ [report]
8
+ exclude_lines =
9
+ pragma: no cover
10
+ # Don't complain if tests don't hit defensive assertion code:
11
+ raise AssertionError
12
+ raise NotImplementedError
13
+ raise TypeError
14
+ @deprecated
15
+ assert False
16
+
testbed/facebookresearch__hydra/.flake8 ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [flake8]
2
+ exclude = .git,.nox,build
3
+ max-line-length = 119
4
+ copyright-check = True
5
+ select = E,F,W,C
6
+ copyright-regexp=Copyright \(c\) Facebook, Inc. and its affiliates. All Rights Reserved
7
+ ignore=W503,E203
testbed/facebookresearch__hydra/.gitattributes ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
3
+ * text eol=lf
4
+
5
+ # Don't do anything with binaries
6
+ *.png binary
7
+ *.jpg binary
8
+ *.svg binary
9
+ *.jpeg binary
10
+ *.gif binary
11
+ *.ico binary
12
+ *.mov binary
13
+ *.mp4 binary
14
+ *.mp3 binary
15
+ *.flv binary
16
+ *.fla binary
17
+ *.swf binary
18
+ *.gz binary
19
+ *.zip binary
20
+ *.7z binary
21
+ *.ttf binary
22
+ *.eot binary
23
+ *.woff binary
24
+ *.pyc binary
25
+ *.pdf binary
26
+ *.ez binary
27
+ *.bz2 binary
28
+ *.swp binary
29
+ *.webp binary
testbed/facebookresearch__hydra/.gitignore ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /.idea
2
+ outputs
3
+ multirun
4
+ dist
5
+ build
6
+ __pycache__
7
+ *.pyc
8
+ *.egg-info
9
+ /.nox
10
+ /report.json
11
+ /.coverage
12
+ .mypy_cache
13
+ pip-wheel-metadata
14
+ .ipynb_checkpoints
15
+ /.dmypy.json
16
+ TODO.txt
testbed/facebookresearch__hydra/.isort.cfg ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ [settings]
2
+ multi_line_output=3
3
+ include_trailing_comma=True
4
+ force_grid_wrap=0
5
+ use_parentheses=True
6
+ line_length=88
7
+ ensure_newline_before_comments=True
8
+ known_third_party=omegaconf,ray,pytest,typing_extensions
9
+ known_first_party=hydra
10
+ skip=plugins,.nox
testbed/facebookresearch__hydra/.pre-commit-config.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/timothycrosley/isort
3
+ rev: 'c54b3dd'
4
+ hooks:
5
+ - id: isort
6
+
7
+ - repo: https://github.com/psf/black
8
+ rev: stable
9
+ hooks:
10
+ - id: black
11
+ language_version: python3.6
12
+
13
+ - repo: https://gitlab.com/pycqa/flake8
14
+ rev: 3.7.9
15
+ hooks:
16
+ - id: flake8
17
+ additional_dependencies: [-e, "git+git://github.com/pycqa/pyflakes.git@1911c20#egg=pyflakes"]
testbed/facebookresearch__hydra/.yamllint ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ yaml-files:
2
+ - '*.yaml'
3
+ - '*.yml'
4
+ - '.yamllint'
5
+
6
+ rules:
7
+ braces: enable
8
+ brackets: enable
9
+ colons: enable
10
+ commas: enable
11
+ comments:
12
+ level: warning
13
+ comments-indentation:
14
+ level: warning
15
+ document-end: disable
16
+ document-start: disable
17
+ empty-lines: enable
18
+ empty-values: disable
19
+ hyphens: enable
20
+ indentation: enable
21
+ key-duplicates: enable
22
+ key-ordering: disable
23
+ line-length: disable
24
+ new-line-at-end-of-file: enable
25
+ new-lines: enable
26
+ octal-values: disable
27
+ quoted-strings: disable
28
+ trailing-spaces: enable
29
+ truthy:
30
+ level: warning
31
+
32
+ ignore: |
33
+ **/.hydra/*.yaml
34
+ .*
testbed/facebookresearch__hydra/CHANGELOG.md ADDED
@@ -0,0 +1 @@
 
 
1
+ Please see NEWS.rst for an updated change log
testbed/facebookresearch__hydra/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Code of Conduct
2
+ Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](https://code.fb.com/codeofconduct) so that you can understand what actions will and will not be tolerated.
testbed/facebookresearch__hydra/CONTRIBUTING.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to hydra
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ Please see the [developer guide](https://hydra.cc/docs/development/contributing/) on the website.
6
+
7
+ ## Pull Requests
8
+ We welcome your pull requests.
9
+
10
+ 1. Fork the repo and create your feature branch from `master`.
11
+ 2. If you've added code add suitable tests.
12
+ 3. If you've changed APIs, update the documentation.
13
+ 4. Ensure the test suite and lint pass.
14
+ 5. If you haven't already, complete the Contributor License Agreement ("CLA").
15
+
16
+ ## Contributor License Agreement ("CLA")
17
+ In order to accept your pull request, we need you to submit a CLA. You only need
18
+ to do this once to work on any of Facebook's open source projects.
19
+
20
+ Complete your CLA here: <https://code.facebook.com/cla>
21
+
22
+ ## Issues
23
+ We use GitHub issues to track public bugs. Please ensure your description is
24
+ clear and has sufficient instructions to be able to reproduce the issue.
25
+
26
+ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
27
+ disclosure of security bugs. In those cases, please go through the process
28
+ outlined on that page and do not file a public issue.
29
+
30
+ ## License
31
+ By contributing to hydra, you agree that your contributions will be licensed
32
+ under the LICENSE file in the root directory of this source tree.
testbed/facebookresearch__hydra/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Facebook, Inc. and its affiliates.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
testbed/facebookresearch__hydra/MANIFEST.in ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ include hydra/py.typed
2
+ global-exclude *.pyc
3
+ global-exclude __pycache__
4
+ recursive-include hydra/* *
5
+
testbed/facebookresearch__hydra/NEWS.md ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 1.0.0-rc1 (2020-05-31)
2
+ ======================
3
+ Hydra 1.0 is a major release introducing many new features and breaking some compatibility.
4
+
5
+ Features
6
+ --------
7
+ - Upgrade to OmegaConf 2.0 ([Release notes](https://github.com/omry/omegaconf/releases/tag/2.0.0)) (#630)
8
+ - Optional config type safety via Structured Configs (#629)
9
+ - Improve command line and config composition error reporting (#349)
10
+ - Hydra config can now be accessed through interpolation using ${hydra:key}, for example ${hydra:job.name} ([#325](https://github.com/facebookresearch/hydra/issues/325))
11
+ - Support for setting environment variable of running job ([#7](https://github.com/facebookresearch/hydra/issues/7))
12
+ - Changes command line processing (requiring + and ~ prefixes for appending and removing items) ([#598](https://github.com/facebookresearch/hydra/issues/598))
13
+ - Introducing `@package` header for config files ([#586](https://github.com/facebookresearch/hydra/issues/586))
14
+ - Add command line override flags for `config_path` and `config_name` ([#386](https://github.com/facebookresearch/hydra/issues/386))
15
+ - hydra.main() now take an optional cfg object to passthrough to the function ([#575](https://github.com/facebookresearch/hydra/issues/575))
16
+ - Add hydra.experimental.{initialize_with_file, initialize_with_module} ([#574](https://github.com/facebookresearch/hydra/issues/574))
17
+ - Support for disabling the creation of the `.hydra` subdirectory by overriding "hydra.output_subdir" to "null" ([#324](https://github.com/facebookresearch/hydra/issues/324))
18
+ - Add `hydra.utils.call()` to call methods and functions as well as instantiate objects. Search module paths more generically. ([#498](https://github.com/facebookresearch/hydra/issues/498))
19
+ - Add support for overriding package from command line and defaults list ([#235](https://github.com/facebookresearch/hydra/issues/235))
20
+ - Config source is now abstracted, allowing additional config sources to be used ([#257](https://github.com/facebookresearch/hydra/issues/257))
21
+ - New ConfigSource plugin API allowing configs to be provided by external plugins ([#367](https://github.com/facebookresearch/hydra/issues/367))
22
+ - Add isort to ensure imports are always sorted ([#340](https://github.com/facebookresearch/hydra/issues/340))
23
+ - Codebase is now passing mypy --strict type checking ([#342](https://github.com/facebookresearch/hydra/issues/342))
24
+ - Improve performance of plugin discovery and instantiation ([#489](https://github.com/facebookresearch/hydra/issues/489))
25
+ - Modules whose name starts with "_" are skipped during plugin discovery ([#494](https://github.com/facebookresearch/hydra/issues/494))
26
+
27
+ Plugins
28
+ -------
29
+ - Add [Ax](https://ax.dev) Sweeper plugin ([Shagun Sodhani](https://shagunsodhani.com/))
30
+ - Add [Nevergrad](https://github.com/facebookresearch/nevergrad) Sweeper plugin ([Jérémy Rapin](https://github.com/jrapin))
31
+ - Add [Joblib](https://joblib.readthedocs.io/en/latest/) Launcher plugin ([Jan-Matthis](https://github.com/jan-matthis))
32
+ - Add [Submitit](https://github.com/facebookincubator/submitit) Launcher plugin to launch jobs to SLURM clusters
33
+ - Add [Fish](https://fishshell.com/) shell Tab Completion plugin ([Binsheng Liu](https://binshengliu.github.io/)) ([#549](https://github.com/facebookresearch/hydra/issues/549))
34
+
35
+ API Change (Renames, deprecations and removals)
36
+ -----------------------------------------------
37
+ - Drop support Python 2.7 and 3.5 ([#313](https://github.com/facebookresearch/hydra/issues/313))
38
+ - hydra.main() now takes an additional optional config_name and composite-style config_path is deprecated ([#395](https://github.com/facebookresearch/hydra/issues/395))
39
+ - Launcher API launch method now takes an additional initial_job_idx indicating the id of the first job in the batch ([#284](https://github.com/facebookresearch/hydra/issues/284))
40
+ - Singleton metaclass is now exposed at hydra.core.Singleton ([#371](https://github.com/facebookresearch/hydra/issues/371))
41
+ - Moved HydraConfig from hydra.plugins.common.utils to hydra.core ([#371](https://github.com/facebookresearch/hydra/issues/371))
42
+ - Move several formerly internal APIs to hydra/core to ensure plugins does not need to use internal APIs ([#371](https://github.com/facebookresearch/hydra/issues/371))
43
+ - Plugin import now requires explicit name (from hydra.plugins.launcher import Launcher) ([#371](https://github.com/facebookresearch/hydra/issues/371))
44
+ - Object Config "class" field is deprecated in favor of "cls" and will be removed in a future version. ([#389](https://github.com/facebookresearch/hydra/issues/389))
45
+ - Experimental compose API config_file changed to config_name ([#395](https://github.com/facebookresearch/hydra/issues/395))
46
+ - User plugins should be modified to not import twice during plugin discovery. see issue for details. ([#482](https://github.com/facebookresearch/hydra/issues/482))
47
+ - Change hydra.core.plugins.Plugins class to a Singleton. access should be changed to the pattern Plugins.instance().foo() ([#489](https://github.com/facebookresearch/hydra/issues/489))
48
+ - Plugins should now include test fixtures (sweep_runner, task_runner) via a standardized conftest.py ([#521](https://github.com/facebookresearch/hydra/issues/521))
49
+ - Switch Python 3 native namespace packages for plugins (See task for details) ([#534](https://github.com/facebookresearch/hydra/issues/534))
50
+ - Packaged configuration directories now requires an `__init__.py` at their top level ([#536](https://github.com/facebookresearch/hydra/issues/536))
51
+ - Appending config groups to the defaults list via the command line now requires a + prefix ([#598](https://github.com/facebookresearch/hydra/issues/598))
52
+ - Removing an item from the defaults list by assigning null (db=null) is deprecated, use ~db instead ([#598](https://github.com/facebookresearch/hydra/issues/598))
53
+ - Installed Hydra applications no longer need have an additional `entry()` function on the stack ([#92](https://github.com/facebookresearch/hydra/issues/92))
54
+
55
+ Bug Fixes
56
+ ---------
57
+
58
+ - Fix a bug causing sys.exit() error code to not be propagated ([#351](https://github.com/facebookresearch/hydra/issues/351))
59
+ - Shutdown logging subsystem aftter job finishes to ensure log files are flushed and closed ([#378](https://github.com/facebookresearch/hydra/issues/378))
60
+ - Fix a bug with utils.instantiate() failing if params contains interpolated values. ([#388](https://github.com/facebookresearch/hydra/issues/388))
61
+ - Allow hydra.utils.instantiate() to accept non primitive objects for passthrough by name ([#400](https://github.com/facebookresearch/hydra/issues/400))
62
+ - Fix to work when an Hydra app is executed in Jupyter notebook using the %run command ([#481](https://github.com/facebookresearch/hydra/issues/481))
63
+ - Plugins are no longer imported twice during plugin discovery ([#482](https://github.com/facebookresearch/hydra/issues/482))
64
+ - to_absolute_dir(path) now converts relative path to be relative to os.cwd() when used outside of Hydra ([#496](https://github.com/facebookresearch/hydra/issues/496))
65
+
66
+ Improved Documentation
67
+ ----------------------
68
+
69
+ - Working examples are provided for all Hydra plugins in [plugins/examples](https://github.com/facebookresearch/hydra/tree/master/plugins/examples) ([#253](https://github.com/facebookresearch/hydra/issues/253))
70
+ - The basic tutorial was rewritten to reflect many changes ([#602](https://github.com/facebookresearch/hydra/issues/602))
71
+ - Add a new tutorial covering Structured Configs ([#628](https://github.com/facebookresearch/hydra/issues/628))
72
+
73
+
74
+ 0.11.3 (2019-12-29)
75
+ ===================
76
+
77
+ Bug Fixes
78
+ ---------
79
+
80
+ - Pin Hydra 0.11 to OmegaConf 1.4 to avoid breaking compatibility when OmegaConf 2.0 is released ([#334](https://github.com/facebookresearch/hydra/issues/334))
81
+
82
+ Improved Documentation
83
+ ----------------------
84
+
85
+ - Document a simple Ray example ([#317](https://github.com/facebookresearch/hydra/issues/317))
86
+
87
+
88
+ 0.11.2 (2019-12-04)
89
+ ===================
90
+
91
+ Features
92
+ --------
93
+
94
+ - Change website from cli.dev to hydra.cc (#314)
95
+
96
+ Bug Fixes
97
+ ---------
98
+
99
+ - Fixes --cfg command line flag not working (#305)
100
+
101
+
102
+ 0.11.0 (2019-11-19)
103
+ ===================
104
+
105
+ Features
106
+ --------
107
+
108
+ - Add hydra.experimental API for composing configuration on demand (hydra.experimental.compose) (#219)
109
+ - Add hydra.utils.get_original_cwd() to access original working directory and hydra.utils.to_absolute_path() to convert a path to absolute path (#251)
110
+ - Change hydra logging format pattern, example: "[2019-10-22 16:13:10,769][HYDRA] Installed Hydra Plugins" (#254)
111
+ - Change --cfg to require config type (one of 'job', 'hydra' or 'all') (#270)
112
+ - Upgrade to OmegaConf 1.4.0, see full change log [here](https://github.com/omry/omegaconf/releases/tag/1.4.0) (#280)
113
+ - Experimental support for Jupyter notebooks via compose API (#281)
114
+ - Allow configuring override_dirname via hydra.job.config.override_dirname to exclude specific keys or change separator characters (#95)
115
+
116
+ Bug Fixes
117
+ ---------
118
+
119
+ - Fix a bug that caused out of order composition when mixing config-groups with non-config-group in the defaults block (#261)
120
+ - Allow '=' to be used in the value of an override, eg. foo=bar=10 (key foo, value bar=10). (#266)
121
+ - Allow composing config files with dot in their name (foo.bar.yaml) (#271)
122
+
123
+ Plugins
124
+ -------
125
+
126
+ - hydra-colorlog plugin adds colored log output.
127
+
128
+ Improved Documentation
129
+ ----------------------
130
+
131
+ - Document utils.get_original_cwd() and utils.to_absolute_path("foo") (#251)
132
+
133
+
134
+ 0.10.0 (2019-10-19)
135
+ ===================
136
+
137
+ Configuration structure changes
138
+ -------------------------------
139
+
140
+ - Change the default sweep subdir from ${hydra.job.num}_${hydra.job.id} to ${hydra.job.num} (#150)
141
+
142
+ Features
143
+ --------
144
+
145
+ - App help now contains config groups and generated config
146
+ App help can now be customized
147
+ Hydra help is now available via --hydra-help (#1)
148
+ - Simplify install and uninstall commands for tab completion (#200)
149
+ - hydra.runtime.cwd now contains the original working directory the app was launched from (#244)
150
+
151
+ Bug Fixes
152
+ ---------
153
+
154
+ - Fix an error with tab completion that occurred when a TAB was pressed after two spaces (#203)
155
+ - Fix a bug when sweeping over groups that are used in an interpolation in defaults (#206)
156
+ - Fix tab completion for cases where app name looks like foo.par (#213)
157
+
158
+ Improved Documentation
159
+ ----------------------
160
+
161
+ - Describe news fragment types in more details in development/contributing (#150)
162
+ - Examples dir now mirrors the structure of the website docs (#209)
163
+
164
+
165
+ 0.9.0 (2019-10-01)
166
+ ==================
167
+
168
+ Deprecations and Removals
169
+ -------------------------
170
+
171
+ - Old demos directory was removed and a new tutorial directory as added (#167)
172
+
173
+ Features
174
+ --------
175
+
176
+ - Make strict mode the default when a config file is specified directly (#150)
177
+ - Replace --verbose with a standard override (hydra.verbose) (#161)
178
+ - Add IntegrationTestSuite to test_utils for testing Launcher plugins (#168)
179
+ - Add support for specifying which config to print in -c, options are job (default), hydra or all. (#176)
180
+ - Hydra is now hosted on https://cli.dev! (#75)
181
+ - Move all Hydra configuration files to a subfolder (.hydra by default) under the output folder (#77)
182
+
183
+ Bug Fixes
184
+ ---------
185
+
186
+ - Fix a bug in tab completion of missing mandatory values. (#145)
187
+ - Fix a bug with multirun overriding free config groups (not in defaults) when strict mode is enabled (#181)
188
+ - Fix a bug that prevented sweeping over an unspecified ('???') default group (#187)
189
+
190
+ Improved Documentation
191
+ ----------------------
192
+
193
+ - Updated the primary tutorial on the web site and added a brand new tutorial directory (#58)
194
+ - Documented debugging methods in website (#6)
195
+
196
+
197
+ 0.1.5 (2019-09-22)
198
+ ==================
199
+
200
+ Deprecations and Removals
201
+ -------------------------
202
+
203
+ - Move FAIRTask, Submititit and FAIR-cluster-defaults plugins to fairinternal/hydra-fair-plugins repository (#138)
204
+ - Remove Fairtask and Submitit example configs from demos as they are no longer needed (#146)
205
+
206
+ Features
207
+ --------
208
+
209
+ - Created hydra-core pip package, Hydra can now installed with 'pip install hydra-core' (#143)
210
+ - Finalized submitit support (#18)
211
+
212
+ Plugins
213
+ -------
214
+
215
+ - Add default launcher config for Fairtask and Submitit launcher plugins
216
+
217
+
218
+ 0.1.4 (2019-09-18)
219
+ ==================
220
+
221
+ Features
222
+ --------
223
+
224
+ - hydra.utils.instantiate() can now take an additional optional kwargs dictionary to pass to constructor of the instantiated object (#142)
225
+ - Initial support for bash completion, see documentation for details (#8)
226
+
227
+ Bug Fixes
228
+ ---------
229
+
230
+ - Fixed Town Crier to generate correct links to issues in generated news file. (#122)
231
+ - Fixed bug with overriding hydra defaults from user config file. (#123)
232
+ - Fixed Singletons not getting serialized to remote jobs. (#128)
233
+ - Fixed a bug that prevented using submitit in strict mode (#129)
234
+ - Fixed example submitit config to set the job name (#133)
235
+
236
+
237
+ 0.1.3 (2019-09-02)
238
+ ==================
239
+
240
+ Configuration structure changes
241
+ -------------------------------
242
+
243
+ - Changed Hydra core defaults to be more appropriate for open source use. To get the FAIR cluster defaults install the fair_cluster plugin (#103)
244
+ - Changed output directories default to group by day (output/DAY/TIME instead of output/DAY_TIME) (#121)
245
+
246
+ Features
247
+ --------
248
+
249
+ - Added the ability to prevent a default from being merged it by assigning null to it (hydra/launcher=null) (#106)
250
+ - Implemented Plugin discovery mechanism, this can be used to find all installed plugins that implement a specific interface (#119)
251
+ - Implemented an API to for manipulating the config search path (#120)
252
+
253
+ Bug Fixes
254
+ ---------
255
+
256
+ - Fixed config loading to properly support the use case in demos/8_specializing_config (#104)
257
+ - Fixed error message when the user config contains defaults that is a mapping and not a list (#107)
258
+ - Fixed config loading order to allow properly overriding Hydra config groups from user config (#115)
259
+
260
+ Plugins
261
+ -------
262
+
263
+ - New plugin: fair_cluster
264
+ Change Hydra defaults to be appropriate for the FAIR cluster
265
+
266
+ Improved Documentation
267
+ ----------------------
268
+
269
+ - Initial search path and plugins documentation (#103)
270
+
271
+
272
+ 0.1.2 (2019-08-26)
273
+ ==================
274
+
275
+ Deprecations and Removals
276
+ -------------------------
277
+
278
+ - Hydra config groups were moved to the hydra/namespace (#101)
279
+ - Removed support for .hydra directory, Hydra can be configured directly from the job config. (#91)
280
+
281
+ Bug Fixes
282
+ ---------
283
+
284
+ - Config loading rewrite fixed #88 (#88)
285
+
286
+
287
+ 0.1.1 (2019-08-22)
288
+ ==================
289
+
290
+ Deprecations and Removals
291
+ -------------------------
292
+
293
+ - Move non-public APIs into hydra._internal:
294
+ - Moved non-API code into hydra._interanl to flag it as private.
295
+ - Moved plugin interfaces into hydra.plugins.
296
+ - Moved code meant to be used by plugins to hydra.plugins.common. (#78)
297
+
298
+ Features
299
+ --------
300
+
301
+ - Integrated towncrier to bring you this news! (#45)
302
+ - Hydra is now compatible with Windows (#63)
303
+ - Hydra apps can now be packaged and installed along with their configuration files. (#87)
304
+
305
+ Bug Fixes
306
+ ---------
307
+
308
+ - It is now possible to use ${override_dirname} in the output directory of a local job (#31)
309
+ - Override_dirname separator changed from : to =, for example: foo/a:10,b:10 => foo/a=10,b=10 (#63)
310
+ - Fixed automatic detection of missing copyright headers (#72)
311
+ - fixed a bug that caused an empty config to be returned if specifed config file did not have a .yaml extension. (#80)
312
+ - Multi change diff:
313
+ - Logging config search path in verbose logging to assist debugging of config load issues
314
+ - Saving hydra.yaml into the job dir to assist debugging hydra issues
315
+ - Fixed a bug caused by fairtask logging change
316
+ - Improved integration-tests debuggability by switching hydra to debug logging in them
317
+ - Added selective plugin testing to nox using env, for example PLUGINS=fairtask would only test fairtask. (#87)
318
+
319
+ Improved Documentation
320
+ ----------------------
321
+
322
+ - Improved the contributing docs (#45)
323
+ - Documented Hydra app packaging under Deployment/Application packaging (#87)
testbed/facebookresearch__hydra/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [![PyPI](https://img.shields.io/pypi/v/hydra-core)](https://pypi.org/project/hydra-core/)
2
+ [![CircleCI](https://img.shields.io/circleci/build/github/facebookresearch/hydra?token=af199cd2deca9e70e53776f9ded96284b10687e9)](https://circleci.com/gh/facebookresearch/hydra)
3
+ ![PyPI - License](https://img.shields.io/pypi/l/hydra-core)
4
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hydra-core)
5
+ [![Downloads](https://pepy.tech/badge/hydra-core/month)](https://pepy.tech/project/hydra-core/month?versions=0.11.*&versions=1.0.*)
6
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
7
+ [![Total alerts](https://img.shields.io/lgtm/alerts/g/facebookresearch/hydra.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/facebookresearch/hydra/alerts/)
8
+ [![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/facebookresearch/hydra.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/facebookresearch/hydra/context:python)
9
+ [![](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://hydra-framework.zulipchat.com)
10
+
11
+ # Hydra
12
+ A framework for elegantly configuring complex applications.
13
+
14
+ Check the [website](https://hydra.cc/) for more information.
15
+
16
+ ### Releases
17
+ #### Stable
18
+ **Hydra 0.11** is the stable version of Hydra.
19
+ - [Documentation](https://hydra.cc/docs/intro)
20
+ - Installation : `pip install hydra-core --upgrade`
21
+
22
+ #### Release candidate
23
+ **Hydra 1.0** is the next major version of Hydra. It is currently a release candidate.
24
+ Please report any issues.
25
+ - [Release notes](https://github.com/facebookresearch/hydra/releases/tag/hydra-1.0.0rc1)
26
+ - [Documentation](https://hydra.cc/docs/next/intro)
27
+ - Installation : `pip install hydra-core --upgrade --pre`
28
+
29
+ ### License
30
+ Hydra is licensed under [MIT License](LICENSE).
31
+
32
+ ## Community
33
+ Ask questions in the chat or StackOverflow (Use the tag #fb-hydra or #omegaconf):
34
+ * [Chat](https://hydra-framework.zulipchat.com)
35
+ * [StackOverflow](https://stackexchange.com/filters/391828/hydra-questions)
36
+ * [Twitter](https://twitter.com/Hydra_Framework)
37
+
38
+
39
+ ### Citing Hydra
40
+ If you use Hydra in your research please use the following BibTeX entry:
41
+ ```text
42
+ @Misc{,
43
+ author = {Omry Yadan},
44
+ title = {A framework for elegantly configuring complex applications},
45
+ howpublished = {Github},
46
+ year = {2019},
47
+ url = {https://github.com/facebookresearch/hydra}
48
+ }
49
+ ```
testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/MANIFEST.in ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ include hydra_pytest_plugin/py.typed
2
+ global-exclude *.pyc
3
+ global-exclude __pycache__
testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Hydra pytest plugin
2
+
3
+ This plugin adds common Hydra related pytest fixtures.
4
+
5
+ NOTE: The fixtures are currently experimental are likely to change with a future version of Hydra.
testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/__init__.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ # Source of truth for version
3
+ __version__ = "1.0.0rc1"
4
+ import copy
5
+ from typing import Callable, List, Optional
6
+
7
+ import pytest
8
+
9
+ from hydra.core.singleton import Singleton
10
+ from hydra.test_utils.test_utils import SweepTaskFunction, TaskTestFunction
11
+ from hydra.types import TaskFunction
12
+
13
+
14
+ @pytest.fixture(scope="function") # type: ignore
15
+ def hydra_restore_singletons() -> None:
16
+ """
17
+ Restore singletons state after the function returns
18
+ """
19
+ state = copy.deepcopy(Singleton.get_state())
20
+ yield
21
+ Singleton.set_state(state)
22
+
23
+
24
+ @pytest.fixture(scope="function") # type: ignore
25
+ def hydra_sweep_runner() -> Callable[
26
+ [
27
+ Optional[str],
28
+ Optional[str],
29
+ Optional[TaskFunction],
30
+ Optional[str],
31
+ Optional[str],
32
+ Optional[List[str]],
33
+ Optional[bool],
34
+ ],
35
+ SweepTaskFunction,
36
+ ]:
37
+ def _(
38
+ calling_file: Optional[str],
39
+ calling_module: Optional[str],
40
+ task_function: Optional[TaskFunction],
41
+ config_path: Optional[str],
42
+ config_name: Optional[str],
43
+ overrides: Optional[List[str]],
44
+ strict: Optional[bool] = None,
45
+ ) -> SweepTaskFunction:
46
+ sweep = SweepTaskFunction()
47
+ sweep.calling_file = calling_file
48
+ sweep.calling_module = calling_module
49
+ sweep.task_function = task_function
50
+ sweep.config_path = config_path
51
+ sweep.config_name = config_name
52
+ sweep.strict = strict
53
+ sweep.overrides = overrides or []
54
+ return sweep
55
+
56
+ return _
57
+
58
+
59
+ @pytest.fixture(scope="function") # type: ignore
60
+ def hydra_task_runner() -> Callable[
61
+ [
62
+ Optional[str],
63
+ Optional[str],
64
+ Optional[str],
65
+ Optional[str],
66
+ Optional[List[str]],
67
+ Optional[bool],
68
+ ],
69
+ TaskTestFunction,
70
+ ]:
71
+ def _(
72
+ calling_file: Optional[str],
73
+ calling_module: Optional[str],
74
+ config_path: Optional[str],
75
+ config_name: Optional[str],
76
+ overrides: Optional[List[str]] = None,
77
+ strict: Optional[bool] = None,
78
+ ) -> TaskTestFunction:
79
+ task = TaskTestFunction()
80
+ task.overrides = overrides or []
81
+ task.calling_file = calling_file
82
+ task.config_name = config_name
83
+ task.calling_module = calling_module
84
+ task.config_path = config_path
85
+ task.strict = strict
86
+ return task
87
+
88
+ return _
testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/py.typed ADDED
File without changes
testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/setup.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ import codecs
3
+ import os
4
+ import re
5
+
6
+ from setuptools import find_packages, setup
7
+
8
+
9
+ def find_version(*file_paths):
10
+ here = os.path.abspath(os.path.dirname(__file__))
11
+ with codecs.open(os.path.join(here, *file_paths), "r") as fp:
12
+ version_file = fp.read()
13
+ version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
14
+ if version_match:
15
+ return version_match.group(1)
16
+ raise RuntimeError("Unable to find version string.")
17
+
18
+
19
+ with open("README.md", "r") as fh:
20
+ LONG_DESC = fh.read()
21
+ setup(
22
+ name="hydra-pytest-plugin",
23
+ version=find_version("hydra_pytest_plugin", "__init__.py"),
24
+ author="Omry Yadan",
25
+ author_email="omry@fb.com",
26
+ description="Hydra pytest plugin",
27
+ long_description=LONG_DESC,
28
+ long_description_content_type="text/markdown",
29
+ url="https://github.com/facebookresearch/hydra/",
30
+ packages=find_packages(include=["hydra_pytest_plugin"]),
31
+ classifiers=["License :: OSI Approved :: MIT License", "Framework :: Pytest"],
32
+ install_requires=["hydra-core~=1.0.0rc1"],
33
+ # the following makes a plugin available to pytest
34
+ entry_points={"pytest11": ["name_of_plugin = hydra_pytest_plugin"]},
35
+ )
testbed/facebookresearch__hydra/lgtm.yml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ queries:
2
+ - exclude: py/import-own-module
testbed/facebookresearch__hydra/noxfile.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ # type: ignore
3
+ import copy
4
+ import os
5
+ import platform
6
+ from dataclasses import dataclass
7
+ from typing import List
8
+
9
+ import nox
10
+ from nox.logger import logger
11
+
12
+ BASE = os.path.abspath(os.path.dirname(__file__))
13
+
14
+ DEFAULT_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"]
15
+ DEFAULT_OS_NAMES = ["Linux", "MacOS", "Windows"]
16
+
17
+ PYTHON_VERSIONS = os.environ.get(
18
+ "NOX_PYTHON_VERSIONS", ",".join(DEFAULT_PYTHON_VERSIONS)
19
+ ).split(",")
20
+
21
+ PLUGINS_INSTALL_COMMANDS = (["pip", "install"], ["pip", "install", "-e"])
22
+
23
+ # Allow limiting testing to specific plugins
24
+ # The list ['ALL'] indicates all plugins
25
+ PLUGINS = os.environ.get("PLUGINS", "ALL").split(",")
26
+
27
+ SKIP_CORE_TESTS = "0"
28
+ SKIP_CORE_TESTS = os.environ.get("SKIP_CORE_TESTS", SKIP_CORE_TESTS) != "0"
29
+ FIX = os.environ.get("FIX", "0") == "1"
30
+ VERBOSE = os.environ.get("VERBOSE", "0")
31
+ SILENT = VERBOSE == "0"
32
+
33
+
34
+ @dataclass
35
+ class Plugin:
36
+ name: str
37
+ path: str
38
+ module: str
39
+
40
+
41
+ def get_current_os() -> str:
42
+ current_os = platform.system()
43
+ if current_os == "Darwin":
44
+ current_os = "MacOS"
45
+ return current_os
46
+
47
+
48
+ print(f"Operating system\t:\t{get_current_os()}")
49
+ print(f"NOX_PYTHON_VERSIONS\t:\t{PYTHON_VERSIONS}")
50
+ print(f"PLUGINS\t\t\t:\t{PLUGINS}")
51
+ print(f"SKIP_CORE_TESTS\t\t:\t{SKIP_CORE_TESTS}")
52
+ print(f"FIX\t\t\t:\t{FIX}")
53
+ print(f"VERBOSE\t\t\t:\t{VERBOSE}")
54
+
55
+
56
+ def _upgrade_basic(session):
57
+ session.run(
58
+ "python",
59
+ "-m",
60
+ "pip",
61
+ "install",
62
+ "--upgrade",
63
+ "setuptools",
64
+ "pip",
65
+ silent=SILENT,
66
+ )
67
+
68
+
69
+ def find_python_files_for_mypy(folder):
70
+ exclude_list = [""]
71
+
72
+ def excluded(file: str) -> bool:
73
+ for exclude in exclude_list:
74
+ if file.startswith(exclude):
75
+ return True
76
+ return False
77
+
78
+ for root, folders, files in os.walk(folder):
79
+ for filename in folders + files:
80
+ if filename.endswith(".py"):
81
+ if excluded(filename):
82
+ yield os.path.join(root, filename)
83
+
84
+
85
+ def install_hydra(session, cmd):
86
+ # clean install hydra
87
+ session.chdir(BASE)
88
+ session.run(*cmd, ".", silent=SILENT)
89
+ session.run(*cmd, "extra/hydra-pytest-plugin", silent=SILENT)
90
+ if not SILENT:
91
+ session.install("pipdeptree", silent=SILENT)
92
+ session.run("pipdeptree", "-p", "hydra-core")
93
+
94
+
95
+ def pytest_args(session, *args):
96
+ ret = ["pytest", "-Werror"]
97
+ ret.extend(args)
98
+ if len(session.posargs) > 0:
99
+ ret.extend(session.posargs)
100
+ return ret
101
+
102
+
103
+ def run_pytest(session, directory=".", *args):
104
+ pytest_cmd = pytest_args(session, directory, *args)
105
+ session.run(*pytest_cmd, silent=SILENT)
106
+
107
+
108
+ def get_setup_python_versions(classifiers):
109
+ pythons = filter(lambda line: "Programming Language :: Python" in line, classifiers)
110
+ return [p[len("Programming Language :: Python :: ") :] for p in pythons]
111
+
112
+
113
+ def get_plugin_os_names(classifiers: List[str]) -> List[str]:
114
+ oses = list(filter(lambda line: "Operating System" in line, classifiers))
115
+ if len(oses) == 0:
116
+ # No Os is specified so all oses are supported
117
+ return DEFAULT_OS_NAMES
118
+ if len(oses) == 1 and oses[0] == "Operating System :: OS Independent":
119
+ # All oses are supported
120
+ return DEFAULT_OS_NAMES
121
+ else:
122
+ return [p.split("::")[-1].strip() for p in oses]
123
+
124
+
125
+ def select_plugins(session) -> List[Plugin]:
126
+ """
127
+ Select all plugins that should be tested in this session.
128
+ Considers the current Python version and operating systems against the supported ones,
129
+ as well as the user plugins selection (via the PLUGINS environment variable).
130
+ """
131
+
132
+ assert session.python is not None, "Session python version is not specified"
133
+ blacklist = [".isort.cfg"]
134
+ example_plugins = [
135
+ {"dir_name": x, "path": f"examples/{x}"}
136
+ for x in sorted(os.listdir(os.path.join(BASE, "plugins/examples")))
137
+ if x not in blacklist
138
+ ]
139
+ plugins = [
140
+ {"dir_name": x, "path": x}
141
+ for x in sorted(os.listdir(os.path.join(BASE, "plugins")))
142
+ if x != "examples"
143
+ if x not in blacklist
144
+ ]
145
+ available_plugins = plugins + example_plugins
146
+
147
+ ret = []
148
+ skipped = []
149
+ for plugin in available_plugins:
150
+ if not (plugin["dir_name"] in PLUGINS or PLUGINS == ["ALL"]):
151
+ skipped.append(f"Deselecting {plugin['dir_name']}: User request")
152
+ continue
153
+
154
+ setup_py = os.path.join(BASE, "plugins", plugin["path"], "setup.py")
155
+ classifiers = session.run(
156
+ "python", setup_py, "--name", "--classifiers", silent=True
157
+ ).splitlines()
158
+ plugin_name = classifiers.pop(0)
159
+ plugin_python_versions = get_setup_python_versions(classifiers)
160
+ python_supported = session.python in plugin_python_versions
161
+
162
+ plugin_os_names = get_plugin_os_names(classifiers)
163
+ os_supported = get_current_os() in plugin_os_names
164
+
165
+ if not python_supported:
166
+ py_str = ", ".join(plugin_python_versions)
167
+ skipped.append(
168
+ f"Deselecting {plugin['dir_name']} : Incompatible Python {session.python}. Supports [{py_str}]"
169
+ )
170
+ continue
171
+
172
+ # Verify this plugin supports the OS we are testing on, skip otherwise
173
+ if not os_supported:
174
+ os_str = ", ".join(plugin_os_names)
175
+ skipped.append(
176
+ f"Deselecting {plugin['dir_name']}: Incompatible OS {get_current_os()}. Supports [{os_str}]"
177
+ )
178
+ continue
179
+
180
+ ret.append(
181
+ Plugin(
182
+ name=plugin_name,
183
+ path=plugin["path"],
184
+ module="hydra_plugins." + plugin["dir_name"],
185
+ )
186
+ )
187
+
188
+ for msg in skipped:
189
+ logger.warn(msg)
190
+
191
+ if len(ret) == 0:
192
+ logger.warn("No plugins selected")
193
+ return ret
194
+
195
+
196
+ def install_lint_deps(session):
197
+ _upgrade_basic(session)
198
+ session.run("pip", "install", "-r", "requirements/dev.txt", silent=SILENT)
199
+ session.run("pip", "install", "-e", ".", silent=SILENT)
200
+
201
+
202
+ @nox.session(python=PYTHON_VERSIONS)
203
+ def lint(session):
204
+ install_lint_deps(session)
205
+ install_hydra(session, ["pip", "install", "-e"])
206
+ session.run("black", "--check", ".", silent=SILENT)
207
+ session.run(
208
+ "isort",
209
+ "--check",
210
+ "--diff",
211
+ ".",
212
+ "--skip=plugins",
213
+ "--skip=.nox",
214
+ silent=SILENT,
215
+ )
216
+ session.run("mypy", ".", "--strict", silent=SILENT)
217
+ session.run("flake8", "--config", ".flake8")
218
+ session.run("yamllint", ".")
219
+ # Mypy for examples
220
+ for pyfile in find_python_files_for_mypy("examples"):
221
+ session.run("mypy", pyfile, "--strict", silent=SILENT)
222
+
223
+
224
+ @nox.session(python=PYTHON_VERSIONS)
225
+ def lint_plugins(session):
226
+
227
+ install_cmd = ["pip", "install", "-e"]
228
+ install_hydra(session, install_cmd)
229
+ plugins = select_plugins(session)
230
+
231
+ # plugin linting requires the plugins and their dependencies to be installed
232
+ for plugin in plugins:
233
+ cmd = install_cmd + [os.path.join("plugins", plugin.path)]
234
+ session.run(*cmd, silent=SILENT)
235
+
236
+ install_lint_deps(session)
237
+
238
+ session.run("flake8", "--config", ".flake8", "plugins")
239
+ # Mypy for plugins
240
+ for plugin in plugins:
241
+ session.chdir(os.path.join("plugins", plugin.path))
242
+ blackcmd = ["black", "."]
243
+ isortcmd = ["isort", "."]
244
+ if not FIX:
245
+ blackcmd += ["--check"]
246
+ isortcmd += ["--check", "--diff"]
247
+ session.run(*blackcmd, silent=SILENT)
248
+ session.run(*isortcmd, silent=SILENT)
249
+ session.chdir(BASE)
250
+
251
+ session.run("mypy", ".", "--strict", silent=SILENT)
252
+
253
+
254
+ @nox.session(python=PYTHON_VERSIONS)
255
+ @nox.parametrize(
256
+ "install_cmd",
257
+ PLUGINS_INSTALL_COMMANDS,
258
+ ids=[" ".join(x) for x in PLUGINS_INSTALL_COMMANDS],
259
+ )
260
+ def test_core(session, install_cmd):
261
+ _upgrade_basic(session)
262
+ install_hydra(session, install_cmd)
263
+ session.install("pytest")
264
+
265
+ run_pytest(session, "tests")
266
+
267
+ # test discovery_test_plugin
268
+ run_pytest(session, "tests/test_plugins/discovery_test_plugin", "--noconftest")
269
+
270
+ # run namespace config loader tests
271
+ run_pytest(session, "tests/test_plugins/namespace_pkg_config_source_test")
272
+
273
+ # Install and test example app
274
+ session.chdir(f"{BASE}/examples/advanced/hydra_app_example")
275
+ session.run(*install_cmd, ".", silent=SILENT)
276
+ run_pytest(session, ".")
277
+
278
+
279
+ @nox.session(python=PYTHON_VERSIONS)
280
+ @nox.parametrize(
281
+ "install_cmd",
282
+ PLUGINS_INSTALL_COMMANDS,
283
+ ids=[" ".join(x) for x in PLUGINS_INSTALL_COMMANDS],
284
+ )
285
+ def test_plugins(session, install_cmd):
286
+ _upgrade_basic(session)
287
+ session.install("pytest")
288
+ install_hydra(session, install_cmd)
289
+ selected_plugin = select_plugins(session)
290
+ for plugin in selected_plugin:
291
+ cmd = list(install_cmd) + [os.path.join("plugins", plugin.path)]
292
+ session.run(*cmd, silent=SILENT)
293
+ if not SILENT:
294
+ session.run("pipdeptree", "-p", plugin.name)
295
+
296
+ # Test that we can import Hydra
297
+ session.run("python", "-c", "from hydra import main", silent=SILENT)
298
+
299
+ # Test that we can import all installed plugins
300
+ for plugin in selected_plugin:
301
+ session.run("python", "-c", f"import {plugin.module}")
302
+
303
+ # Run Hydra tests to verify installed plugins did not break anything
304
+ if not SKIP_CORE_TESTS:
305
+ run_pytest(session, "tests")
306
+ else:
307
+ session.log("Skipping Hydra core tests")
308
+
309
+ # Run tests for all installed plugins
310
+ for plugin in selected_plugin:
311
+ # install all other plugins that are compatible with the current Python version
312
+ session.chdir(os.path.join(BASE, "plugins", plugin.path))
313
+ run_pytest(session)
314
+
315
+
316
+ @nox.session(python="3.8")
317
+ def coverage(session):
318
+ coverage_env = {
319
+ "COVERAGE_HOME": BASE,
320
+ "COVERAGE_FILE": f"{BASE}/.coverage",
321
+ "COVERAGE_RCFILE": f"{BASE}/.coveragerc",
322
+ }
323
+
324
+ _upgrade_basic(session)
325
+ session.install("coverage", "pytest")
326
+ install_hydra(session, ["pip", "install", "-e"])
327
+ session.run("coverage", "erase")
328
+
329
+ selected_plugins = select_plugins(session)
330
+ for plugin in selected_plugins:
331
+ session.run(
332
+ "pip", "install", "-e", os.path.join("plugins", plugin.path), silent=SILENT,
333
+ )
334
+
335
+ session.run("coverage", "erase", env=coverage_env)
336
+ # run plugin coverage
337
+ for plugin in selected_plugins:
338
+ session.chdir(os.path.join("plugins", plugin.path))
339
+ cov_args = ["coverage", "run", "--append", "-m"]
340
+ cov_args.extend(pytest_args(session))
341
+ session.run(*cov_args, silent=SILENT, env=coverage_env)
342
+ session.chdir(BASE)
343
+
344
+ # run hydra-core coverage
345
+ session.run(
346
+ "coverage",
347
+ "run",
348
+ "--append",
349
+ "-m",
350
+ silent=SILENT,
351
+ env=coverage_env,
352
+ *pytest_args(session),
353
+ )
354
+
355
+ # Increase the fail_under as coverage improves
356
+ session.run("coverage", "report", "--fail-under=80", env=coverage_env)
357
+ session.run("coverage", "erase", env=coverage_env)
358
+
359
+
360
+ @nox.session(python=PYTHON_VERSIONS)
361
+ def test_jupyter_notebooks(session):
362
+ versions = copy.copy(DEFAULT_PYTHON_VERSIONS)
363
+ if session.python not in versions:
364
+ session.skip(
365
+ f"Not testing Jupyter notebook on Python {session.python}, supports [{','.join(versions)}]"
366
+ )
367
+ # pyzmq 19.0.1 has installation issues on Windows
368
+ session.install("jupyter", "nbval", "pyzmq==19.0.0")
369
+ install_hydra(session, ["pip", "install", "-e"])
370
+ args = pytest_args(
371
+ session, "--nbval", "examples/notebook/hydra_notebook_example.ipynb"
372
+ )
373
+ # Jupyter notebook test on Windows yield warnings
374
+ args = [x for x in args if x != "-Werror"]
375
+ session.run(*args, silent=SILENT)
376
+
377
+ args = pytest_args(session, "--nbval", "examples/notebook/%run_test.ipynb")
378
+ args = [x for x in args if x != "-Werror"]
379
+ session.run(*args, silent=SILENT)
testbed/facebookresearch__hydra/pyproject.toml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.towncrier]
2
+ package = "hydra"
3
+ package_dir = ""
4
+ filename = "NEWS.md"
5
+ directory = "news/"
6
+ title_format = "{version} ({project_date})"
7
+ template = "news/_template.rst"
8
+ issue_format = "[#{issue}](https://github.com/facebookresearch/hydra/issues/{issue})"
9
+ start_string = "<!-- TOWNCRIER -->\n"
10
+
11
+ [[tool.towncrier.type]]
12
+ directory = "feature"
13
+ name = "Features"
14
+ showcontent = true
15
+
16
+ [[tool.towncrier.type]]
17
+ directory = "api_change"
18
+ name = "API Change (Renames, deprecations and removals)"
19
+ showcontent = true
20
+
21
+ [[tool.towncrier.type]]
22
+ directory = "bugfix"
23
+ name = "Bug Fixes"
24
+ showcontent = true
25
+
26
+ [[tool.towncrier.type]]
27
+ directory = "plugin"
28
+ name = "Plugins"
29
+ showcontent = true
30
+
31
+ [[tool.towncrier.type]]
32
+ directory = "config"
33
+ name = "Configuration structure changes"
34
+ showcontent = true
35
+
36
+ [[tool.towncrier.type]]
37
+ directory = "docs"
38
+ name = "Improved Documentation"
39
+ showcontent = true
40
+
41
+ [[tool.towncrier.type]]
42
+ directory = "trivial"
43
+ name = "Trivial Changes"
44
+ showcontent = false
45
+
46
+ [[tool.towncrier.type]]
47
+ directory = "maintenance"
48
+ name = "Maintenance Changes"
49
+ showcontent = true
testbed/facebookresearch__hydra/pytest.ini ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [pytest]
2
+ # reasons for excludes:
3
+ # .nox: large and irrelevant
4
+ # plugins: tested separately
5
+ # examples: contains the test for the example app, tested separately (app needs to be installed first)
6
+ # website: No python code
7
+ # tests/test_plugins : tested separately
8
+ norecursedirs = .nox plugins examples website tests/test_plugins build
testbed/facebookresearch__hydra/setup.cfg ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [mypy]
2
+ python_version = 3.6
3
+ mypy_path=.stubs
testbed/facebookresearch__hydra/setup.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ # type: ignore
3
+ import codecs
4
+ import os
5
+ import pathlib
6
+ import re
7
+ import shutil
8
+ from distutils import cmd
9
+ from os.path import exists, isdir, join
10
+ from typing import Any, List
11
+
12
+ import pkg_resources
13
+ from setuptools import find_packages, setup
14
+
15
+
16
+ def find_version(*file_paths):
17
+ here = os.path.abspath(os.path.dirname(__file__))
18
+ with codecs.open(os.path.join(here, *file_paths), "r") as fp:
19
+ version_file = fp.read()
20
+ version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
21
+ if version_match:
22
+ return version_match.group(1)
23
+ raise RuntimeError("Unable to find version string.")
24
+
25
+
26
+ with pathlib.Path("requirements/requirements.txt").open() as requirements_txt:
27
+ install_requires = [
28
+ str(requirement)
29
+ for requirement in pkg_resources.parse_requirements(requirements_txt)
30
+ ]
31
+
32
+
33
+ class CleanCommand(cmd.Command):
34
+ """
35
+ Our custom command to clean out junk files.
36
+ """
37
+
38
+ description = "Cleans out junk files we don't want in the repo"
39
+ user_options: List[Any] = []
40
+
41
+ def initialize_options(self):
42
+ pass
43
+
44
+ def finalize_options(self):
45
+ pass
46
+
47
+ @staticmethod
48
+ def find(root, includes, excludes=[]):
49
+ res = []
50
+ for parent, dirs, files in os.walk(root):
51
+ for f in dirs + files:
52
+ add = list()
53
+ for include in includes:
54
+ if re.findall(include, f):
55
+ add.append(join(parent, f))
56
+ res.extend(add)
57
+ final_list = []
58
+ # Exclude things that matches an exclude pattern
59
+ for ex in excludes:
60
+ for file in res:
61
+ if not re.findall(ex, file):
62
+ final_list.append(file)
63
+ return final_list
64
+
65
+ def run(self):
66
+ delete_patterns = [
67
+ ".eggs",
68
+ ".egg-info",
69
+ ".pytest_cache",
70
+ "build",
71
+ "dist",
72
+ "__pycache__",
73
+ ".pyc",
74
+ ]
75
+ deletion_list = CleanCommand.find(
76
+ ".", includes=delete_patterns, excludes=["\\.nox/.*"]
77
+ )
78
+
79
+ for f in deletion_list:
80
+ if exists(f):
81
+ if isdir(f):
82
+ shutil.rmtree(f, ignore_errors=True)
83
+ else:
84
+ os.unlink(f)
85
+
86
+
87
+ with open("README.md", "r") as fh:
88
+ LONG_DESC = fh.read()
89
+ setup(
90
+ cmdclass={"clean": CleanCommand},
91
+ name="hydra-core",
92
+ version=find_version("hydra", "__init__.py"),
93
+ author="Omry Yadan",
94
+ author_email="omry@fb.com",
95
+ description="A framework for elegantly configuring complex applications",
96
+ long_description=LONG_DESC,
97
+ long_description_content_type="text/markdown",
98
+ url="https://github.com/facebookresearch/hydra",
99
+ keywords="command-line configuration yaml tab-completion",
100
+ packages=find_packages(include=["hydra"]),
101
+ include_package_data=True,
102
+ classifiers=[
103
+ "License :: OSI Approved :: MIT License",
104
+ "Development Status :: 4 - Beta",
105
+ "Programming Language :: Python :: 3.6",
106
+ "Programming Language :: Python :: 3.7",
107
+ "Programming Language :: Python :: 3.8",
108
+ "Operating System :: POSIX :: Linux",
109
+ "Operating System :: MacOS",
110
+ "Operating System :: Microsoft :: Windows",
111
+ ],
112
+ install_requires=install_requires,
113
+ # Install development dependencies with
114
+ # pip install -r requirements/dev.txt -e .
115
+ )
testbed/facebookresearch__hydra/tests/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ from hydra.core.utils import verify_pytest_plugin_version
3
+
4
+ verify_pytest_plugin_version()
testbed/facebookresearch__hydra/tests/scripts/test_bash_completion.exp ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ log_user 0
3
+ set timeout 4
4
+ set env(PS1) >>
5
+
6
+ # Under pycharm, for some unknown reason readline displays
7
+ # the suggestions in a different order, breaking the test.
8
+ # This enables debug output from Hydra which is easier to test
9
+ set env(HYDRA_COMP_DEBUG) 1
10
+ set env(INPUTRC) /dev/null
11
+
12
+ # Suppress bash deprecation warning on Mac
13
+ set env(BASH_SILENCE_DEPRECATION_WARNING) 1
14
+
15
+ # parray env
16
+
17
+ spawn bash --norc --noprofile
18
+ expect >>
19
+
20
+ set in_line [lindex $argv 1]
21
+ set len [expr [string length $in_line] - 1]
22
+ set line [string range $in_line 5 $len]
23
+ set num_tabs [lindex $argv 2]
24
+ puts "input line: '$line'"
25
+ puts "num_tabs: $num_tabs"
26
+
27
+ send "eval \"\$([lindex $argv 0] -sc install=bash)\"\r"
28
+ expect >>
29
+
30
+ set command "[lindex $argv 0] $line"
31
+ while {$num_tabs > 0} {
32
+ incr num_tabs -1
33
+ append command "\t"
34
+ }
35
+
36
+ puts "command: '$command'"
37
+
38
+ send $command
39
+
40
+ puts "\nMatching:\n"
41
+ foreach arg [lrange $argv 3 end] {
42
+ expect {
43
+ "$arg" {puts "matched '$arg' to '$expect_out(0,string)'\nbuffer: '$expect_out(buffer)'";continue}
44
+ timeout {puts "Error matching $arg"; exit 1}
45
+ }
46
+ }
testbed/facebookresearch__hydra/tests/test_apps/app_with_cfg_groups/conf/dataset/imagenet.yaml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # @package _global_
2
+ dataset:
3
+ name: imagenet
4
+ path: /datasets/imagenet
testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/config.yaml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # @package _global_
2
+ defaults:
3
+ - group: opt1
testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/group/opt1.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # @package _global_
2
+ group_opt1: true
testbed/facebookresearch__hydra/tests/test_basic_launcher.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ import pytest
3
+
4
+ from hydra.test_utils.launcher_common_tests import (
5
+ BatchedSweeperTestSuite,
6
+ IntegrationTestSuite,
7
+ LauncherTestSuite,
8
+ )
9
+
10
+
11
+ @pytest.mark.parametrize("launcher_name, overrides", [("basic", [])])
12
+ class TestBasicLauncher(LauncherTestSuite):
13
+ pass
14
+
15
+
16
+ @pytest.mark.parametrize(
17
+ "task_launcher_cfg, extra_flags",
18
+ [
19
+ pytest.param(
20
+ {
21
+ "defaults": [
22
+ {"hydra/launcher": "basic"},
23
+ {"hydra/hydra_logging": "hydra_debug"},
24
+ {"hydra/job_logging": "disabled"},
25
+ ]
26
+ },
27
+ ["-m"],
28
+ id="basic_launcher_multirun",
29
+ )
30
+ ],
31
+ )
32
+ class TestBasicLauncherIntegration(IntegrationTestSuite):
33
+ """
34
+ Run this launcher through the integration test suite.
35
+ """
36
+
37
+ pass
38
+
39
+
40
+ @pytest.mark.parametrize(
41
+ "launcher_name, overrides",
42
+ [("basic", ["hydra/sweeper=basic", "hydra.sweeper.params.max_batch_size=2"])],
43
+ )
44
+ class TestBasicSweeperWithBatching(BatchedSweeperTestSuite):
45
+ ...
testbed/facebookresearch__hydra/tests/test_completion.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ import distutils.spawn
3
+ import os
4
+ import re
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import List
9
+
10
+ import pytest
11
+ from packaging import version
12
+
13
+ from hydra._internal.config_loader_impl import ConfigLoaderImpl
14
+ from hydra._internal.core_plugins.bash_completion import BashCompletion
15
+ from hydra._internal.utils import create_config_search_path
16
+ from hydra.plugins.completion_plugin import DefaultCompletionPlugin
17
+ from hydra.test_utils.test_utils import chdir_hydra_root
18
+
19
+ chdir_hydra_root()
20
+
21
+
22
+ def is_expect_exists() -> bool:
23
+ return distutils.spawn.find_executable("expect") is not None
24
+
25
+
26
+ def is_fish_supported() -> bool:
27
+ if distutils.spawn.find_executable("fish") is None:
28
+ return False
29
+
30
+ proc = subprocess.run(
31
+ ["fish", "--version"], stdout=subprocess.PIPE, encoding="utf-8"
32
+ )
33
+ matches = re.match(r".*version\s+(\d\.\d\.\d)(.*)", proc.stdout)
34
+ if not matches:
35
+ return False
36
+
37
+ fish_version, git_version = matches.groups()
38
+
39
+ # Release after 3.1.2 or git build after 3.1.2 contain space fix.
40
+ if version.parse(fish_version) > version.parse("3.1.2"):
41
+ return True
42
+ elif version.parse(fish_version) >= version.parse("3.1.2") and git_version:
43
+ return True
44
+ else:
45
+ return False
46
+
47
+
48
+ def create_config_loader() -> ConfigLoaderImpl:
49
+ return ConfigLoaderImpl(
50
+ config_search_path=create_config_search_path(
51
+ search_path_dir=os.path.realpath("hydra/test_utils/configs/completion_test")
52
+ )
53
+ )
54
+
55
+
56
+ base_completion_list: List[str] = [
57
+ "dict.",
58
+ "dict_prefix=",
59
+ "group=",
60
+ "hydra.",
61
+ "hydra/",
62
+ "list.",
63
+ "list_prefix=",
64
+ "test_hydra/",
65
+ ]
66
+
67
+
68
+ @pytest.mark.parametrize("line_prefix", ["", "dict.key1=val1 ", "-r "])
69
+ @pytest.mark.parametrize(
70
+ "line,num_tabs,expected",
71
+ [
72
+ ("", 2, base_completion_list),
73
+ (" ", 2, base_completion_list),
74
+ ("dict", 2, ["dict.", "dict_prefix="]),
75
+ ("dict.", 3, ["dict.key1=", "dict.key2=", "dict.key3="]),
76
+ ("dict.key", 2, ["dict.key1=", "dict.key2=", "dict.key3="]),
77
+ ("dict.key1=", 2, ["dict.key1=val1"]),
78
+ ("dict.key3=", 2, ["dict.key3="]), # no value because dict.key3 is ???
79
+ ("list", 2, ["list.", "list_prefix="]),
80
+ ("list.", 2, ["list.0=", "list.1=", "list.2="]),
81
+ (
82
+ "hydra/",
83
+ 3,
84
+ [
85
+ "hydra/help=",
86
+ "hydra/hydra_help=",
87
+ "hydra/hydra_logging=",
88
+ "hydra/job_logging=",
89
+ "hydra/launcher=",
90
+ "hydra/output=",
91
+ "hydra/sweeper=",
92
+ ],
93
+ ),
94
+ ("test_hydra/lau", 2, ["test_hydra/launcher="]),
95
+ ("test_hydra/launcher=", 2, ["test_hydra/launcher=fairtask"]),
96
+ ("test_hydra/launcher=fa", 2, ["test_hydra/launcher=fairtask"]),
97
+ # loading groups
98
+ ("gro", 2, ["group="]),
99
+ ("group=di", 2, ["group=dict"]),
100
+ (
101
+ "group=dict ",
102
+ 3,
103
+ [
104
+ "dict.",
105
+ "dict_prefix=",
106
+ "group.",
107
+ "group=",
108
+ "hydra.",
109
+ "hydra/",
110
+ "list.",
111
+ "list_prefix=",
112
+ "test_hydra/",
113
+ "toys.",
114
+ ],
115
+ ),
116
+ ("group=", 2, ["group=dict", "group=list"]),
117
+ ("group=dict group.dict=", 2, ["group.dict=true"]),
118
+ ("group=dict group=", 2, ["group=dict", "group=list"]),
119
+ ],
120
+ )
121
+ class TestCompletion:
122
+ def test_completion_plugin(
123
+ self, line_prefix: str, num_tabs: int, line: str, expected: List[str]
124
+ ) -> None:
125
+ config_loader = create_config_loader()
126
+ bc = DefaultCompletionPlugin(config_loader)
127
+ ret = bc._query(config_name="config.yaml", line=line_prefix + line)
128
+ assert ret == expected
129
+
130
+ @pytest.mark.skipif( # type: ignore
131
+ not is_expect_exists(),
132
+ reason="expect should be installed to run the expects tests",
133
+ )
134
+ @pytest.mark.parametrize( # type: ignore
135
+ "prog", [["python", "hydra/test_utils/completion.py"]]
136
+ )
137
+ @pytest.mark.parametrize("shell", ["bash", "fish"]) # type: ignore
138
+ def test_shell_integration(
139
+ self,
140
+ shell: str,
141
+ prog: List[str],
142
+ num_tabs: int,
143
+ line_prefix: str,
144
+ line: str,
145
+ expected: List[str],
146
+ ) -> None:
147
+ if shell == "fish" and not is_fish_supported():
148
+ pytest.skip("fish is not installed or the version is too old")
149
+
150
+ # verify expect will be running the correct Python.
151
+ # This preemptively detect a much harder to understand error from expect.
152
+ ret = subprocess.check_output(["which", "python"], env=os.environ)
153
+ assert os.path.realpath(ret.decode("utf-8").strip()) == os.path.realpath(
154
+ sys.executable.strip()
155
+ )
156
+
157
+ verbose = os.environ.get("VERBOSE", "0") != "0"
158
+
159
+ line1 = "line={}".format(line_prefix + line)
160
+ cmd = ["expect"]
161
+ if verbose:
162
+ cmd.append("-d")
163
+
164
+ cmd.extend(
165
+ [
166
+ "tests/scripts/test_{}_completion.exp".format(shell),
167
+ f"{' '.join(prog)}",
168
+ line1,
169
+ str(num_tabs),
170
+ ]
171
+ )
172
+
173
+ if shell == "fish":
174
+ # Fish will add a space to an unambiguous completion.
175
+ expected = [x + " " if re.match(r".*=\w+$", x) else x for x in expected]
176
+
177
+ # Exactly match token end. See
178
+ # https://github.com/fish-shell/fish-shell/issues/6928
179
+ expected = [re.escape(x) + "$" for x in expected]
180
+
181
+ cmd.extend(expected)
182
+ if verbose:
183
+ print("\nCOMMAND:\n" + " ".join([f"'{x}'" for x in cmd]))
184
+ subprocess.check_call(cmd)
185
+
186
+
187
+ @pytest.mark.parametrize( # type: ignore
188
+ "line,expected",
189
+ [
190
+ ("-c job", base_completion_list),
191
+ ("-c hydra ", base_completion_list),
192
+ ("-c all ", base_completion_list),
193
+ ],
194
+ )
195
+ def test_with_flags(line: str, expected: List[str]) -> None:
196
+ config_loader = create_config_loader()
197
+ bc = DefaultCompletionPlugin(config_loader)
198
+ ret = bc._query(config_name="config.yaml", line=line)
199
+ assert ret == expected
200
+
201
+
202
+ @pytest.mark.parametrize("relative", [True, False]) # type: ignore
203
+ @pytest.mark.parametrize("line_prefix", ["", "dict.key1=val1 "]) # type: ignore
204
+ @pytest.mark.parametrize( # type: ignore
205
+ "key_eq, fname_prefix, files, expected",
206
+ [
207
+ ("abc=", "", ["foo.txt"], ["foo.txt"]),
208
+ ("abc=", "fo", ["foo.txt"], ["foo.txt"]),
209
+ ("abc=", "foo.txt", ["foo.txt"], ["foo.txt"]),
210
+ ("abc=", "foo", ["foo1.txt", "foo2.txt"], ["foo1.txt", "foo2.txt"]),
211
+ ("abc=", "foo1", ["foo1.txt", "foo2.txt"], ["foo1.txt"]),
212
+ ("abc=", "foo/bar", [], []),
213
+ ],
214
+ )
215
+ def test_file_completion(
216
+ tmpdir: Path,
217
+ files: List[str],
218
+ line_prefix: str,
219
+ key_eq: str,
220
+ fname_prefix: str,
221
+ expected: List[str],
222
+ relative: bool,
223
+ ) -> None:
224
+ def create_files(in_files: List[str]) -> None:
225
+ for f in in_files:
226
+ path = Path(f)
227
+ dirname = path.parent
228
+ if str(dirname) != ".":
229
+ Path.mkdir(dirname, parents=True)
230
+ Path(f).touch(exist_ok=True)
231
+
232
+ config_loader = create_config_loader()
233
+ try:
234
+ pwd = os.getcwd()
235
+ os.chdir(str(tmpdir))
236
+ create_files(files)
237
+ bc = DefaultCompletionPlugin(config_loader)
238
+ probe = line_prefix + key_eq
239
+ if relative:
240
+ prefix = "." + os.path.sep
241
+ probe += prefix + fname_prefix
242
+ else:
243
+ prefix = os.path.realpath(".")
244
+ probe += os.path.join(prefix, fname_prefix)
245
+
246
+ ret = bc._query(config_name="config.yaml", line=probe)
247
+ assert len(expected) == len(ret)
248
+ for idx, file in enumerate(expected):
249
+ assert key_eq + os.path.join(prefix, file) == ret[idx]
250
+ finally:
251
+ os.chdir(pwd)
252
+
253
+
254
+ @pytest.mark.parametrize( # type: ignore
255
+ "prefix", ["", " ", "\t", "/foo/bar", " /foo/bar/"]
256
+ )
257
+ @pytest.mark.parametrize( # type: ignore
258
+ "app_prefix",
259
+ [
260
+ "python foo.py",
261
+ "hydra_app",
262
+ "hydra_app ",
263
+ "hy1-_=ra_app",
264
+ "foo.par",
265
+ "f_o-o1=2.par",
266
+ "python foo.py",
267
+ "python tutorials/hydra_app/example/hydra_app/main.py",
268
+ "python foo.py",
269
+ ],
270
+ )
271
+ @pytest.mark.parametrize( # type: ignore
272
+ "args_line, args_line_index",
273
+ [
274
+ ("", None),
275
+ ("foo=bar", None),
276
+ ("foo=bar bar=baz0", None),
277
+ ("", 0),
278
+ ("foo=bar", 3),
279
+ ("foo=bar bar=baz0", 3),
280
+ ("dict.", 0),
281
+ ("dict.", 5),
282
+ ],
283
+ )
284
+ def test_strip(
285
+ prefix: str, app_prefix: str, args_line: str, args_line_index: int
286
+ ) -> None:
287
+ app_prefix = prefix + app_prefix
288
+ if args_line:
289
+ app_prefix = app_prefix + " "
290
+ line = "{}{}".format(app_prefix, args_line)
291
+ result_line = BashCompletion.strip_python_or_app_name(line)
292
+ assert result_line == args_line
293
+
294
+
295
+ @pytest.mark.parametrize( # type: ignore
296
+ "shell,script,comp_func",
297
+ [
298
+ (
299
+ "bash",
300
+ "tests/scripts/test_bash_install_uninstall.sh",
301
+ "hydra_bash_completion",
302
+ ),
303
+ (
304
+ "fish",
305
+ "tests/scripts/test_fish_install_uninstall.fish",
306
+ "hydra_fish_completion",
307
+ ),
308
+ ],
309
+ )
310
+ def test_install_uninstall(shell: str, script: str, comp_func: str) -> None:
311
+ if shell == "fish" and not is_fish_supported():
312
+ pytest.skip("fish is not installed or the version is too old")
313
+ cmd = [shell, script, "python hydra/test_utils/completion.py", comp_func]
314
+ subprocess.check_call(cmd)
testbed/facebookresearch__hydra/tests/test_config_loader.py ADDED
@@ -0,0 +1,1194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ import re
3
+ from dataclasses import dataclass
4
+ from typing import Any, List
5
+
6
+ import pkg_resources
7
+ import pytest
8
+ from omegaconf import MISSING, OmegaConf, ValidationError, open_dict
9
+
10
+ from hydra._internal.config_loader_impl import (
11
+ ConfigLoaderImpl,
12
+ DefaultElement,
13
+ ParsedConfigOverride,
14
+ ParsedOverride,
15
+ )
16
+ from hydra._internal.utils import create_config_search_path
17
+ from hydra.core.config_loader import LoadTrace
18
+ from hydra.core.config_store import ConfigStore, ConfigStoreWithProvider
19
+ from hydra.core.utils import env_override
20
+ from hydra.errors import HydraException, MissingConfigException
21
+ from hydra.test_utils.test_utils import chdir_hydra_root
22
+
23
+ chdir_hydra_root()
24
+
25
+
26
+ @dataclass
27
+ class MySQLConfig:
28
+ driver: str = MISSING
29
+ host: str = MISSING
30
+ port: int = MISSING
31
+ user: str = MISSING
32
+ password: str = MISSING
33
+
34
+
35
+ @dataclass
36
+ class TopLevelConfig:
37
+ normal_yaml_config: bool = MISSING
38
+ db: MySQLConfig = MySQLConfig()
39
+
40
+
41
+ hydra_load_list: List[LoadTrace] = [
42
+ LoadTrace("hydra_config", "structured://", "hydra", None),
43
+ LoadTrace("hydra/hydra_logging/default", "pkg://hydra.conf", "hydra", None),
44
+ LoadTrace("hydra/job_logging/default", "pkg://hydra.conf", "hydra", None),
45
+ LoadTrace("hydra/launcher/basic", "pkg://hydra.conf", "hydra", None),
46
+ LoadTrace("hydra/sweeper/basic", "pkg://hydra.conf", "hydra", "hydra"),
47
+ LoadTrace("hydra/output/default", "pkg://hydra.conf", "hydra", None),
48
+ LoadTrace("hydra/help/default", "pkg://hydra.conf", "hydra", None),
49
+ LoadTrace("hydra/hydra_help/default", "pkg://hydra.conf", "hydra", None),
50
+ ]
51
+
52
+
53
+ @pytest.mark.parametrize(
54
+ "path",
55
+ [
56
+ pytest.param("file://hydra/test_utils/configs", id="file"),
57
+ pytest.param("pkg://hydra.test_utils.configs", id="pkg"),
58
+ ],
59
+ )
60
+ class TestConfigLoader:
61
+ def test_load_configuration(self, path: str) -> None:
62
+ config_loader = ConfigLoaderImpl(
63
+ config_search_path=create_config_search_path(path)
64
+ )
65
+ cfg = config_loader.load_configuration(
66
+ config_name="config.yaml", strict=False, overrides=["abc=123"]
67
+ )
68
+ with open_dict(cfg):
69
+ del cfg["hydra"]
70
+ assert cfg == {"normal_yaml_config": True, "abc": 123}
71
+
72
+ def test_load_with_missing_default(self, path: str) -> None:
73
+ config_loader = ConfigLoaderImpl(
74
+ config_search_path=create_config_search_path(path)
75
+ )
76
+ with pytest.raises(MissingConfigException):
77
+ config_loader.load_configuration(
78
+ config_name="missing-default.yaml", overrides=[], strict=False
79
+ )
80
+
81
+ def test_load_with_missing_optional_default(self, path: str) -> None:
82
+ config_loader = ConfigLoaderImpl(
83
+ config_search_path=create_config_search_path(path)
84
+ )
85
+ cfg = config_loader.load_configuration(
86
+ config_name="missing-optional-default.yaml", overrides=[], strict=False
87
+ )
88
+ with open_dict(cfg):
89
+ del cfg["hydra"]
90
+ assert cfg == {}
91
+
92
+ def test_load_with_optional_default(self, path: str) -> None:
93
+ config_loader = ConfigLoaderImpl(
94
+ config_search_path=create_config_search_path(path)
95
+ )
96
+ cfg = config_loader.load_configuration(
97
+ config_name="optional-default.yaml", overrides=[], strict=False
98
+ )
99
+ with open_dict(cfg):
100
+ del cfg["hydra"]
101
+ assert cfg == {"foo": 10}
102
+
103
+ def test_load_changing_group_in_default(self, path: str) -> None:
104
+ config_loader = ConfigLoaderImpl(
105
+ config_search_path=create_config_search_path(path)
106
+ )
107
+ cfg = config_loader.load_configuration(
108
+ config_name="optional-default.yaml",
109
+ overrides=["group1=file2"],
110
+ strict=False,
111
+ )
112
+ with open_dict(cfg):
113
+ del cfg["hydra"]
114
+ assert cfg == {"foo": 20}
115
+
116
+ @pytest.mark.parametrize( # type: ignore
117
+ "overrides,expected",
118
+ [
119
+ pytest.param(
120
+ [],
121
+ {"group1_option1": True, "pkg1": {"group2_option1": True}},
122
+ id="no_overrides",
123
+ ),
124
+ pytest.param(
125
+ ["group1@:pkg2=option1"],
126
+ {"pkg2": {"group1_option1": True}, "pkg1": {"group2_option1": True}},
127
+ id="override_unspecified_pkg_of_default",
128
+ ),
129
+ pytest.param(
130
+ ["group1@:pkg1=option1"],
131
+ {"pkg1": {"group1_option1": True, "group2_option1": True}},
132
+ id="override_two_groups_to_same_package",
133
+ ),
134
+ ],
135
+ )
136
+ def test_load_changing_group_and_package_in_default(
137
+ self, path: str, overrides: List[str], expected: Any
138
+ ) -> None:
139
+ config_loader = ConfigLoaderImpl(
140
+ config_search_path=create_config_search_path(f"{path}/package_tests")
141
+ )
142
+ cfg = config_loader.load_configuration(
143
+ config_name="pkg_override", overrides=overrides
144
+ )
145
+ with open_dict(cfg):
146
+ del cfg["hydra"]
147
+ assert cfg == expected
148
+
149
+ @pytest.mark.parametrize( # type: ignore
150
+ "overrides,expected",
151
+ [
152
+ pytest.param(
153
+ [],
154
+ {"pkg1": {"group1_option1": True}, "pkg2": {"group1_option1": True}},
155
+ id="baseline",
156
+ ),
157
+ pytest.param(
158
+ ["+group1@pkg3=option1"],
159
+ {
160
+ "pkg1": {"group1_option1": True},
161
+ "pkg2": {"group1_option1": True},
162
+ "pkg3": {"group1_option1": True},
163
+ },
164
+ id="append",
165
+ ),
166
+ pytest.param(
167
+ ["~group1@pkg1"],
168
+ {"pkg2": {"group1_option1": True}},
169
+ id="delete_package",
170
+ ),
171
+ pytest.param(
172
+ ["group1@pkg1:new_pkg=option1"],
173
+ {"new_pkg": {"group1_option1": True}, "pkg2": {"group1_option1": True}},
174
+ id="change_pkg1",
175
+ ),
176
+ pytest.param(
177
+ ["group1@pkg2:new_pkg=option1"],
178
+ {"pkg1": {"group1_option1": True}, "new_pkg": {"group1_option1": True}},
179
+ id="change_pkg2",
180
+ ),
181
+ ],
182
+ )
183
+ def test_override_compose_two_package_one_group(
184
+ self, path: str, overrides: List[str], expected: Any
185
+ ) -> None:
186
+ config_loader = ConfigLoaderImpl(
187
+ config_search_path=create_config_search_path(f"{path}/package_tests")
188
+ )
189
+ cfg = config_loader.load_configuration(
190
+ config_name="two_packages_one_group", overrides=overrides
191
+ )
192
+ with open_dict(cfg):
193
+ del cfg["hydra"]
194
+ assert cfg == expected
195
+
196
+ def test_load_adding_group_not_in_default(self, path: str) -> None:
197
+ config_loader = ConfigLoaderImpl(
198
+ config_search_path=create_config_search_path(path)
199
+ )
200
+ cfg = config_loader.load_configuration(
201
+ config_name="optional-default.yaml",
202
+ overrides=["+group2=file1"],
203
+ strict=False,
204
+ )
205
+ with open_dict(cfg):
206
+ del cfg["hydra"]
207
+ assert cfg == {"foo": 10, "bar": 100}
208
+
209
+ def test_change_run_dir_with_override(self, path: str) -> None:
210
+ config_loader = ConfigLoaderImpl(
211
+ config_search_path=create_config_search_path(path)
212
+ )
213
+ cfg = config_loader.load_configuration(
214
+ config_name="overriding_run_dir.yaml",
215
+ overrides=["hydra.run.dir=abc"],
216
+ strict=False,
217
+ )
218
+ assert cfg.hydra.run.dir == "abc"
219
+
220
+ def test_change_run_dir_with_config(self, path: str) -> None:
221
+ config_loader = ConfigLoaderImpl(
222
+ config_search_path=create_config_search_path(path)
223
+ )
224
+ cfg = config_loader.load_configuration(
225
+ config_name="overriding_run_dir.yaml", overrides=[], strict=False
226
+ )
227
+ assert cfg.hydra.run.dir == "cde"
228
+
229
+ def test_load_strict(self, path: str) -> None:
230
+ """
231
+ Ensure that in strict mode we can override only things that are already in the config
232
+ :return:
233
+ """
234
+ config_loader = ConfigLoaderImpl(
235
+ config_search_path=create_config_search_path(path)
236
+ )
237
+ # Test that overriding existing things works in strict mode
238
+ cfg = config_loader.load_configuration(
239
+ config_name="compose.yaml", overrides=["foo=ZZZ"], strict=True
240
+ )
241
+ with open_dict(cfg):
242
+ del cfg["hydra"]
243
+ assert cfg == {"foo": "ZZZ", "bar": 100}
244
+
245
+ # Test that accessing a key that is not there will fail
246
+ with pytest.raises(AttributeError):
247
+ # noinspection PyStatementEffect
248
+ cfg.not_here
249
+
250
+ # Test that bad overrides triggers the KeyError
251
+ with pytest.raises(HydraException):
252
+ config_loader.load_configuration(
253
+ config_name="compose.yaml", overrides=["f00=ZZZ"], strict=True
254
+ )
255
+
256
+ def test_load_history(self, path: str) -> None:
257
+ config_loader = ConfigLoaderImpl(
258
+ config_search_path=create_config_search_path(path)
259
+ )
260
+ config_loader.load_configuration(
261
+ config_name="missing-optional-default.yaml", overrides=[], strict=False
262
+ )
263
+ expected = hydra_load_list.copy()
264
+ expected.append(LoadTrace("missing-optional-default.yaml", path, "main", None))
265
+ expected.append(LoadTrace("foo/missing", None, None, None))
266
+
267
+ assert config_loader.get_load_history() == expected
268
+
269
+ def test_load_history_with_basic_launcher(self, path: str) -> None:
270
+ config_loader = ConfigLoaderImpl(
271
+ config_search_path=create_config_search_path(path)
272
+ )
273
+ config_loader.load_configuration(
274
+ config_name="custom_default_launcher.yaml",
275
+ overrides=["hydra/launcher=basic"],
276
+ strict=False,
277
+ )
278
+
279
+ expected = hydra_load_list.copy()
280
+ expected.append(LoadTrace("custom_default_launcher.yaml", path, "main", None))
281
+ assert config_loader.get_load_history() == expected
282
+
283
+ def test_load_yml_file(self, path: str) -> None:
284
+ config_loader = ConfigLoaderImpl(
285
+ config_search_path=create_config_search_path(path)
286
+ )
287
+ cfg = config_loader.load_configuration(
288
+ config_name="config.yml", overrides=[], strict=False
289
+ )
290
+ with open_dict(cfg):
291
+ del cfg["hydra"]
292
+
293
+ assert cfg == {"yml_file_here": True}
294
+
295
+ def test_override_with_equals(self, path: str) -> None:
296
+ config_loader = ConfigLoaderImpl(
297
+ config_search_path=create_config_search_path(path)
298
+ )
299
+ cfg = config_loader.load_configuration(
300
+ config_name="config.yaml", overrides=["abc='cde=12'"], strict=False
301
+ )
302
+ with open_dict(cfg):
303
+ del cfg["hydra"]
304
+ assert cfg == OmegaConf.create({"normal_yaml_config": True, "abc": "cde=12"})
305
+
306
+ def test_compose_file_with_dot(self, path: str) -> None:
307
+ config_loader = ConfigLoaderImpl(
308
+ config_search_path=create_config_search_path(path)
309
+ )
310
+ cfg = config_loader.load_configuration(
311
+ config_name="compose.yaml", overrides=["group1=abc.cde"], strict=False
312
+ )
313
+ with open_dict(cfg):
314
+ del cfg["hydra"]
315
+ assert cfg == {"abc=cde": None, "bar": 100}
316
+
317
+ def test_load_config_with_schema(
318
+ self, hydra_restore_singletons: Any, path: str
319
+ ) -> None:
320
+
321
+ ConfigStore.instance().store(
322
+ name="config", node=TopLevelConfig, provider="this_test"
323
+ )
324
+ ConfigStore.instance().store(
325
+ group="db", name="mysql", node=MySQLConfig, provider="this_test",
326
+ )
327
+
328
+ config_loader = ConfigLoaderImpl(
329
+ config_search_path=create_config_search_path(path)
330
+ )
331
+
332
+ cfg = config_loader.load_configuration(
333
+ config_name="config", overrides=["+db=mysql"]
334
+ )
335
+ with open_dict(cfg):
336
+ del cfg["hydra"]
337
+ assert cfg == {
338
+ "normal_yaml_config": True,
339
+ "db": {
340
+ "driver": "mysql",
341
+ "host": "???",
342
+ "port": "???",
343
+ "user": "omry",
344
+ "password": "secret",
345
+ },
346
+ }
347
+
348
+ expected = hydra_load_list.copy()
349
+ expected.append(LoadTrace("config", path, "main", "this_test"))
350
+ expected.append(LoadTrace("db/mysql", path, "main", "this_test"))
351
+ assert config_loader.get_load_history() == expected
352
+
353
+ # verify illegal modification is rejected at runtime
354
+ with pytest.raises(ValidationError):
355
+ cfg.db.port = "fail"
356
+
357
+ # verify illegal override is rejected during load
358
+ with pytest.raises(HydraException):
359
+ config_loader.load_configuration(
360
+ config_name="db/mysql", overrides=["db.port=fail"]
361
+ )
362
+
363
+ def test_load_config_file_with_schema_validation(
364
+ self, hydra_restore_singletons: Any, path: str
365
+ ) -> None:
366
+
367
+ with ConfigStoreWithProvider("this_test") as cs:
368
+ cs.store(name="config", node=TopLevelConfig)
369
+ cs.store(group="db", name="mysql", node=MySQLConfig, package="db")
370
+
371
+ config_loader = ConfigLoaderImpl(
372
+ config_search_path=create_config_search_path(path)
373
+ )
374
+ cfg = config_loader.load_configuration(
375
+ config_name="config", overrides=["+db=mysql"], strict=False
376
+ )
377
+
378
+ with open_dict(cfg):
379
+ del cfg["hydra"]
380
+ assert cfg == {
381
+ "normal_yaml_config": True,
382
+ "db": {
383
+ "driver": "mysql",
384
+ "host": "???",
385
+ "port": "???",
386
+ "user": "omry",
387
+ "password": "secret",
388
+ },
389
+ }
390
+
391
+ expected = hydra_load_list.copy()
392
+ expected.append(LoadTrace("config", path, "main", "this_test"))
393
+ expected.append(LoadTrace("db/mysql", path, "main", "this_test"))
394
+ assert config_loader.get_load_history() == expected
395
+
396
+ def test_assign_null(
397
+ self, hydra_restore_singletons: Any, path: str, recwarn: Any
398
+ ) -> None:
399
+ config_loader = ConfigLoaderImpl(
400
+ config_search_path=create_config_search_path(path)
401
+ )
402
+ cfg = config_loader.load_configuration(
403
+ config_name="config.yaml", overrides=["abc=null"]
404
+ )
405
+ with open_dict(cfg):
406
+ del cfg["hydra"]
407
+ assert cfg == {"normal_yaml_config": True, "abc": None}
408
+ assert len(recwarn) == 0
409
+
410
+
411
+ @pytest.mark.parametrize( # type:ignore
412
+ "in_primary,in_merged,expected",
413
+ [
414
+ ([], [], []),
415
+ (
416
+ [DefaultElement(config_group="a", config_name="aa")],
417
+ [],
418
+ [DefaultElement(config_group="a", config_name="aa")],
419
+ ),
420
+ (
421
+ [DefaultElement(config_group="a", config_name="aa")],
422
+ [DefaultElement(config_group="b", config_name="bb")],
423
+ [
424
+ DefaultElement(config_group="a", config_name="aa"),
425
+ DefaultElement(config_group="b", config_name="bb"),
426
+ ],
427
+ ),
428
+ (
429
+ [
430
+ DefaultElement(config_group="hydra_logging", config_name="default"),
431
+ DefaultElement(config_group="job_logging", config_name="default"),
432
+ DefaultElement(config_group="launcher", config_name="basic"),
433
+ DefaultElement(config_group="sweeper", config_name="basic"),
434
+ ],
435
+ [
436
+ DefaultElement(config_group="optimizer", config_name="nesterov"),
437
+ DefaultElement(config_group="launcher", config_name="basic"),
438
+ ],
439
+ [
440
+ DefaultElement(config_group="hydra_logging", config_name="default"),
441
+ DefaultElement(config_group="job_logging", config_name="default"),
442
+ DefaultElement(config_group="launcher", config_name="basic"),
443
+ DefaultElement(config_group="sweeper", config_name="basic"),
444
+ DefaultElement(config_group="optimizer", config_name="nesterov"),
445
+ ],
446
+ ),
447
+ ],
448
+ )
449
+ def test_merge_default_lists(
450
+ in_primary: List[DefaultElement],
451
+ in_merged: List[DefaultElement],
452
+ expected: List[DefaultElement],
453
+ ) -> None:
454
+ ConfigLoaderImpl._combine_default_lists(in_primary, in_merged)
455
+ assert in_primary == expected
456
+
457
+
458
+ @pytest.mark.parametrize( # type:ignore
459
+ "config_file, overrides",
460
+ [
461
+ # remove from config
462
+ ("removing-hydra-launcher-default.yaml", []),
463
+ # remove from override
464
+ ("config.yaml", ["~hydra/launcher"]),
465
+ # remove from both
466
+ ("removing-hydra-launcher-default.yaml", ["~hydra/launcher"]),
467
+ # second overrides removes
468
+ ("config.yaml", ["hydra/launcher=submitit", "~hydra/launcher"]),
469
+ ],
470
+ )
471
+ def test_default_removal(config_file: str, overrides: List[str]) -> None:
472
+ config_loader = ConfigLoaderImpl(
473
+ config_search_path=create_config_search_path("hydra/test_utils/configs")
474
+ )
475
+ config_loader.load_configuration(
476
+ config_name=config_file, overrides=overrides, strict=False
477
+ )
478
+
479
+ expected = list(
480
+ filter(lambda x: x.filename != "hydra/launcher/basic", hydra_load_list.copy())
481
+ )
482
+ expected.append(
483
+ LoadTrace(config_file, "file://hydra/test_utils/configs", "main", None)
484
+ )
485
+ assert config_loader.get_load_history() == expected
486
+
487
+
488
+ def test_defaults_not_list_exception() -> None:
489
+ config_loader = ConfigLoaderImpl(
490
+ config_search_path=create_config_search_path("hydra/test_utils/configs")
491
+ )
492
+ with pytest.raises(ValueError):
493
+ config_loader.load_configuration(
494
+ config_name="defaults_not_list.yaml", overrides=[], strict=False
495
+ )
496
+
497
+
498
+ @pytest.mark.parametrize( # type:ignore
499
+ "module_name, resource_name",
500
+ [
501
+ ("hydra.test_utils", ""),
502
+ ("hydra.test_utils", "__init__.py"),
503
+ ("hydra.test_utils", "configs"),
504
+ ("hydra.test_utils", "configs/config.yaml"),
505
+ ("hydra.test_utils.configs", ""),
506
+ ("hydra.test_utils.configs", "config.yaml"),
507
+ ("hydra.test_utils.configs", "group1"),
508
+ ("hydra.test_utils.configs", "group1/file1.yaml"),
509
+ ],
510
+ )
511
+ def test_resource_exists(module_name: str, resource_name: str) -> None:
512
+ assert pkg_resources.resource_exists(module_name, resource_name) is True
513
+
514
+
515
+ def test_override_hydra_config_value_from_config_file() -> None:
516
+ config_loader = ConfigLoaderImpl(
517
+ config_search_path=create_config_search_path("hydra/test_utils/configs")
518
+ )
519
+
520
+ cfg = config_loader.load_configuration(
521
+ config_name="overriding_output_dir.yaml", overrides=[], strict=False
522
+ )
523
+ assert cfg.hydra.run.dir == "foo"
524
+
525
+
526
+ def test_override_hydra_config_group_from_config_file() -> None:
527
+ config_loader = ConfigLoaderImpl(
528
+ config_search_path=create_config_search_path("hydra/test_utils/configs")
529
+ )
530
+
531
+ config_loader.load_configuration(
532
+ config_name="overriding_logging_default.yaml", overrides=[], strict=False
533
+ )
534
+
535
+ # This load history is too different to easily reuse the standard hydra_load_list
536
+ assert config_loader.get_load_history() == [
537
+ LoadTrace("hydra_config", "structured://", "hydra", None),
538
+ LoadTrace("hydra/hydra_logging/hydra_debug", "pkg://hydra.conf", "hydra", None),
539
+ LoadTrace("hydra/job_logging/disabled", "pkg://hydra.conf", "hydra", None),
540
+ LoadTrace("hydra/sweeper/basic", "pkg://hydra.conf", "hydra", "hydra"),
541
+ LoadTrace("hydra/output/default", "pkg://hydra.conf", "hydra", None),
542
+ LoadTrace("hydra/help/default", "pkg://hydra.conf", "hydra", None),
543
+ LoadTrace("hydra/hydra_help/default", "pkg://hydra.conf", "hydra", None),
544
+ LoadTrace(
545
+ "overriding_logging_default.yaml",
546
+ "file://hydra/test_utils/configs",
547
+ "main",
548
+ None,
549
+ ),
550
+ ]
551
+
552
+
553
+ def test_list_groups() -> None:
554
+ config_loader = ConfigLoaderImpl(
555
+ config_search_path=create_config_search_path(
556
+ "hydra/test_utils/configs/cloud_infra_example"
557
+ )
558
+ )
559
+ groups = config_loader.list_groups("")
560
+ assert sorted(groups) == [
561
+ "application",
562
+ "cloud_provider",
563
+ "db",
564
+ "environment",
565
+ "hydra",
566
+ ]
567
+
568
+ assert sorted(config_loader.list_groups("hydra")) == [
569
+ "help",
570
+ "hydra_help",
571
+ "hydra_logging",
572
+ "job_logging",
573
+ "launcher",
574
+ "output",
575
+ "sweeper",
576
+ ]
577
+
578
+
579
+ def test_non_config_group_default() -> None:
580
+ config_loader = ConfigLoaderImpl(
581
+ config_search_path=create_config_search_path("hydra/test_utils/configs")
582
+ )
583
+ config_loader.load_configuration(
584
+ config_name="non_config_group_default.yaml", overrides=[], strict=False
585
+ )
586
+
587
+ expected = hydra_load_list.copy()
588
+ expected.extend(
589
+ [
590
+ LoadTrace(
591
+ "non_config_group_default.yaml",
592
+ "file://hydra/test_utils/configs",
593
+ "main",
594
+ None,
595
+ ),
596
+ LoadTrace("some_config", "file://hydra/test_utils/configs", "main", None),
597
+ ]
598
+ )
599
+ assert config_loader.get_load_history() == expected
600
+
601
+
602
+ def test_mixed_composition_order() -> None:
603
+ """
604
+ Tests that the order of mixed composition (defaults contains both config group and non config group
605
+ items) is correct
606
+ """
607
+ config_loader = ConfigLoaderImpl(
608
+ config_search_path=create_config_search_path("hydra/test_utils/configs")
609
+ )
610
+ config_loader.load_configuration(
611
+ config_name="mixed_compose.yaml", overrides=[], strict=False
612
+ )
613
+
614
+ expected = hydra_load_list.copy()
615
+ expected.extend(
616
+ [
617
+ LoadTrace(
618
+ "mixed_compose.yaml", "file://hydra/test_utils/configs", "main", None
619
+ ),
620
+ LoadTrace("some_config", "file://hydra/test_utils/configs", "main", None),
621
+ LoadTrace("group1/file1", "file://hydra/test_utils/configs", "main", None),
622
+ LoadTrace("config", "file://hydra/test_utils/configs", "main", None),
623
+ ]
624
+ )
625
+
626
+ assert config_loader.get_load_history() == expected
627
+
628
+
629
+ def test_load_schema_as_config(hydra_restore_singletons: Any) -> None:
630
+ """
631
+ Load structured config as a configuration
632
+ """
633
+ ConfigStore.instance().store(
634
+ name="config", node=TopLevelConfig, provider="this_test"
635
+ )
636
+
637
+ ConfigStore.instance().store(
638
+ name="db/mysql", node=MySQLConfig, provider="this_test",
639
+ )
640
+
641
+ config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path(None))
642
+ cfg = config_loader.load_configuration(config_name="config", overrides=[])
643
+ with open_dict(cfg):
644
+ del cfg["hydra"]
645
+ assert cfg == {
646
+ "normal_yaml_config": "???",
647
+ "db": {
648
+ "driver": MISSING,
649
+ "host": MISSING,
650
+ "port": MISSING,
651
+ "user": MISSING,
652
+ "password": MISSING,
653
+ },
654
+ }
655
+
656
+ expected = hydra_load_list.copy()
657
+ expected.extend([LoadTrace("config", "structured://", "this_test", None)])
658
+ assert config_loader.get_load_history() == expected
659
+
660
+
661
+ @dataclass
662
+ class Plugin:
663
+ name: str = MISSING
664
+ params: Any = MISSING
665
+
666
+
667
+ @dataclass
668
+ class ConcretePlugin(Plugin):
669
+ name: str = "foobar_plugin"
670
+
671
+ @dataclass
672
+ class FoobarParams:
673
+ foo: int = 10
674
+
675
+ params: FoobarParams = FoobarParams()
676
+
677
+
678
+ @dataclass
679
+ # A plugin that does not extend the parent Plugin class
680
+ class InvalidPlugin:
681
+ name: str = "invalid_plugin"
682
+
683
+
684
+ @dataclass
685
+ class Config:
686
+ plugin: Plugin = Plugin()
687
+
688
+
689
+ def test_overlapping_schemas(hydra_restore_singletons: Any) -> None:
690
+
691
+ cs = ConfigStore.instance()
692
+ cs.store(name="config", node=Config)
693
+ cs.store(group="plugin", name="concrete", node=ConcretePlugin)
694
+
695
+ config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path(None))
696
+ cfg = config_loader.load_configuration(config_name="config", overrides=[])
697
+ with open_dict(cfg):
698
+ del cfg["hydra"]
699
+
700
+ assert cfg == {"plugin": {"name": "???", "params": "???"}}
701
+ assert OmegaConf.get_type(cfg.plugin) == Plugin
702
+
703
+ cfg = config_loader.load_configuration(
704
+ config_name="config", overrides=["+plugin=concrete"]
705
+ )
706
+ with open_dict(cfg):
707
+ del cfg["hydra"]
708
+
709
+ assert cfg == {"plugin": {"name": "foobar_plugin", "params": {"foo": 10}}}
710
+ assert OmegaConf.get_type(cfg.plugin) == ConcretePlugin
711
+ assert OmegaConf.get_type(cfg.plugin.params) == ConcretePlugin.FoobarParams
712
+ with pytest.raises(ValidationError):
713
+ cfg.plugin = 10
714
+
715
+
716
+ def test_invalid_plugin_merge(hydra_restore_singletons: Any) -> Any:
717
+ cs = ConfigStore.instance()
718
+ cs.store(name="config", node=Config)
719
+ cs.store(group="plugin", name="invalid", node=InvalidPlugin)
720
+
721
+ cl = ConfigLoaderImpl(config_search_path=create_config_search_path(None))
722
+ with pytest.raises(HydraException):
723
+ cl.load_configuration(config_name="config", overrides=["plugin=invalid"])
724
+
725
+
726
+ def test_job_env_copy() -> None:
727
+ config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path(None))
728
+ with env_override({"zonk": "123456"}):
729
+ cfg = config_loader.load_configuration(
730
+ config_name=None, overrides=["hydra.job.env_copy=[zonk]"]
731
+ )
732
+ assert cfg.hydra.job.env_set == {"zonk": "123456"}
733
+
734
+
735
+ @pytest.mark.parametrize( # type: ignore
736
+ "overrides,expected",
737
+ [
738
+ (
739
+ [],
740
+ {
741
+ "optimizer": {"type": "adam", "lr": 0.1, "beta": 0.01},
742
+ "dataset": {"name": "imagenet", "path": "/datasets/imagenet"},
743
+ "adam_imagenet": True,
744
+ },
745
+ ),
746
+ (
747
+ ["optimizer=nesterov"],
748
+ {
749
+ "optimizer": {"type": "nesterov", "lr": 0.001},
750
+ "dataset": {"name": "imagenet", "path": "/datasets/imagenet"},
751
+ "nesterov_imagenet": True,
752
+ },
753
+ ),
754
+ ],
755
+ )
756
+ def test_complex_defaults(overrides: Any, expected: Any) -> None:
757
+ config_loader = ConfigLoaderImpl(
758
+ config_search_path=create_config_search_path(
759
+ "tests/test_apps/sweep_complex_defaults/conf"
760
+ )
761
+ )
762
+
763
+ cfg = config_loader.load_configuration(config_name="config", overrides=overrides)
764
+ with open_dict(cfg):
765
+ del cfg["hydra"]
766
+ assert cfg == expected
767
+
768
+
769
+ @pytest.mark.parametrize( # type: ignore
770
+ "override, expected",
771
+ [
772
+ # changing item
773
+ pytest.param(
774
+ "db=postgresql",
775
+ ParsedOverride(None, "db", None, None, "postgresql"),
776
+ id="change_option",
777
+ ),
778
+ pytest.param(
779
+ "db@dest=postgresql",
780
+ ParsedOverride(None, "db", "dest", None, "postgresql"),
781
+ id="change_option",
782
+ ),
783
+ pytest.param(
784
+ "db@src:dest=postgresql",
785
+ ParsedOverride(None, "db", "src", "dest", "postgresql"),
786
+ id="change_both",
787
+ ),
788
+ pytest.param(
789
+ "db@dest",
790
+ ParsedOverride(None, "db", "dest", None, None),
791
+ id="change_package",
792
+ ),
793
+ pytest.param(
794
+ "db@src:dest",
795
+ ParsedOverride(None, "db", "src", "dest", None),
796
+ id="change_package",
797
+ ),
798
+ # adding item
799
+ pytest.param(
800
+ "+model=resnet",
801
+ ParsedOverride("+", "model", None, None, "resnet"),
802
+ id="add_item",
803
+ ),
804
+ pytest.param(
805
+ "+db@offsite_backup=mysql",
806
+ ParsedOverride("+", "db", "offsite_backup", None, "mysql"),
807
+ id="add_item",
808
+ ),
809
+ # deleting item
810
+ pytest.param(
811
+ "~db", ParsedOverride("~", "db", None, None, None), id="delete_item",
812
+ ),
813
+ pytest.param(
814
+ "~db@src", ParsedOverride("~", "db", "src", None, None), id="delete_item",
815
+ ),
816
+ pytest.param(
817
+ "~db", ParsedOverride("~", "db", None, None, None), id="delete_item",
818
+ ),
819
+ pytest.param(
820
+ "~db@src", ParsedOverride("~", "db", "src", None, None), id="delete_item",
821
+ ),
822
+ ],
823
+ )
824
+ def test_parse_override(override: str, expected: ParsedOverride) -> None:
825
+ ret = ConfigLoaderImpl._parse_override(override)
826
+ assert ret.override == expected
827
+
828
+
829
+ config_parse_error_msg = (
830
+ "Error parsing config override : '{override}'"
831
+ "\nAccepted forms:"
832
+ "\n\tOverride: key=value"
833
+ "\n\tAppend: +key=value"
834
+ "\n\tDelete: ~key=value, ~key"
835
+ )
836
+
837
+
838
+ @pytest.mark.parametrize( # type: ignore
839
+ "override, expected",
840
+ [
841
+ pytest.param(
842
+ "x.y.z=abc", ParsedConfigOverride(None, "x.y.z", "abc"), id="change_option",
843
+ ),
844
+ pytest.param(
845
+ "+x.y.z=abc", ParsedConfigOverride("+", "x.y.z", "abc"), id="adding",
846
+ ),
847
+ pytest.param(
848
+ "~x.y.z=abc", ParsedConfigOverride("~", "x.y.z", "abc"), id="adding",
849
+ ),
850
+ pytest.param("~x.y.z=", ParsedConfigOverride("~", "x.y.z", ""), id="adding"),
851
+ pytest.param(
852
+ "=a",
853
+ pytest.raises(
854
+ HydraException,
855
+ match=re.escape(config_parse_error_msg.format(override="=a")),
856
+ ),
857
+ id="no_key",
858
+ ),
859
+ ],
860
+ )
861
+ def test_parse_config_override(override: str, expected: Any) -> None:
862
+ if isinstance(expected, ParsedConfigOverride):
863
+ ret = ConfigLoaderImpl._parse_config_override(override)
864
+ assert ret == expected
865
+ else:
866
+ with expected:
867
+ ConfigLoaderImpl._parse_config_override(override)
868
+
869
+
870
+ defaults_list = [{"db": "mysql"}, {"db@src": "mysql"}, {"hydra/launcher": "basic"}]
871
+
872
+
873
+ @pytest.mark.parametrize( # type: ignore
874
+ "input_defaults,overrides,expected",
875
+ [
876
+ # change item
877
+ pytest.param(
878
+ defaults_list,
879
+ ["db=postgresql"],
880
+ [{"db": "postgresql"}, {"db@src": "mysql"}, {"hydra/launcher": "basic"}],
881
+ id="change_option",
882
+ ),
883
+ pytest.param(
884
+ defaults_list,
885
+ ["db@src=postgresql"],
886
+ [{"db": "mysql"}, {"db@src": "postgresql"}, {"hydra/launcher": "basic"}],
887
+ id="change_option",
888
+ ),
889
+ pytest.param(
890
+ defaults_list,
891
+ ["db@:dest=postgresql"],
892
+ [
893
+ {"db@dest": "postgresql"},
894
+ {"db@src": "mysql"},
895
+ {"hydra/launcher": "basic"},
896
+ ],
897
+ id="change_both",
898
+ ),
899
+ pytest.param(
900
+ defaults_list,
901
+ ["db@src:dest=postgresql"],
902
+ [{"db": "mysql"}, {"db@dest": "postgresql"}, {"hydra/launcher": "basic"}],
903
+ id="change_both",
904
+ ),
905
+ pytest.param(
906
+ defaults_list,
907
+ ["db@XXX:dest=postgresql"],
908
+ pytest.raises(
909
+ HydraException,
910
+ match=re.escape(
911
+ "Could not rename package. No match for 'db@XXX' in the defaults list."
912
+ ),
913
+ ),
914
+ id="change_both_invalid_package",
915
+ ),
916
+ pytest.param(
917
+ defaults_list,
918
+ ["db@:dest"],
919
+ [{"db@dest": "mysql"}, {"db@src": "mysql"}, {"hydra/launcher": "basic"}],
920
+ id="change_package",
921
+ ),
922
+ pytest.param(
923
+ defaults_list,
924
+ ["db@src:dest"],
925
+ [{"db": "mysql"}, {"db@dest": "mysql"}, {"hydra/launcher": "basic"}],
926
+ id="change_package",
927
+ ),
928
+ pytest.param(
929
+ defaults_list,
930
+ ["db@XXX:dest"],
931
+ pytest.raises(
932
+ HydraException,
933
+ match=re.escape(
934
+ "Could not rename package. No match for 'db@XXX' in the defaults list."
935
+ ),
936
+ ),
937
+ id="change_package_from_invalid",
938
+ ),
939
+ # adding item
940
+ pytest.param([], ["+db=mysql"], [{"db": "mysql"}], id="adding_item"),
941
+ pytest.param(
942
+ defaults_list,
943
+ ["+db@backup=mysql"],
944
+ [
945
+ {"db": "mysql"},
946
+ {"db@src": "mysql"},
947
+ {"hydra/launcher": "basic"},
948
+ {"db@backup": "mysql"},
949
+ ],
950
+ id="adding_item_at_package",
951
+ ),
952
+ pytest.param(
953
+ defaults_list,
954
+ ["+db=mysql"],
955
+ pytest.raises(
956
+ HydraException,
957
+ match=re.escape(
958
+ "Could not add. An item matching 'db' is already in the defaults list"
959
+ ),
960
+ ),
961
+ id="adding_duplicate_item",
962
+ ),
963
+ pytest.param(
964
+ defaults_list,
965
+ ["+db@src:foo=mysql"],
966
+ pytest.raises(
967
+ HydraException,
968
+ match=re.escape(
969
+ "Add syntax does not support package rename, remove + prefix"
970
+ ),
971
+ ),
972
+ id="add_rename_error",
973
+ ),
974
+ pytest.param(
975
+ defaults_list,
976
+ ["+db@src=mysql"],
977
+ pytest.raises(
978
+ HydraException,
979
+ match=re.escape(
980
+ "Could not add. An item matching 'db@src' is already in the defaults list"
981
+ ),
982
+ ),
983
+ id="adding_duplicate_item",
984
+ ),
985
+ pytest.param(
986
+ [],
987
+ ["db=mysql"],
988
+ pytest.raises(
989
+ HydraException,
990
+ match=re.escape(
991
+ "Could not override 'db'. No match in the defaults list."
992
+ "\nTo append to your default list use +db=mysql"
993
+ ),
994
+ ),
995
+ id="adding_without_plus",
996
+ ),
997
+ # deleting item
998
+ pytest.param(
999
+ [],
1000
+ ["~db=mysql"],
1001
+ pytest.raises(
1002
+ HydraException,
1003
+ match=re.escape(
1004
+ "Could not delete. No match for 'db' in the defaults list."
1005
+ ),
1006
+ ),
1007
+ id="delete_no_match",
1008
+ ),
1009
+ pytest.param(
1010
+ defaults_list,
1011
+ ["~db"],
1012
+ [{"db@src": "mysql"}, {"hydra/launcher": "basic"}],
1013
+ id="delete",
1014
+ ),
1015
+ pytest.param(
1016
+ defaults_list,
1017
+ ["~db=mysql"],
1018
+ [{"db@src": "mysql"}, {"hydra/launcher": "basic"}],
1019
+ id="delete",
1020
+ ),
1021
+ pytest.param(
1022
+ defaults_list,
1023
+ ["~db=postgresql"],
1024
+ pytest.raises(
1025
+ HydraException,
1026
+ match=re.escape(
1027
+ "Could not delete. No match for 'db=postgresql' in the defaults list."
1028
+ ),
1029
+ ),
1030
+ id="delete_mismatch_value",
1031
+ ),
1032
+ pytest.param(
1033
+ defaults_list,
1034
+ ["~db@src"],
1035
+ [{"db": "mysql"}, {"hydra/launcher": "basic"}],
1036
+ id="delete",
1037
+ ),
1038
+ # syntax error
1039
+ pytest.param(
1040
+ defaults_list,
1041
+ ["db"],
1042
+ pytest.raises(
1043
+ HydraException,
1044
+ match=re.escape("Error parsing config group override : 'db'"),
1045
+ ),
1046
+ id="syntax_error",
1047
+ ),
1048
+ ],
1049
+ )
1050
+ def test_apply_overrides_to_defaults(
1051
+ input_defaults: List[str], overrides: List[str], expected: Any
1052
+ ) -> None:
1053
+ defaults = ConfigLoaderImpl._parse_defaults(
1054
+ OmegaConf.create({"defaults": input_defaults})
1055
+ )
1056
+ parsed_overrides = [
1057
+ ConfigLoaderImpl._parse_override(override) for override in overrides
1058
+ ]
1059
+
1060
+ if isinstance(expected, list):
1061
+ expected_defaults = ConfigLoaderImpl._parse_defaults(
1062
+ OmegaConf.create({"defaults": expected})
1063
+ )
1064
+ ConfigLoaderImpl._apply_overrides_to_defaults(
1065
+ overrides=parsed_overrides, defaults=defaults
1066
+ )
1067
+ assert defaults == expected_defaults
1068
+ else:
1069
+ with expected:
1070
+ ConfigLoaderImpl._apply_overrides_to_defaults(
1071
+ overrides=parsed_overrides, defaults=defaults
1072
+ )
1073
+
1074
+
1075
+ def test_delete_by_assigning_null_is_deprecated() -> None:
1076
+ msg = (
1077
+ "\nRemoving from the defaults list by assigning 'null' "
1078
+ "is deprecated and will be removed in Hydra 1.1."
1079
+ "\nUse ~db"
1080
+ )
1081
+
1082
+ defaults = ConfigLoaderImpl._parse_defaults(
1083
+ OmegaConf.create({"defaults": [{"db": "mysql"}]})
1084
+ )
1085
+ parsed_overrides = [ConfigLoaderImpl._parse_override("db=null")]
1086
+
1087
+ with pytest.warns(expected_warning=UserWarning, match=re.escape(msg)):
1088
+ assert parsed_overrides[0].override.is_delete()
1089
+ ConfigLoaderImpl._apply_overrides_to_defaults(
1090
+ overrides=parsed_overrides, defaults=defaults
1091
+ )
1092
+ assert defaults == []
1093
+
1094
+
1095
+ @pytest.mark.parametrize( # type: ignore
1096
+ "input_cfg,strict,overrides,expected",
1097
+ [
1098
+ # append
1099
+ pytest.param({}, False, ["x=10"], {"x": 10}, id="append"),
1100
+ pytest.param(
1101
+ {},
1102
+ True,
1103
+ ["x=10"],
1104
+ pytest.raises(
1105
+ HydraException,
1106
+ match=re.escape(
1107
+ "Could not override 'x'. No match in config."
1108
+ "\nTo append to your config use +x=10"
1109
+ ),
1110
+ ),
1111
+ id="append",
1112
+ ),
1113
+ pytest.param({}, True, ["+x=10"], {"x": 10}, id="append"),
1114
+ # append item with @
1115
+ pytest.param(
1116
+ {},
1117
+ False,
1118
+ ["user@hostname=active"],
1119
+ {"user@hostname": "active"},
1120
+ id="append@",
1121
+ ),
1122
+ pytest.param(
1123
+ {},
1124
+ True,
1125
+ ["+user@hostname=active"],
1126
+ {"user@hostname": "active"},
1127
+ id="append@",
1128
+ ),
1129
+ pytest.param(
1130
+ {"x": 20},
1131
+ True,
1132
+ ["+x=10"],
1133
+ pytest.raises(
1134
+ HydraException,
1135
+ match=re.escape(
1136
+ "Could not append to config. An item is already at 'x'"
1137
+ ),
1138
+ ),
1139
+ id="append",
1140
+ ),
1141
+ # override
1142
+ pytest.param({"x": 20}, False, ["x=10"], {"x": 10}, id="override"),
1143
+ pytest.param({"x": 20}, True, ["x=10"], {"x": 10}, id="override"),
1144
+ pytest.param(
1145
+ {"x": 20}, False, ["x=null"], {"x": None}, id="override_with_null"
1146
+ ),
1147
+ # delete
1148
+ pytest.param({"x": 20}, False, ["~x"], {}, id="delete"),
1149
+ pytest.param({"x": 20}, False, ["~x=20"], {}, id="delete"),
1150
+ pytest.param({"x": {"y": 10}}, False, ["~x"], {}, id="delete"),
1151
+ pytest.param({"x": {"y": 10}}, False, ["~x.y"], {"x": {}}, id="delete"),
1152
+ pytest.param({"x": {"y": 10}}, False, ["~x.y=10"], {"x": {}}, id="delete"),
1153
+ pytest.param({"x": 20}, True, ["~x"], {}, id="delete_strict"),
1154
+ pytest.param({"x": 20}, True, ["~x=20"], {}, id="delete_strict"),
1155
+ pytest.param({"x": {"y": 10}}, True, ["~x"], {}, id="delete_strict"),
1156
+ pytest.param({"x": {"y": 10}}, True, ["~x.y"], {"x": {}}, id="delete_strict"),
1157
+ pytest.param(
1158
+ {"x": {"y": 10}}, True, ["~x.y=10"], {"x": {}}, id="delete_strict"
1159
+ ),
1160
+ pytest.param(
1161
+ {"x": 20},
1162
+ False,
1163
+ ["~z"],
1164
+ pytest.raises(
1165
+ HydraException,
1166
+ match=re.escape("Could not delete from config. 'z' does not exist."),
1167
+ ),
1168
+ id="delete_error_key",
1169
+ ),
1170
+ pytest.param(
1171
+ {"x": 20},
1172
+ False,
1173
+ ["~x=10"],
1174
+ pytest.raises(
1175
+ HydraException,
1176
+ match=re.escape(
1177
+ "Could not delete from config. The value of 'x' is 20 and not 10."
1178
+ ),
1179
+ ),
1180
+ id="delete_error_value",
1181
+ ),
1182
+ ],
1183
+ )
1184
+ def test_apply_overrides_to_config(
1185
+ input_cfg: Any, strict: bool, overrides: List[str], expected: Any
1186
+ ) -> None:
1187
+ cfg = OmegaConf.create(input_cfg)
1188
+ OmegaConf.set_struct(cfg, strict)
1189
+ if isinstance(expected, dict):
1190
+ ConfigLoaderImpl._apply_overrides_to_config(overrides=overrides, cfg=cfg)
1191
+ assert cfg == expected
1192
+ else:
1193
+ with expected:
1194
+ ConfigLoaderImpl._apply_overrides_to_config(overrides=overrides, cfg=cfg)
testbed/facebookresearch__hydra/tests/test_config_repository.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ import re
3
+ from typing import Any, List, Optional
4
+
5
+ import pytest
6
+
7
+ from hydra._internal.config_repository import ConfigRepository
8
+ from hydra._internal.config_search_path_impl import ConfigSearchPathImpl
9
+ from hydra._internal.core_plugins.file_config_source import FileConfigSource
10
+ from hydra._internal.core_plugins.package_config_source import PackageConfigSource
11
+ from hydra._internal.core_plugins.structured_config_source import StructuredConfigSource
12
+ from hydra.core.object_type import ObjectType
13
+ from hydra.core.plugins import Plugins
14
+ from hydra.plugins.config_source import ConfigSource
15
+ from hydra.test_utils.config_source_common_tests import ConfigSourceTestSuite
16
+ from hydra.test_utils.test_utils import chdir_hydra_root
17
+
18
+ chdir_hydra_root()
19
+
20
+
21
+ @pytest.mark.parametrize(
22
+ "type_, path",
23
+ [
24
+ pytest.param(
25
+ FileConfigSource,
26
+ "file://tests/test_apps/config_source_test/dir",
27
+ id="FileConfigSource",
28
+ ),
29
+ pytest.param(
30
+ PackageConfigSource,
31
+ "pkg://tests.test_apps.config_source_test.dir",
32
+ id="PackageConfigSource",
33
+ ),
34
+ pytest.param(
35
+ StructuredConfigSource,
36
+ "structured://tests.test_apps.config_source_test.structured",
37
+ id="StructuredConfigSource",
38
+ ),
39
+ ],
40
+ )
41
+ class TestCoreConfigSources(ConfigSourceTestSuite):
42
+ pass
43
+
44
+
45
+ def create_config_search_path(path: str) -> ConfigSearchPathImpl:
46
+ csp = ConfigSearchPathImpl()
47
+ csp.append(provider="test", path=path)
48
+ return csp
49
+
50
+
51
+ @pytest.mark.parametrize(
52
+ "path",
53
+ [
54
+ "file://tests/test_apps/config_source_test/dir",
55
+ "pkg://tests.test_apps.config_source_test.dir",
56
+ ],
57
+ )
58
+ class TestConfigRepository:
59
+ def test_config_repository_load(
60
+ self, hydra_restore_singletons: Any, path: str
61
+ ) -> None:
62
+ Plugins.instance() # initializes
63
+ config_search_path = create_config_search_path(path)
64
+ repo = ConfigRepository(config_search_path=config_search_path)
65
+ ret = repo.load_config(
66
+ config_path="dataset/imagenet.yaml", is_primary_config=False
67
+ )
68
+ assert ret is not None
69
+ assert ret.config == {
70
+ "dataset": {"name": "imagenet", "path": "/datasets/imagenet"}
71
+ }
72
+ assert (
73
+ repo.load_config(config_path="not_found.yaml", is_primary_config=True)
74
+ is None
75
+ )
76
+
77
+ def test_config_repository_exists(
78
+ self, hydra_restore_singletons: Any, path: str
79
+ ) -> None:
80
+ Plugins.instance() # initializes
81
+ config_search_path = create_config_search_path(path)
82
+ repo = ConfigRepository(config_search_path=config_search_path)
83
+ assert repo.config_exists("dataset/imagenet.yaml")
84
+ assert not repo.config_exists("not_found.yaml")
85
+
86
+ @pytest.mark.parametrize( # type: ignore
87
+ "config_path,results_filter,expected",
88
+ [
89
+ (
90
+ "",
91
+ None,
92
+ [
93
+ "config_without_group",
94
+ "dataset",
95
+ "level1",
96
+ "optimizer",
97
+ "package_test",
98
+ "primary_config",
99
+ "primary_config_with_non_global_package",
100
+ ],
101
+ ),
102
+ ("", ObjectType.GROUP, ["dataset", "level1", "optimizer", "package_test"]),
103
+ (
104
+ "",
105
+ ObjectType.CONFIG,
106
+ [
107
+ "config_without_group",
108
+ "dataset",
109
+ "primary_config",
110
+ "primary_config_with_non_global_package",
111
+ ],
112
+ ),
113
+ ("dataset", None, ["cifar10", "imagenet"]),
114
+ ("dataset", ObjectType.GROUP, []),
115
+ ("dataset", ObjectType.CONFIG, ["cifar10", "imagenet"]),
116
+ ("level1", ObjectType.GROUP, ["level2"]),
117
+ ("level1", ObjectType.CONFIG, []),
118
+ ("level1/level2", ObjectType.CONFIG, ["nested1", "nested2"]),
119
+ ],
120
+ )
121
+ def test_config_repository_list(
122
+ self,
123
+ hydra_restore_singletons: Any,
124
+ path: str,
125
+ config_path: str,
126
+ results_filter: Optional[ObjectType],
127
+ expected: List[str],
128
+ ) -> None:
129
+ Plugins.instance() # initializes
130
+ config_search_path = create_config_search_path(path)
131
+ repo = ConfigRepository(config_search_path=config_search_path)
132
+ ret = repo.get_group_options(
133
+ group_name=config_path, results_filter=results_filter
134
+ )
135
+ assert ret == expected
136
+
137
+
138
+ @pytest.mark.parametrize("sep", [" "]) # type: ignore
139
+ @pytest.mark.parametrize( # type: ignore
140
+ "cfg_text, expected",
141
+ [
142
+ ("# @package{sep}foo.bar", {"package": "foo.bar"}),
143
+ ("# @package{sep} foo.bar", {"package": "foo.bar"}),
144
+ ("# @package {sep}foo.bar", {"package": "foo.bar"}),
145
+ ("#@package{sep}foo.bar", {"package": "foo.bar"}),
146
+ ("#@package{sep}foo.bar ", {"package": "foo.bar"}),
147
+ (
148
+ "#@package{sep}foo.bar bah",
149
+ pytest.raises(ValueError, match=re.escape("Too many components in"),),
150
+ ),
151
+ (
152
+ "#@package",
153
+ pytest.raises(
154
+ ValueError, match=re.escape("Expected header format: KEY VALUE, got"),
155
+ ),
156
+ ),
157
+ (
158
+ """# @package{sep}foo.bar
159
+ foo: bar
160
+ # comment dsa
161
+ """,
162
+ {"package": "foo.bar"},
163
+ ),
164
+ (
165
+ """
166
+ # @package{sep}foo.bar
167
+ """,
168
+ {"package": "foo.bar"},
169
+ ),
170
+ ],
171
+ )
172
+ def test_get_config_header(cfg_text: str, expected: Any, sep: str) -> None:
173
+ cfg_text = cfg_text.format(sep=sep)
174
+ if isinstance(expected, dict):
175
+ header = ConfigSource._get_header_dict(cfg_text)
176
+ assert header == expected
177
+ else:
178
+ with expected:
179
+ ConfigSource._get_header_dict(cfg_text)
testbed/facebookresearch__hydra/tests/test_config_search_path.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ from os.path import realpath
3
+ from typing import List, Optional, Tuple
4
+
5
+ import pytest
6
+
7
+ from hydra._internal.config_search_path_impl import ConfigSearchPathImpl
8
+ from hydra._internal.utils import compute_search_path_dir
9
+ from hydra.core.config_search_path import SearchPathElement, SearchPathQuery
10
+
11
+
12
+ def create_search_path(base_list: List[Tuple[str, str]]) -> ConfigSearchPathImpl:
13
+ csp = ConfigSearchPathImpl()
14
+ csp.config_search_path = [SearchPathElement(x[0], x[1]) for x in base_list]
15
+ return csp
16
+
17
+
18
+ def to_tuples_list(
19
+ search_path: ConfigSearchPathImpl,
20
+ ) -> List[Tuple[Optional[str], Optional[str]]]:
21
+ return [(x.provider, x.path) for x in search_path.config_search_path]
22
+
23
+
24
+ @pytest.mark.parametrize( # type: ignore
25
+ "input_list, reference, expected_idx",
26
+ [
27
+ ([], ("", ""), -1),
28
+ ([("a", "10")], ("a", None), 0),
29
+ ([("a", "10"), ("b", "20"), ("a", "30")], ("a", None), 2),
30
+ ([("a", "10"), ("b", "20"), ("a", "30")], ("b", None), 1),
31
+ ([("a", "10"), ("b", "20"), ("a", "30")], ("a", "10"), 0),
32
+ ],
33
+ )
34
+ def test_find_last_match(
35
+ input_list: List[Tuple[str, str]], reference: str, expected_idx: int,
36
+ ) -> None:
37
+ csp = create_search_path(input_list)
38
+ assert (
39
+ csp.find_last_match(SearchPathQuery(reference[0], reference[1])) == expected_idx
40
+ )
41
+
42
+
43
+ @pytest.mark.parametrize( # type: ignore
44
+ "input_list, reference, expected_idx",
45
+ [
46
+ ([], ("", ""), -1),
47
+ ([("a", "10")], ("a", None), 0),
48
+ ([("a", "10"), ("b", "20"), ("a", "30")], ("a", None), 0),
49
+ ([("a", "10"), ("b", "20"), ("a", "30")], ("b", None), 1),
50
+ ([("a", "10"), ("b", "20"), ("a", "30")], ("a", "10"), 0),
51
+ ],
52
+ )
53
+ def test_find_first_match(
54
+ input_list: List[Tuple[str, str]], reference: str, expected_idx: int,
55
+ ) -> None:
56
+ csp = create_search_path(input_list)
57
+ sp = SearchPathQuery(reference[0], reference[1])
58
+ assert csp.find_first_match(sp) == expected_idx
59
+
60
+
61
+ @pytest.mark.parametrize( # type: ignore
62
+ "base_list, provider, path, anchor_provider, result_list",
63
+ [
64
+ # appending to an empty list
65
+ ([], "foo", "/path", None, [("foo", "/path")]),
66
+ # appending to a non empty list
67
+ ([("f1", "/p1")], "f2", "/p2", None, [("f1", "/p1"), ("f2", "/p2")]),
68
+ # appending after an anchor at key 0
69
+ (
70
+ [("f1", "A"), ("f2", "B")],
71
+ "f3",
72
+ "B",
73
+ SearchPathQuery(None, "A"),
74
+ [("f1", "A"), ("f3", "B"), ("f2", "B")],
75
+ ),
76
+ # appending after an anchor at the end of the list
77
+ (
78
+ [("f1", "A"), ("f2", "B")],
79
+ "f3",
80
+ "B",
81
+ SearchPathQuery(None, "B"),
82
+ [("f1", "A"), ("f2", "B"), ("f3", "B")],
83
+ ),
84
+ # appending after a non existent anchor
85
+ (
86
+ [],
87
+ "new_provider",
88
+ "/path",
89
+ "unregister_provider",
90
+ [("new_provider", "/path")],
91
+ ),
92
+ ],
93
+ )
94
+ def test_append(
95
+ base_list: List[Tuple[str, str]],
96
+ provider: str,
97
+ path: str,
98
+ anchor_provider: SearchPathQuery,
99
+ result_list: List[Tuple[str, str]],
100
+ ) -> None:
101
+ csp = create_search_path(base_list)
102
+ csp.append(provider=provider, path=path, anchor=anchor_provider)
103
+ assert to_tuples_list(csp) == result_list
104
+
105
+
106
+ @pytest.mark.parametrize( # type: ignore
107
+ "base_list, provider, path, anchor_provider, result_list",
108
+ [
109
+ # prepending to an empty list
110
+ ([], "foo", "/path", None, [("foo", "/path")]),
111
+ # prepending to a full list
112
+ (
113
+ [("foo", "/path")],
114
+ "foo2",
115
+ "/path2",
116
+ None,
117
+ [("foo2", "/path2"), ("foo", "/path")],
118
+ ),
119
+ # prepending in front of an anchor at key 0
120
+ (
121
+ [("foo", "/path")],
122
+ "foo2",
123
+ "/path2",
124
+ SearchPathQuery("foo", "/path"),
125
+ [("foo2", "/path2"), ("foo", "/path")],
126
+ ),
127
+ # prepending in front of an anchor at key 1
128
+ (
129
+ [("foo", "/path"), ("foo2", "/path2")],
130
+ "foo3",
131
+ "/path3",
132
+ SearchPathQuery("foo2", "/path2"),
133
+ [("foo", "/path"), ("foo3", "/path3"), ("foo2", "/path2")],
134
+ ),
135
+ # prepending in front of a none existing anchor results in prepending to the head of the list
136
+ ([], "foo2", "/path2", "does not exist", [("foo2", "/path2")]),
137
+ ],
138
+ )
139
+ def test_prepend(
140
+ base_list: List[Tuple[str, str]],
141
+ provider: str,
142
+ path: str,
143
+ anchor_provider: SearchPathQuery,
144
+ result_list: List[Tuple[str, str]],
145
+ ) -> None:
146
+ csp = create_search_path(base_list)
147
+ csp.prepend(provider=provider, path=path, anchor=anchor_provider)
148
+ assert to_tuples_list(csp) == result_list
149
+
150
+
151
+ @pytest.mark.parametrize( # type:ignore
152
+ "calling_file, calling_module, config_path, expected",
153
+ [
154
+ ("foo.py", None, None, realpath("")),
155
+ ("foo/bar.py", None, None, realpath("foo")),
156
+ ("foo/bar.py", None, "conf", realpath("foo/conf")),
157
+ ("foo/bar.py", None, "../conf", realpath("conf")),
158
+ ("c:/foo/bar.py", None, "conf", realpath("c:/foo/conf")),
159
+ ("c:/foo/bar.py", None, "../conf", realpath("c:/conf")),
160
+ # short module name, keep it to avoid empty module error
161
+ (None, "module", None, "pkg://module"),
162
+ (None, "package.module", None, "pkg://package"),
163
+ (None, "package.module", "conf", "pkg://package/conf"),
164
+ # This is an unusual one. this behavior is intentional.
165
+ (None, "package.module", "../conf", "pkg://conf"),
166
+ (None, "package1.package2.module", "../conf", "pkg://package1/conf"),
167
+ # prefer package
168
+ ("foo", "package1.package2.module", "../conf", "pkg://package1/conf"),
169
+ ],
170
+ )
171
+ def test_compute_search_path_dir(
172
+ calling_file: str, calling_module: str, config_path: str, expected: str
173
+ ) -> None:
174
+ res = compute_search_path_dir(calling_file, calling_module, config_path)
175
+ assert res == expected
testbed/facebookresearch__hydra/tests/test_core_utils.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ from typing import Any
3
+
4
+ from omegaconf import open_dict
5
+
6
+ from hydra._internal.config_loader_impl import ConfigLoaderImpl
7
+ from hydra._internal.utils import create_config_search_path
8
+ from hydra.core import utils
9
+ from hydra.core.hydra_config import HydraConfig
10
+
11
+
12
+ def test_accessing_hydra_config(hydra_restore_singletons: Any) -> Any:
13
+ utils.setup_globals()
14
+
15
+ config_loader = ConfigLoaderImpl(
16
+ config_search_path=create_config_search_path("pkg://hydra.test_utils.configs")
17
+ )
18
+ cfg = config_loader.load_configuration(
19
+ config_name="accessing_hydra_config", overrides=[]
20
+ )
21
+ HydraConfig.instance().set_config(cfg)
22
+ with open_dict(cfg):
23
+ del cfg["hydra"]
24
+ assert cfg.job_name == "UNKNOWN_NAME"
25
+ assert cfg.config_name == "accessing_hydra_config"
testbed/facebookresearch__hydra/tests/test_hydra.py ADDED
@@ -0,0 +1,814 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ import os
3
+ import re
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Any, List, Set
8
+
9
+ import pytest
10
+ from omegaconf import DictConfig, OmegaConf
11
+
12
+ from hydra import MissingConfigException
13
+ from hydra.test_utils.test_utils import (
14
+ TSweepRunner,
15
+ TTaskRunner,
16
+ chdir_hydra_root,
17
+ integration_test,
18
+ verify_dir_outputs,
19
+ )
20
+
21
+ chdir_hydra_root()
22
+
23
+
24
+ @pytest.mark.parametrize( # type: ignore
25
+ "calling_file, calling_module", [(".", None), (None, ".")]
26
+ )
27
+ def test_missing_conf_dir(
28
+ hydra_restore_singletons: Any,
29
+ hydra_task_runner: TTaskRunner,
30
+ calling_file: str,
31
+ calling_module: str,
32
+ ) -> None:
33
+ with pytest.raises(MissingConfigException):
34
+ with hydra_task_runner(
35
+ calling_file=calling_file,
36
+ calling_module=calling_module,
37
+ config_path="dir_not_found",
38
+ config_name=None,
39
+ ):
40
+ pass
41
+
42
+
43
+ @pytest.mark.parametrize( # type: ignore
44
+ "calling_file, calling_module",
45
+ [
46
+ ("tests/test_apps/app_without_config/my_app.py", None),
47
+ (None, "tests.test_apps.app_without_config.my_app"),
48
+ ],
49
+ )
50
+ def test_missing_conf_file(
51
+ hydra_restore_singletons: Any,
52
+ hydra_task_runner: TTaskRunner,
53
+ calling_file: str,
54
+ calling_module: str,
55
+ ) -> None:
56
+ with pytest.raises(MissingConfigException):
57
+ with hydra_task_runner(
58
+ calling_file=calling_file,
59
+ calling_module=calling_module,
60
+ config_path=None,
61
+ config_name="not_found.yaml",
62
+ ):
63
+ pass
64
+
65
+
66
+ @pytest.mark.parametrize( # type: ignore
67
+ "calling_file, calling_module",
68
+ [
69
+ ("tests/test_apps/app_without_config/my_app.py", None),
70
+ (None, "tests.test_apps.app_without_config.my_app"),
71
+ ],
72
+ )
73
+ def test_app_without_config___no_overrides(
74
+ hydra_restore_singletons: Any,
75
+ hydra_task_runner: TTaskRunner,
76
+ calling_file: str,
77
+ calling_module: str,
78
+ ) -> None:
79
+ with hydra_task_runner(
80
+ calling_file=calling_file,
81
+ calling_module=calling_module,
82
+ config_path=None,
83
+ config_name=None,
84
+ ) as task:
85
+ assert task.job_ret is not None
86
+ assert task.job_ret.cfg == {}
87
+
88
+
89
+ @pytest.mark.parametrize( # type: ignore
90
+ "calling_file, calling_module",
91
+ [
92
+ ("tests/test_apps/hydra_main_rerun/my_app.py", None),
93
+ (None, "tests.test_apps.hydra_main_rerun.my_app"),
94
+ ],
95
+ )
96
+ def test_hydra_main_rerun(
97
+ hydra_restore_singletons: Any,
98
+ hydra_task_runner: TTaskRunner,
99
+ calling_file: str,
100
+ calling_module: str,
101
+ ) -> None:
102
+ with hydra_task_runner(
103
+ calling_file=calling_file,
104
+ calling_module=calling_module,
105
+ config_path=None,
106
+ config_name=None,
107
+ ) as task:
108
+ assert task.job_ret is not None
109
+ assert task.job_ret.cfg == {}
110
+
111
+
112
+ @pytest.mark.parametrize( # type: ignore
113
+ "calling_file, calling_module",
114
+ [
115
+ ("tests/test_apps/app_without_config/my_app.py", None),
116
+ (None, "tests.test_apps.app_without_config.my_app"),
117
+ ],
118
+ )
119
+ def test_app_without_config__with_append(
120
+ hydra_restore_singletons: Any,
121
+ hydra_task_runner: TTaskRunner,
122
+ calling_file: str,
123
+ calling_module: str,
124
+ ) -> None:
125
+ with hydra_task_runner(
126
+ calling_file=calling_file,
127
+ calling_module=calling_module,
128
+ config_path="",
129
+ config_name=None,
130
+ overrides=["+abc=123", "+a.b=1", "+a.a=2"],
131
+ ) as task:
132
+ assert task.job_ret is not None and task.job_ret.cfg == dict(
133
+ abc=123, a=dict(b=1, a=2)
134
+ )
135
+ verify_dir_outputs(task.job_ret, task.overrides)
136
+
137
+
138
+ @pytest.mark.parametrize( # type: ignore
139
+ "calling_file, calling_module",
140
+ [
141
+ ("tests/test_apps/app_with_cfg/my_app.py", None),
142
+ (None, "tests.test_apps.app_with_cfg.my_app"),
143
+ ],
144
+ )
145
+ def test_app_with_config_file__no_overrides(
146
+ hydra_restore_singletons: Any,
147
+ hydra_task_runner: TTaskRunner,
148
+ calling_file: str,
149
+ calling_module: str,
150
+ ) -> None:
151
+
152
+ task = hydra_task_runner(
153
+ calling_file=calling_file,
154
+ calling_module=calling_module,
155
+ config_path=None, # Testing legacy mode, both path and named are in config_path
156
+ config_name="config.yaml",
157
+ )
158
+ with task:
159
+ assert task.job_ret is not None and task.job_ret.cfg == {
160
+ "dataset": {"name": "imagenet", "path": "/datasets/imagenet"}
161
+ }
162
+
163
+ verify_dir_outputs(task.job_ret)
164
+
165
+
166
+ @pytest.mark.parametrize( # type: ignore
167
+ "calling_file, calling_module",
168
+ [
169
+ ("tests/test_apps/app_with_cfg_groups_no_header/my_app.py", None,),
170
+ (None, "tests.test_apps.app_with_cfg_groups_no_header.my_app",),
171
+ ],
172
+ )
173
+ def test_config_without_package_header_warnings(
174
+ hydra_restore_singletons: Any,
175
+ hydra_task_runner: TTaskRunner,
176
+ calling_file: str,
177
+ calling_module: str,
178
+ recwarn: Any,
179
+ ) -> None:
180
+ task = hydra_task_runner(
181
+ calling_file=calling_file,
182
+ calling_module=calling_module,
183
+ config_path="conf",
184
+ config_name="config.yaml",
185
+ )
186
+ with task:
187
+ assert task.job_ret is not None and task.job_ret.cfg == {
188
+ "optimizer": {"type": "nesterov", "lr": 0.001}
189
+ }
190
+
191
+ assert len(recwarn) == 1
192
+ msg = recwarn.pop().message.args[0]
193
+ assert "Missing @package directive optimizer/nesterov.yaml in " in msg
194
+ assert (
195
+ "See https://hydra.cc/docs/next/upgrades/0.11_to_1.0/adding_a_package_directive"
196
+ in msg
197
+ )
198
+
199
+
200
+ @pytest.mark.parametrize( # type: ignore
201
+ "calling_file, calling_module",
202
+ [
203
+ ("tests/test_apps/app_with_cfg_groups/my_app.py", None),
204
+ (None, "tests.test_apps.app_with_cfg_groups.my_app"),
205
+ ],
206
+ )
207
+ def test_app_with_config_path_backward_compatibility(
208
+ hydra_restore_singletons: Any,
209
+ hydra_task_runner: TTaskRunner,
210
+ calling_file: str,
211
+ calling_module: str,
212
+ ) -> None:
213
+ msg = (
214
+ "\nUsing config_path to specify the config name is deprecated, specify the config name via config_name"
215
+ "\nSee https://hydra.cc/next/upgrades/0.11_to_1.0/config_path_changes"
216
+ )
217
+
218
+ with pytest.warns(expected_warning=UserWarning, match=re.escape(msg)):
219
+ task = hydra_task_runner(
220
+ calling_file=calling_file,
221
+ calling_module=calling_module,
222
+ config_path="conf/config.yaml", # Testing legacy mode, both path and named are in config_path
223
+ config_name=None,
224
+ )
225
+ with task:
226
+ assert task.job_ret is not None and task.job_ret.cfg == {
227
+ "optimizer": {"type": "nesterov", "lr": 0.001}
228
+ }
229
+
230
+ verify_dir_outputs(task.job_ret)
231
+
232
+
233
+ @pytest.mark.parametrize( # type: ignore
234
+ "calling_file, calling_module",
235
+ [
236
+ ("tests/test_apps/app_with_cfg/my_app.py", None),
237
+ (None, "tests.test_apps.app_with_cfg.my_app"),
238
+ ],
239
+ )
240
+ def test_app_with_config_file__with_overide(
241
+ hydra_restore_singletons: Any,
242
+ hydra_task_runner: TTaskRunner,
243
+ calling_file: str,
244
+ calling_module: str,
245
+ ) -> None:
246
+ with hydra_task_runner(
247
+ calling_file=calling_file,
248
+ calling_module=calling_module,
249
+ config_path=None,
250
+ config_name="config.yaml",
251
+ overrides=["dataset.path=/datasets/imagenet2"],
252
+ ) as task:
253
+ assert task.job_ret is not None and task.job_ret.cfg == dict(
254
+ dataset=dict(name="imagenet", path="/datasets/imagenet2")
255
+ )
256
+ verify_dir_outputs(task.job_ret, task.overrides)
257
+
258
+
259
+ @pytest.mark.parametrize( # type: ignore
260
+ "calling_file, calling_module",
261
+ [
262
+ ("tests/test_apps/app_with_split_cfg/my_app.py", None),
263
+ (None, "tests.test_apps.app_with_split_cfg.my_app"),
264
+ ],
265
+ )
266
+ def test_app_with_split_config(
267
+ hydra_restore_singletons: Any,
268
+ hydra_task_runner: TTaskRunner,
269
+ calling_file: str,
270
+ calling_module: str,
271
+ ) -> None:
272
+ with hydra_task_runner(
273
+ calling_file=calling_file,
274
+ calling_module=calling_module,
275
+ config_path=None,
276
+ config_name="config.yaml",
277
+ ) as task:
278
+ assert task.job_ret is not None and task.job_ret.cfg == dict(
279
+ dataset=dict(name="imagenet", path="/datasets/imagenet"),
280
+ optimizer=dict(lr=0.001, type="nesterov"),
281
+ )
282
+ verify_dir_outputs(task.job_ret)
283
+
284
+
285
+ @pytest.mark.parametrize( # type: ignore
286
+ "calling_file, calling_module",
287
+ [
288
+ ("tests/test_apps/app_with_cfg_groups/my_app.py", None),
289
+ (None, "tests.test_apps.app_with_cfg_groups.my_app"),
290
+ ],
291
+ )
292
+ def test_app_with_config_groups__override_dataset__wrong(
293
+ hydra_restore_singletons: Any,
294
+ hydra_task_runner: TTaskRunner,
295
+ calling_file: str,
296
+ calling_module: str,
297
+ ) -> None:
298
+ with pytest.raises(MissingConfigException) as ex:
299
+ with hydra_task_runner(
300
+ calling_file=calling_file,
301
+ calling_module=calling_module,
302
+ config_path="conf",
303
+ config_name=None,
304
+ overrides=["+optimizer=wrong_name"],
305
+ ):
306
+ pass
307
+ assert sorted(ex.value.options) == sorted(["adam", "nesterov"])
308
+
309
+
310
+ @pytest.mark.parametrize( # type: ignore
311
+ "calling_file, calling_module",
312
+ [
313
+ ("tests/test_apps/app_with_cfg_groups/my_app.py", None),
314
+ (None, "tests.test_apps.app_with_cfg_groups.my_app"),
315
+ ],
316
+ )
317
+ def test_app_with_config_groups__override_all_configs(
318
+ hydra_restore_singletons: Any,
319
+ hydra_task_runner: TTaskRunner,
320
+ calling_file: str,
321
+ calling_module: str,
322
+ ) -> None:
323
+ with hydra_task_runner(
324
+ calling_file=calling_file,
325
+ calling_module=calling_module,
326
+ config_path="conf",
327
+ config_name=None,
328
+ overrides=["+optimizer=adam", "optimizer.lr=10"],
329
+ ) as task:
330
+ assert task.job_ret is not None and task.job_ret.cfg == dict(
331
+ optimizer=dict(type="adam", lr=10, beta=0.01)
332
+ )
333
+ verify_dir_outputs(task.job_ret, overrides=task.overrides)
334
+
335
+
336
+ @pytest.mark.parametrize( # type: ignore
337
+ "calling_file, calling_module",
338
+ [
339
+ ("tests/test_apps/app_with_custom_launcher/my_app.py", None),
340
+ (None, "tests.test_apps.app_with_custom_launcher.my_app"),
341
+ ],
342
+ )
343
+ def test_app_with_sweep_cfg__override_to_basic_launcher(
344
+ hydra_restore_singletons: Any,
345
+ hydra_task_runner: TTaskRunner,
346
+ calling_file: str,
347
+ calling_module: str,
348
+ ) -> None:
349
+ with hydra_task_runner(
350
+ calling_file=calling_file,
351
+ calling_module=calling_module,
352
+ config_path=None,
353
+ config_name="config.yaml",
354
+ overrides=["hydra/launcher=basic"],
355
+ ) as task:
356
+ assert task.job_ret is not None
357
+ assert task.job_ret.hydra_cfg is not None
358
+ hydra_cfg = task.job_ret.hydra_cfg
359
+ assert (
360
+ hydra_cfg.hydra.launcher.cls
361
+ == "hydra._internal.core_plugins.basic_launcher.BasicLauncher"
362
+ )
363
+ assert len(task.job_ret.hydra_cfg.hydra.launcher.params) == 0
364
+
365
+
366
+ def test_short_module_name(tmpdir: Path) -> None:
367
+ cmd = [
368
+ sys.executable,
369
+ "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py",
370
+ "hydra.run.dir=" + str(tmpdir),
371
+ ]
372
+ result = subprocess.check_output(cmd)
373
+ assert OmegaConf.create(str(result.decode("utf-8"))) == {
374
+ "db": {"driver": "mysql", "password": "secret", "user": "omry"}
375
+ }
376
+
377
+
378
+ def test_hydra_main_module_override_name(tmpdir: Path) -> None:
379
+ cfg = OmegaConf.create()
380
+ integration_test(
381
+ tmpdir=tmpdir,
382
+ task_config=cfg,
383
+ overrides=[],
384
+ prints="HydraConfig.get().job.name",
385
+ expected_outputs="Foo",
386
+ env_override={"HYDRA_MAIN_MODULE": "hydra.test_utils.configs.Foo"},
387
+ )
388
+
389
+
390
+ def test_short_hydra_main_module_override_name(tmpdir: Path) -> None:
391
+ cfg = OmegaConf.create()
392
+ integration_test(
393
+ tmpdir=tmpdir,
394
+ task_config=cfg,
395
+ overrides=[],
396
+ prints="HydraConfig.get().job.name",
397
+ expected_outputs="Foo",
398
+ env_override={"HYDRA_MAIN_MODULE": "Foo"},
399
+ )
400
+
401
+
402
+ @pytest.mark.parametrize( # type: ignore
403
+ "env_name", ["HYDRA_MAIN_MODULE", "FB_PAR_MAIN_MODULE", "FB_XAR_MAIN_MODULE"]
404
+ )
405
+ def test_module_env_override(tmpdir: Path, env_name: str) -> None:
406
+ """
407
+ Tests that module name overrides are working.
408
+ """
409
+ cmd = [
410
+ sys.executable,
411
+ "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py",
412
+ "hydra.run.dir=" + str(tmpdir),
413
+ ]
414
+ modified_env = os.environ.copy()
415
+ modified_env[env_name] = "hydra.test_utils.configs.Foo"
416
+ result = subprocess.check_output(cmd, env=modified_env)
417
+ assert OmegaConf.create(str(result.decode("utf-8"))) == {"normal_yaml_config": True}
418
+
419
+
420
+ @pytest.mark.parametrize( # type: ignore
421
+ "flag,expected_keys",
422
+ [("--cfg=all", ["db", "hydra"]), ("--cfg=hydra", ["hydra"]), ("--cfg=job", ["db"])],
423
+ )
424
+ def test_cfg(tmpdir: Path, flag: str, expected_keys: List[str]) -> None:
425
+ cmd = [
426
+ sys.executable,
427
+ "examples/tutorials/basic/your_first_hydra_app/5_defaults/my_app.py",
428
+ "hydra.run.dir=" + str(tmpdir),
429
+ flag,
430
+ ]
431
+ result = subprocess.check_output(cmd)
432
+ conf = OmegaConf.create(str(result.decode("utf-8")))
433
+ for key in expected_keys:
434
+ assert key in conf
435
+
436
+
437
+ @pytest.mark.parametrize( # type: ignore
438
+ "flags,expected",
439
+ [
440
+ (
441
+ ["--cfg=job", "--package=_global_"],
442
+ """# @package _global_
443
+ db:
444
+ driver: mysql
445
+ user: omry
446
+ pass: secret
447
+ """,
448
+ ),
449
+ (
450
+ ["--cfg=job", "--package=db"],
451
+ """# @package db
452
+ driver: mysql
453
+ user: omry
454
+ pass: secret
455
+ """,
456
+ ),
457
+ (["--cfg=job", "--package=db.driver"], "mysql\n"),
458
+ ],
459
+ )
460
+ def test_cfg_with_package(tmpdir: Path, flags: List[str], expected: str) -> None:
461
+ cmd = [
462
+ sys.executable,
463
+ "examples/tutorials/basic/your_first_hydra_app/5_defaults/my_app.py",
464
+ "hydra.run.dir=" + str(tmpdir),
465
+ ] + flags
466
+
467
+ def norm(s: str) -> str:
468
+ return s.replace("\r\n", "\n").replace("\r", "\n")
469
+
470
+ result = subprocess.check_output(cmd).decode("utf-8")
471
+ assert norm(result) == norm(expected)
472
+
473
+
474
+ @pytest.mark.parametrize( # type: ignore
475
+ "calling_file, calling_module",
476
+ [
477
+ ("tests/test_apps/app_with_config_with_free_group/my_app.py", None),
478
+ (None, "tests.test_apps.app_with_config_with_free_group.my_app"),
479
+ ],
480
+ )
481
+ @pytest.mark.parametrize("overrides", [["+free_group=opt1,opt2"]]) # type: ignore
482
+ def test_multirun_with_free_override(
483
+ hydra_restore_singletons: Any,
484
+ hydra_sweep_runner: TSweepRunner,
485
+ calling_file: str,
486
+ calling_module: str,
487
+ overrides: List[str],
488
+ ) -> None:
489
+ sweep = hydra_sweep_runner(
490
+ calling_file=calling_file,
491
+ calling_module=calling_module,
492
+ config_path="conf/",
493
+ config_name="config.yaml",
494
+ task_function=None,
495
+ overrides=overrides,
496
+ )
497
+ with sweep:
498
+ assert sweep.returns is not None and len(sweep.returns[0]) == 2
499
+ assert sweep.returns[0][0].overrides == ["+free_group=opt1"]
500
+ assert sweep.returns[0][0].cfg == {"group_opt1": True, "free_group_opt1": True}
501
+ assert sweep.returns[0][1].overrides == ["+free_group=opt2"]
502
+ assert sweep.returns[0][1].cfg == {"group_opt1": True, "free_group_opt2": True}
503
+
504
+
505
+ @pytest.mark.parametrize( # type: ignore
506
+ "calling_file, calling_module",
507
+ [
508
+ pytest.param(
509
+ "tests/test_apps/sweep_complex_defaults/my_app.py", None, id="file_path"
510
+ ),
511
+ pytest.param(
512
+ None, "tests.test_apps.sweep_complex_defaults.my_app", id="pkg_path"
513
+ ),
514
+ ],
515
+ )
516
+ def test_sweep_complex_defaults(
517
+ hydra_restore_singletons: Any,
518
+ hydra_sweep_runner: TSweepRunner,
519
+ calling_file: str,
520
+ calling_module: str,
521
+ ) -> None:
522
+ with hydra_sweep_runner(
523
+ calling_file=calling_file,
524
+ calling_module=calling_module,
525
+ config_path="conf",
526
+ config_name="config.yaml",
527
+ task_function=None,
528
+ overrides=["optimizer=adam,nesterov"],
529
+ ) as sweep:
530
+ assert sweep.returns is not None and len(sweep.returns[0]) == 2
531
+ assert sweep.returns[0][0].overrides == ["optimizer=adam"]
532
+ assert sweep.returns[0][1].overrides == ["optimizer=nesterov"]
533
+
534
+
535
+ @pytest.mark.parametrize( # type: ignore
536
+ "script, flag, overrides,expected",
537
+ [
538
+ pytest.param(
539
+ "examples/tutorials/basic/your_first_hydra_app/1_simple_cli/my_app.py",
540
+ "--help",
541
+ ["hydra.help.template=foo"],
542
+ "foo\n",
543
+ id="simple_cli_app",
544
+ ),
545
+ pytest.param(
546
+ "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py",
547
+ "--help",
548
+ ["hydra.help.template=foo"],
549
+ "foo\n",
550
+ id="overriding_help_template",
551
+ ),
552
+ pytest.param(
553
+ "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py",
554
+ "--help",
555
+ ["hydra.help.template=$CONFIG", "db.user=root"],
556
+ """db:
557
+ driver: mysql
558
+ user: root
559
+ password: secret
560
+
561
+ """,
562
+ id="overriding_help_template:$CONFIG",
563
+ ),
564
+ pytest.param(
565
+ "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py",
566
+ "--help",
567
+ ["hydra.help.template=$FLAGS_HELP"],
568
+ """--help,-h : Application's help
569
+ --hydra-help : Hydra's help
570
+ --version : show program's version number and exit
571
+ --cfg,-c : Show config instead of running [job|hydra|all]
572
+ --package,-p : Config package to show
573
+ --run,-r : Run a job
574
+ --multirun,-m : Run multiple jobs with the configured launcher
575
+ --shell-completion,-sc : Install or Uninstall shell completion:
576
+ Bash - Install:
577
+ eval "$(python {script} -sc install=bash)"
578
+ Bash - Uninstall:
579
+ eval "$(python {script} -sc uninstall=bash)"
580
+
581
+ Fish - Install:
582
+ python {script} -sc install=fish | source
583
+ Fish - Uninstall:
584
+ python {script} -sc uninstall=fish | source
585
+
586
+ --config-path,-cp : Overrides the config_path specified in hydra.main().
587
+ The config_path is relative to the Python file declaring @hydra.main()
588
+ --config-name,-cn : Overrides the config_name specified in hydra.main()
589
+ --info,-i : Print Hydra information
590
+ Overrides : Any key=value arguments to override config values (use dots for.nested=overrides)
591
+ """,
592
+ id="overriding_help_template:$FLAGS_HELP",
593
+ ),
594
+ pytest.param(
595
+ "examples/tutorials/basic/your_first_hydra_app/4_config_groups/my_app.py",
596
+ "--help",
597
+ ["hydra.help.template=$APP_CONFIG_GROUPS"],
598
+ """db: mysql, postgresql
599
+
600
+ """,
601
+ id="overriding_help_template:$APP_CONFIG_GROUPS",
602
+ ),
603
+ pytest.param(
604
+ "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py",
605
+ "--hydra-help",
606
+ ["hydra.hydra_help.template=foo"],
607
+ "foo\n",
608
+ id="overriding_hydra_help_template",
609
+ ),
610
+ pytest.param(
611
+ "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py",
612
+ "--hydra-help",
613
+ ["hydra.hydra_help.template=$FLAGS_HELP"],
614
+ """--help,-h : Application's help
615
+ --hydra-help : Hydra's help
616
+ --version : show program's version number and exit
617
+ --cfg,-c : Show config instead of running [job|hydra|all]
618
+ --package,-p : Config package to show
619
+ --run,-r : Run a job
620
+ --multirun,-m : Run multiple jobs with the configured launcher
621
+ --shell-completion,-sc : Install or Uninstall shell completion:
622
+ Bash - Install:
623
+ eval "$(python {script} -sc install=bash)"
624
+ Bash - Uninstall:
625
+ eval "$(python {script} -sc uninstall=bash)"
626
+
627
+ Fish - Install:
628
+ python {script} -sc install=fish | source
629
+ Fish - Uninstall:
630
+ python {script} -sc uninstall=fish | source
631
+
632
+ --config-path,-cp : Overrides the config_path specified in hydra.main().
633
+ The config_path is relative to the Python file declaring @hydra.main()
634
+ --config-name,-cn : Overrides the config_name specified in hydra.main()
635
+ --info,-i : Print Hydra information
636
+ Overrides : Any key=value arguments to override config values (use dots for.nested=overrides)
637
+ """,
638
+ id="overriding_hydra_help_template:$FLAGS_HELP",
639
+ ),
640
+ ],
641
+ )
642
+ def test_help(
643
+ tmpdir: Path, script: str, flag: str, overrides: List[str], expected: Any,
644
+ ) -> None:
645
+ cmd = [sys.executable, script, "hydra.run.dir=" + str(tmpdir)]
646
+ cmd.extend(overrides)
647
+ cmd.append(flag)
648
+ print(" ".join(cmd))
649
+ result = str(subprocess.check_output(cmd).decode("utf-8"))
650
+ # normalize newlines on Windows to make testing easier
651
+ result = result.replace("\r\n", "\n")
652
+ assert result == expected.format(script=script)
653
+
654
+
655
+ @pytest.mark.parametrize( # type: ignore
656
+ "calling_file, calling_module",
657
+ [
658
+ ("tests/test_apps/interpolating_dir_hydra_to_app/my_app.py", None),
659
+ (None, "tests.test_apps.interpolating_dir_hydra_to_app.my_app"),
660
+ ],
661
+ )
662
+ def test_interpolating_dir_hydra_to_app(
663
+ hydra_restore_singletons: Any,
664
+ hydra_task_runner: TTaskRunner,
665
+ calling_file: str,
666
+ calling_module: str,
667
+ ) -> None:
668
+ basedir = "foo"
669
+ with hydra_task_runner(
670
+ calling_file=calling_file,
671
+ calling_module=calling_module,
672
+ config_path=None,
673
+ config_name="config.yaml",
674
+ overrides=["experiment.base_dir=" + basedir],
675
+ ) as task:
676
+ assert task.temp_dir is not None
677
+ path = Path(task.temp_dir) / basedir
678
+ assert path.exists()
679
+
680
+
681
+ def test_sys_exit(tmpdir: Path) -> None:
682
+ cmd = [
683
+ sys.executable,
684
+ "tests/test_apps/sys_exit/my_app.py",
685
+ "hydra.run.dir=" + str(tmpdir),
686
+ ]
687
+ assert subprocess.run(cmd).returncode == 42
688
+
689
+
690
+ @pytest.mark.parametrize( # type: ignore
691
+ "task_config, overrides, expected_dir",
692
+ [
693
+ ({"hydra": {"run": {"dir": "foo"}}}, [], "foo"),
694
+ ({}, ["hydra.run.dir=bar"], "bar"),
695
+ ({"hydra": {"run": {"dir": "foo"}}}, ["hydra.run.dir=boom"], "boom"),
696
+ (
697
+ {
698
+ "hydra": {"run": {"dir": "foo-${hydra.job.override_dirname}"}},
699
+ "app": {"a": 1, "b": 2},
700
+ },
701
+ ["app.a=20"],
702
+ "foo-app.a=20",
703
+ ),
704
+ ],
705
+ )
706
+ def test_local_run_workdir(
707
+ tmpdir: Path, task_config: DictConfig, overrides: List[str], expected_dir: str
708
+ ) -> None:
709
+ cfg = OmegaConf.create(task_config)
710
+ assert isinstance(cfg, DictConfig)
711
+ expected_dir1 = tmpdir / expected_dir
712
+ integration_test(
713
+ tmpdir=tmpdir,
714
+ task_config=cfg,
715
+ overrides=overrides,
716
+ prints="os.getcwd()",
717
+ expected_outputs=str(expected_dir1),
718
+ )
719
+
720
+
721
+ def test_hydra_env_set(tmpdir: Path) -> None:
722
+ cfg = OmegaConf.create({"hydra": {"job": {"env_set": {"foo": "bar"}}}})
723
+ integration_test(
724
+ tmpdir=tmpdir,
725
+ task_config=cfg,
726
+ overrides=[],
727
+ prints="os.environ['foo']",
728
+ expected_outputs="bar",
729
+ )
730
+
731
+
732
+ @pytest.mark.parametrize( # type: ignore
733
+ "override", [pytest.param("xyz", id="db=xyz"), pytest.param("", id="db=")]
734
+ )
735
+ @pytest.mark.parametrize( # type: ignore
736
+ "calling_file, calling_module",
737
+ [
738
+ pytest.param("hydra/test_utils/example_app.py", None, id="file"),
739
+ pytest.param(None, "hydra.test_utils.example_app", id="module"),
740
+ ],
741
+ )
742
+ def test_override_with_invalid_group_choice(
743
+ hydra_restore_singletons: Any,
744
+ hydra_task_runner: TTaskRunner,
745
+ calling_file: str,
746
+ calling_module: str,
747
+ override: str,
748
+ ) -> None:
749
+ msg = f"""Could not load db/{override}, available options:\ndb:\n\tmysql\n\tpostgresql"""
750
+
751
+ with pytest.raises(MissingConfigException, match=re.escape(msg)):
752
+ with hydra_task_runner(
753
+ calling_file=calling_file,
754
+ calling_module=calling_module,
755
+ config_path="configs",
756
+ config_name="db_conf",
757
+ overrides=[f"db={override}"],
758
+ ):
759
+ ...
760
+
761
+
762
+ @pytest.mark.parametrize("config_path", ["dir1", "dir2"]) # type: ignore
763
+ @pytest.mark.parametrize("config_name", ["cfg1", "cfg2"]) # type: ignore
764
+ def test_config_name_and_path_overrides(
765
+ tmpdir: Path, config_path: str, config_name: str
766
+ ) -> None:
767
+ cmd = [
768
+ sys.executable,
769
+ "tests/test_apps/app_with_multiple_config_dirs/my_app.py",
770
+ "hydra.run.dir=" + str(tmpdir),
771
+ f"--config-name={config_name}",
772
+ f"--config-path={config_path}",
773
+ ]
774
+ print(" ".join(cmd))
775
+ result = str(subprocess.check_output(cmd).decode("utf-8")).strip()
776
+ # normalize newlines on Windows to make testing easier
777
+ result = result.replace("\r\n", "\n")
778
+ assert result == f"{config_path}_{config_name}: true"
779
+
780
+
781
+ @pytest.mark.parametrize( # type: ignore
782
+ "overrides, expected_files",
783
+ [
784
+ ([], {"my_app.log", ".hydra"}),
785
+ (["hydra.output_subdir=foo"], {"my_app.log", "foo"}),
786
+ (["hydra.output_subdir=null"], {"my_app.log"}),
787
+ ],
788
+ )
789
+ @pytest.mark.parametrize( # type: ignore
790
+ "calling_file, calling_module",
791
+ [
792
+ ("tests/test_apps/app_with_cfg/my_app.py", None),
793
+ (None, "tests.test_apps.app_with_cfg.my_app"),
794
+ ],
795
+ )
796
+ def test_hydra_output_dir(
797
+ hydra_restore_singletons: Any,
798
+ hydra_task_runner: TTaskRunner,
799
+ calling_file: str,
800
+ calling_module: str,
801
+ overrides: List[str],
802
+ expected_files: Set[str],
803
+ ) -> None:
804
+ with hydra_task_runner(
805
+ calling_file=calling_file,
806
+ calling_module=calling_module,
807
+ config_path=None,
808
+ config_name=None,
809
+ overrides=overrides,
810
+ ) as task:
811
+ assert task.temp_dir is not None
812
+ path = Path(task.temp_dir)
813
+ files = set([str(x)[len(task.temp_dir) + 1 :] for x in path.iterdir()])
814
+ assert files == expected_files
testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/setup.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ from setuptools import find_namespace_packages, setup
3
+
4
+ setup(
5
+ name="hydra-namespace-test-plugin",
6
+ version="0.1.0",
7
+ author="Omry Yadan",
8
+ author_email="omry@fb.com",
9
+ url="https://github.com/facebookresearch/hydra/",
10
+ packages=find_namespace_packages(include=["some_namespace.*"]),
11
+ install_requires=["hydra-core==1.0.*"],
12
+ )
testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/level1/level2/nested1.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # @package _global_
2
+ l1_l2_n1: true
testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/explicit.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # @package a.b
2
+ foo: bar
testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/group_name.yaml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # @package foo._group_._name_
2
+ foo: bar
testbed/facebookresearch__hydra/tests/test_utils.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ import copy
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Any, Dict, Optional
6
+
7
+ import pytest
8
+ from omegaconf import DictConfig, OmegaConf
9
+
10
+ import hydra._internal.utils as internal_utils
11
+ from hydra import utils
12
+ from hydra.conf import HydraConf, RuntimeConf
13
+ from hydra.core.hydra_config import HydraConfig
14
+ from hydra.types import ObjectConf
15
+
16
+
17
+ def some_method() -> int:
18
+ return 42
19
+
20
+
21
+ class Bar:
22
+ def __init__(self, a: Any, b: Any, c: Any, d: Any = "default_value") -> None:
23
+ self.a = a
24
+ self.b = b
25
+ self.c = c
26
+ self.d = d
27
+
28
+ def __repr__(self) -> str:
29
+ return f"a={self.a}, b={self.b}, c={self.c}, d={self.d}"
30
+
31
+ @staticmethod
32
+ def static_method() -> int:
33
+ return 43
34
+
35
+ def __eq__(self, other: Any) -> Any:
36
+ """Overrides the default implementation"""
37
+ if isinstance(other, Bar):
38
+
39
+ return (
40
+ self.a == other.a
41
+ and self.b == other.b
42
+ and self.c == other.c
43
+ and self.d == other.d
44
+ )
45
+ return NotImplemented
46
+
47
+ def __ne__(self, other: Any) -> Any:
48
+ """Overrides the default implementation (unnecessary in Python 3)"""
49
+ x = self.__eq__(other)
50
+ if x is not NotImplemented:
51
+ return not x
52
+ return NotImplemented
53
+
54
+
55
+ class Foo:
56
+ def __init__(self, x: int) -> None:
57
+ self.x = x
58
+
59
+ def __eq__(self, other: Any) -> Any:
60
+ if isinstance(other, Foo):
61
+ return self.x == other.x
62
+ return False
63
+
64
+
65
+ class Baz(Foo):
66
+ @classmethod
67
+ def class_method(self, y: int) -> Any:
68
+ return self(y + 1)
69
+
70
+ @staticmethod
71
+ def static_method(z: int) -> int:
72
+ return z
73
+
74
+
75
+ class Fii:
76
+ def __init__(self, a: Baz = Baz(10)):
77
+ self.a = a
78
+
79
+ def __repr__(self) -> str:
80
+ return f"a={self.a}"
81
+
82
+ def __eq__(self, other: Any) -> Any:
83
+ """Overrides the default implementation"""
84
+ if isinstance(other, Fii):
85
+
86
+ return self.a == other.a
87
+ return NotImplemented
88
+
89
+ def __ne__(self, other: Any) -> Any:
90
+ """Overrides the default implementation (unnecessary in Python 3)"""
91
+ x = self.__eq__(other)
92
+ if x is not NotImplemented:
93
+ return not x
94
+ return NotImplemented
95
+
96
+
97
+ fii = Fii()
98
+
99
+
100
+ def fum(k: int) -> int:
101
+ return k + 1
102
+
103
+
104
+ @pytest.mark.parametrize( # type: ignore
105
+ "path,expected_type", [("tests.test_utils.Bar", Bar)]
106
+ )
107
+ def test_get_class(path: str, expected_type: type) -> None:
108
+ assert utils.get_class(path) == expected_type
109
+
110
+
111
+ @pytest.mark.parametrize( # type: ignore
112
+ "path,return_value", [("tests.test_utils.some_method", 42)]
113
+ )
114
+ def test_get_method(path: str, return_value: Any) -> None:
115
+ assert utils.get_method(path)() == return_value
116
+
117
+
118
+ @pytest.mark.parametrize( # type: ignore
119
+ "path,return_value", [("tests.test_utils.Bar.static_method", 43)]
120
+ )
121
+ def test_get_static_method(path: str, return_value: Any) -> None:
122
+ assert utils.get_static_method(path)() == return_value
123
+
124
+
125
+ @pytest.mark.parametrize( # type: ignore
126
+ "input_conf, key_to_get_config, kwargs_to_pass, expected",
127
+ [
128
+ (
129
+ {
130
+ "cls": "tests.test_utils.Bar",
131
+ "params": {"a": 10, "b": 20, "c": 30, "d": 40},
132
+ },
133
+ None,
134
+ {},
135
+ Bar(10, 20, 30, 40),
136
+ ),
137
+ (
138
+ {
139
+ "all_params": {
140
+ "main": {
141
+ "cls": "tests.test_utils.Bar",
142
+ "params": {"a": 10, "b": 20, "c": "${all_params.aux.c}"},
143
+ },
144
+ "aux": {"c": 30},
145
+ }
146
+ },
147
+ "all_params.main",
148
+ {"d": 40},
149
+ Bar(10, 20, 30, 40),
150
+ ),
151
+ (
152
+ {"cls": "tests.test_utils.Bar", "params": {"b": 20, "c": 30}},
153
+ None,
154
+ {"a": 10, "d": 40},
155
+ Bar(10, 20, 30, 40),
156
+ ),
157
+ (
158
+ {"cls": "tests.test_utils.Bar", "params": {"b": 200, "c": "${params.b}"}},
159
+ None,
160
+ {"a": 10, "d": 40},
161
+ Bar(10, 200, 200, 40),
162
+ ),
163
+ # Check class and static methods
164
+ (
165
+ {"cls": "tests.test_utils.Baz.class_method", "params": {"y": 10}},
166
+ None,
167
+ {},
168
+ Baz(11),
169
+ ),
170
+ (
171
+ {"cls": "tests.test_utils.Baz.static_method", "params": {"z": 43}},
172
+ None,
173
+ {},
174
+ 43,
175
+ ),
176
+ # Check nested types and static methods
177
+ ({"cls": "tests.test_utils.Fii", "params": {}}, None, {}, Fii(Baz(10)),),
178
+ (
179
+ {"cls": "tests.test_utils.fii.a.class_method", "params": {"y": 10}},
180
+ None,
181
+ {},
182
+ Baz(11),
183
+ ),
184
+ (
185
+ {"cls": "tests.test_utils.fii.a.static_method", "params": {"z": 43}},
186
+ None,
187
+ {},
188
+ 43,
189
+ ),
190
+ # Check that default value is respected
191
+ (
192
+ {"cls": "tests.test_utils.Bar", "params": {"b": 200, "c": "${params.b}"}},
193
+ None,
194
+ {"a": 10},
195
+ Bar(10, 200, 200, "default_value"),
196
+ ),
197
+ (
198
+ {"cls": "tests.test_utils.Bar", "params": {}},
199
+ None,
200
+ {"a": 10, "b": 20, "c": 30},
201
+ Bar(10, 20, 30, "default_value"),
202
+ ),
203
+ # call a function from a module
204
+ ({"cls": "tests.test_utils.fum", "params": {"k": 43}}, None, {}, 44,),
205
+ # Check builtins
206
+ ({"cls": "builtins.str", "params": {"object": 43}}, None, {}, "43",),
207
+ ],
208
+ )
209
+ def test_class_instantiate(
210
+ input_conf: Dict[str, Any],
211
+ key_to_get_config: Optional[str],
212
+ kwargs_to_pass: Dict[str, Any],
213
+ expected: Any,
214
+ ) -> Any:
215
+ conf = OmegaConf.create(input_conf)
216
+ assert isinstance(conf, DictConfig)
217
+ if key_to_get_config is None:
218
+ config_to_pass = conf
219
+ else:
220
+ config_to_pass = OmegaConf.select(conf, key_to_get_config)
221
+ config_to_pass_copy = copy.deepcopy(config_to_pass)
222
+ obj = utils.instantiate(config_to_pass, **kwargs_to_pass)
223
+ assert obj == expected
224
+ # make sure config is not modified by instantiate
225
+ assert config_to_pass == config_to_pass_copy
226
+
227
+
228
+ def test_class_instantiate_pass_omegaconf_node() -> Any:
229
+ pc = ObjectConf()
230
+ # This is a bit clunky because it exposes a problem with the backport of dataclass on Python 3.6
231
+ # see: https://github.com/ericvsmith/dataclasses/issues/155
232
+ pc.cls = "tests.test_utils.Bar"
233
+ pc.params = {"b": 200, "c": {"x": 10, "y": "${params.b}"}}
234
+ conf = OmegaConf.structured(pc)
235
+ obj = utils.instantiate(conf, **{"a": 10, "d": Foo(99)})
236
+ assert obj == Bar(10, 200, {"x": 10, "y": 200}, Foo(99))
237
+ assert OmegaConf.is_config(obj.c)
238
+
239
+
240
+ def test_class_warning() -> None:
241
+ expected = Bar(10, 20, 30, 40)
242
+ with pytest.warns(UserWarning):
243
+ config = OmegaConf.structured(
244
+ {
245
+ "class": "tests.test_utils.Bar",
246
+ "params": {"a": 10, "b": 20, "c": 30, "d": 40},
247
+ }
248
+ )
249
+ assert utils.instantiate(config) == expected
250
+
251
+ config = OmegaConf.structured(
252
+ {"cls": "tests.test_utils.Bar", "params": {"a": 10, "b": 20, "c": 30, "d": 40}}
253
+ )
254
+ assert utils.instantiate(config) == expected
255
+
256
+
257
+ def test_get_original_cwd(hydra_restore_singletons: Any) -> None:
258
+ orig = "/foo/bar"
259
+ cfg = OmegaConf.create({"hydra": HydraConf(runtime=RuntimeConf(cwd=orig))})
260
+ assert isinstance(cfg, DictConfig)
261
+ HydraConfig.instance().set_config(cfg)
262
+ assert utils.get_original_cwd() == orig
263
+
264
+
265
+ def test_get_original_cwd_without_hydra(hydra_restore_singletons: Any) -> None:
266
+ with pytest.raises(ValueError):
267
+ utils.get_original_cwd()
268
+
269
+
270
+ @pytest.mark.parametrize( # type: ignore
271
+ "orig_cwd, path, expected",
272
+ [
273
+ ("/home/omry/hydra", "foo/bar", "/home/omry/hydra/foo/bar"),
274
+ ("/home/omry/hydra/", "foo/bar", "/home/omry/hydra/foo/bar"),
275
+ ("/home/omry/hydra/", "/foo/bar", "/foo/bar"),
276
+ ],
277
+ )
278
+ def test_to_absolute_path(
279
+ hydra_restore_singletons: Any, orig_cwd: str, path: str, expected: str
280
+ ) -> None:
281
+ # normalize paths to current OS
282
+ orig_cwd = str(Path(orig_cwd))
283
+ path = str(Path(path))
284
+ expected = str(Path(expected))
285
+ cfg = OmegaConf.create({"hydra": HydraConf(runtime=RuntimeConf(cwd=orig_cwd))})
286
+ assert isinstance(cfg, DictConfig)
287
+ HydraConfig().set_config(cfg)
288
+ assert utils.to_absolute_path(path) == expected
289
+
290
+
291
+ @pytest.mark.parametrize( # type: ignore
292
+ "path, expected",
293
+ [
294
+ ("foo/bar", f"{os.getcwd()}/foo/bar"),
295
+ ("foo/bar", f"{os.getcwd()}/foo/bar"),
296
+ ("/foo/bar", os.path.abspath("/foo/bar")),
297
+ ],
298
+ )
299
+ def test_to_absolute_path_without_hydra(
300
+ hydra_restore_singletons: Any, path: str, expected: str
301
+ ) -> None:
302
+ # normalize paths to current OS
303
+ path = str(Path(path))
304
+ expected = str(Path(expected).absolute())
305
+ assert utils.to_absolute_path(path) == expected
306
+
307
+
308
+ @pytest.mark.parametrize( # type: ignore
309
+ "matrix,expected",
310
+ [
311
+ ([["a"]], [1]),
312
+ ([["a", "bb"]], [1, 2]),
313
+ ([["a", "bb"], ["aa", "b"]], [2, 2]),
314
+ ([["a"], ["aa", "b"]], [2, 1]),
315
+ ([["a", "aa"], ["bb"]], [2, 2]),
316
+ ([["a"]], [1]),
317
+ ([["a"]], [1]),
318
+ ([["a"]], [1]),
319
+ ],
320
+ )
321
+ def test_get_column_widths(matrix: Any, expected: Any) -> None:
322
+ assert internal_utils.get_column_widths(matrix) == expected
testbed/facebookresearch__hydra/website/.gitignore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dependencies
2
+ /node_modules
3
+
4
+ # production
5
+ /build
6
+
7
+ # generated files
8
+ .docusaurus
9
+ .cache-loader
10
+
11
+ # misc
12
+ .DS_Store
13
+ .env.local
14
+ .env.development.local
15
+ .env.test.local
16
+ .env.production.local
17
+
18
+ npm-debug.log*
19
+ yarn-debug.log*
20
+ yarn-error.log*
testbed/facebookresearch__hydra/website/.yarnclean ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # test directories
2
+ __tests__
3
+ test
4
+ tests
5
+ powered-test
6
+
7
+ # asset directories
8
+ docs
9
+ doc
10
+ website
11
+ images
12
+ assets
13
+
14
+ # examples
15
+ example
16
+ examples
17
+
18
+ # code coverage directories
19
+ coverage
20
+ .nyc_output
21
+
22
+ # build scripts
23
+ Makefile
24
+ Gulpfile.js
25
+ Gruntfile.js
26
+
27
+ # configs
28
+ appveyor.yml
29
+ circle.yml
30
+ codeship-services.yml
31
+ codeship-steps.yml
32
+ wercker.yml
33
+ .tern-project
34
+ .gitattributes
35
+ .editorconfig
36
+ .*ignore
37
+ .eslintrc
38
+ .jshintrc
39
+ .flowconfig
40
+ .documentup.json
41
+ .yarn-metadata.json
42
+ .travis.yml
43
+
44
+ # misc
45
+ *.md
testbed/facebookresearch__hydra/website/README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Website
2
+
3
+ This website is built using Docusaurus 2, a modern static website generator.
4
+
5
+ ### Installation
6
+
7
+ ```
8
+ $ yarn
9
+ ```
10
+
11
+ ### Local Development
12
+
13
+ ```
14
+ $ yarn start
15
+ ```
16
+
17
+ This command starts a local development server and open up a browser window. Most changes are reflected live without having to restart the server.
18
+
19
+ ### Build
20
+
21
+ ```
22
+ $ yarn build
23
+ ```
24
+
25
+ This command generates static content into the `build` directory and can be served using any static contents hosting service.
26
+
27
+ ### Deployment
28
+
29
+ Done automatically once a website change is landed to master.
30
+
31
+
32
+ ### Adding pages
33
+
34
+ New pages, e.g., for a new plugin, should be added to `docs/`. They can be accessed on a local server via `http://localhost:3000/docs/next/page_name`.
testbed/facebookresearch__hydra/website/blog/2020-05-04-New-blog.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: New Hydra blog
3
+ author: Omry Yadan
4
+ author_title: Creator of Hydra
5
+ author_url: https://github.com/omry
6
+ author_image_url: http://graph.facebook.com/733244046/picture/?height=200&width=200
7
+ tags: [Hydra]
8
+ ---
9
+ Welcome to the Hydra blog.
10
+
11
+ Catching up on some previous content:
12
+
13
+ ##### Apr/8/2020
14
+ [FLOSS Weekly interview](https://twit.tv/shows/floss-weekly/episodes/573)
15
+
16
+ ##### Feb/3/2020
17
+ [PyTorch Medium channel blog post](http://bit.ly/2Sdq2B3)
18
+
19
+ ##### Oct/3/2019
20
+ [Facebook engineering blog release post](https://engineering.fb.com/open-source/hydra/)
testbed/facebookresearch__hydra/website/docs/advanced/command_line_overrides.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: command_line_overrides
3
+ title: Command line overrides
4
+ ---
5
+ You can manipulate your configuration via the command line. This includes:
6
+ - Manipulation of the defaults list
7
+ - Manipulation of the resulting config object
8
+
9
+ Both of those looks similar in the command line.
10
+ Command line overrides matching a Config group are manipulating the Defaults List; The rest are manipulating the resulting config object.
11
+
12
+ ```text title="Defaults List overrides"
13
+ PACKAGE : PATH[.PATH]*
14
+ PATH : [A-Za-z0-9_-]+
15
+ OPTION : .*
16
+
17
+ # Changing an existing item
18
+ GROUP[@SRC_PKG[:DEST_PKG]][=OPTION]
19
+
20
+ # Appending a new item
21
+ +GROUP@[SRC_PKG]=OPTION
22
+
23
+ # Deleting an existing item
24
+ ~GROUP[@PACKAGE][=OPTION]
25
+ ```
26
+
27
+ ```text title="Config overrides"
28
+ KEY=VALUE
29
+ KEY : .+
30
+ VALUE : .+
31
+
32
+ # Changing an existing item
33
+ KEY=VALUE
34
+
35
+ # Appending a new item
36
+ +KEY=VALUE
37
+
38
+ # Deleting an existing item
39
+ ~KEY[=VALUE]
40
+ ```
41
+
42
+ # Examples
43
+ ## Config values
44
+ - Overriding a config value : `foo.bar=value`
45
+ - Appending a config value : `+foo.bar=value`
46
+ - Removing a config value : `~foo.bar`, `~foo.bar=value`
47
+
48
+ ## Defaults list
49
+ - Overriding selected Option: `db=mysql`
50
+ - Overriding selected Option and renaming package: `db@src_pkg:dst_pkg=mysql`
51
+ - Renaming package: `db@src_pkg:dst_pkg`
52
+ - Appending to defaults: `+experiment=exp1`
53
+ - Deleting from defaults: `~db`, `~db=mysql`
54
+
55
+ When renaming a package, if the current item in the defaults list does not have a package,
56
+ use the empty string for the source package, e.g: `db@:dst_package`.
testbed/facebookresearch__hydra/website/docs/advanced/overriding_packages.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: overriding_packages
3
+ title: Overriding packages
4
+ ---
5
+
6
+ The contents of a config file can be relocated, or replicated, within the config, via package overrides.
7
+
8
+ ### Package specification
9
+
10
+ ``` text title="Definition of a package"
11
+ PACKAGE : _global_ | COMPONENT[.COMPONENT]*
12
+ COMPONENT : _group_ | _name_ | \w+
13
+
14
+ _global_ : the top level package (equivalent to the empty string).
15
+ _group_ : the config group in dot notation: foo/bar/zoo.yaml -> foo.bar
16
+ _name_ : the config file name: foo/bar/zoo.yaml -> zoo
17
+ ```
18
+
19
+ ### Overriding the package in a file via a package directive
20
+
21
+ A `@package directive` specifies a common [package](/terminology.md#package) for all nodes in the config file.
22
+ It must be placed at the top of each `config group file`.
23
+
24
+ ```text title="Package directive examples"
25
+ # @package foo.bar
26
+ # @package _global_
27
+ # @package _group_
28
+ # @package _group_._name_
29
+ # @package foo._group_._name_
30
+ ```
31
+ #### Examples
32
+ ##### A package directive with a literal
33
+ <div className="row">
34
+ <div className="col col--6">
35
+
36
+ ```yaml title="mysql.yaml" {1-2}
37
+ # @package foo.bar
38
+
39
+ db:
40
+ host: localhost
41
+ port: 3306
42
+ ```
43
+
44
+ </div>
45
+
46
+ <div className="col col--6">
47
+
48
+ ```yaml title="Interpretation" {1-2}
49
+ foo:
50
+ bar:
51
+ db:
52
+ host: localhost
53
+ port: 3306
54
+ ```
55
+
56
+ </div>
57
+ </div>
58
+
59
+
60
+ ##### A package directive with `_group_` and `_name_`
61
+
62
+ <div className="row">
63
+ <div className="col col--6">
64
+
65
+ ```yaml title="db/mysql.yaml" {1-2}
66
+ # @package _group_._name_
67
+
68
+ host: localhost
69
+ port: 3306
70
+ ```
71
+ </div><div className="col col--6">
72
+
73
+ ```yaml title="Interpretation" {1-2}
74
+ db:
75
+ mysql:
76
+ host: localhost
77
+ port: 3306
78
+ ```
79
+ </div></div>
80
+
81
+ ### Overriding the package via the defaults list
82
+ The following example adds the `mysql` config in under the packages `src` and `dst`.
83
+
84
+
85
+ <div className="row">
86
+ <div className="col col--6">
87
+
88
+ ```yaml title="config.yaml"
89
+ defaults:
90
+ - db@db.src: mysql
91
+ - db@db.dst: mysql
92
+
93
+
94
+
95
+
96
+ ```
97
+ </div><div className="col col--6">
98
+
99
+ ```yaml title="Interpretation"
100
+ db:
101
+ src:
102
+ host: localhost
103
+ port: 3306
104
+ dst:
105
+ host: localhost
106
+ port: 3306
107
+ ```
108
+ </div></div>
109
+
110
+ ### Overriding the package via the command line
111
+ Overriding the package for `db` specified in the defaults list from `db.dst` to `backup`:
112
+ ```bash
113
+ $ python my_app.py db@db.dst:backup
114
+ $ python my_app.py db@db.dst:backup=postgresql # And change the config group option
115
+ ```
116
+
117
+ Overriding the package of a config group option not in the defaults list:
118
+ ```text
119
+ python my_app.py +webserver@prod=apache
120
+ ```
121
+
122
+ For more details, see the [Command line overrides](advanced/command_line_overrides.md) page.
123
+
124
+ ### History and future of the package directive
125
+ The primary config, named in `@hydra.main()` should not have a package directive.
126
+
127
+ For config files in config groups the default depends on the version:
128
+ - In **Hydra 0.11**, there was an implicit default of `_global_`
129
+ - **Hydra 1.0** the default is `_global_`
130
+ A warning is issued for each **config group file** without a `@package` directive.
131
+ - In **Hydra 1.1** the default for **config group files** will become `_group_`
132
+
133
+ By adding an explicit `@package` to your configs files, you guarantee that they
134
+ will not break when you upgrade to Hydra 1.1.
135
+
testbed/facebookresearch__hydra/website/docs/advanced/packaging.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ id: app_packaging
3
+ title: Application packaging
4
+ sidebar_label: Application packaging
5
+ ---
6
+
7
+ You can package your Hydra application along with its configuration.
8
+ There is a working example [here](https://github.com/facebookresearch/hydra/tree/master/examples/advanced/hydra_app_example).
9
+
10
+ You can run it with:
11
+
12
+ ```yaml
13
+ $ python examples/advanced/hydra_app_example/hydra_app/main.py
14
+ dataset:
15
+ name: imagenet
16
+ path: /datasets/imagenet
17
+ ```
18
+
19
+ To install it, use:
20
+ ```text
21
+ $ pip install examples/advanced/hydra_app_example
22
+ ...
23
+ Successfully installed hydra-app-0.1
24
+ ```
25
+
26
+ Run the installed app with:
27
+ ```yaml
28
+ $ hydra_app
29
+ dataset:
30
+ name: imagenet
31
+ path: /datasets/imagenet
32
+ ```
33
+
34
+ The installed app will use the packaged configuration files.