Skip to content

Commit 2759fd4

Browse files
authored
Merge #144 - add black and isort
2 parents 8d3f9ec + e0ac266 commit 2759fd4

17 files changed

+122
-126
lines changed

Diff for: .flake8

+1-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,12 @@
11
[flake8]
22
allow-untyped-nested = true
3-
application_import_names = snekbox
43
docstring-convention = all
5-
import-order-style = pycharm
6-
inline-quotes = "
74
max-line-length = 100
85

96
exclude = __pycache__,.cache,user_base,venv,.venv,snekbox/config_pb2.py
107

118
ignore =
12-
W503,
9+
E203, W503,
1310
# Missing Docstrings
1411
D100,D104,D105,D107,
1512
# Docstring Whitespace

Diff for: .github/workflows/test.yaml

+2-10
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ jobs:
1414
runs-on: ${{ matrix.os }}
1515
strategy:
1616
matrix:
17-
os: [ubuntu-20.04, self-hosted]
17+
os: [ubuntu-20.04, ubuntu-22.04]
1818

1919
steps:
2020
- name: Download image artifact
@@ -53,17 +53,9 @@ jobs:
5353
path: .coverage.*
5454
retention-days: 1
5555

56-
# Self-hosted runner needs containers, images, networks, volumes, etc.
57-
# removed because they persist across runs and may interfere.
58-
- name: Docker cleanup
59-
if: matrix.os == 'self-hosted' && always()
60-
run: |
61-
export IMAGE_SUFFIX='-venv:${{ inputs.version }}'
62-
docker-compose down --rmi all --remove-orphans -v -t 0
63-
6456
report:
6557
name: Report coverage
66-
runs-on: ubuntu-20.04
58+
runs-on: ubuntu-latest
6759
needs: test
6860

6961
steps:

Diff for: .pre-commit-config.yaml

+17-12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
repos:
22
- repo: https://github.com/pre-commit/pre-commit-hooks
3-
rev: v3.4.0
3+
rev: v4.2.0
44
hooks:
55
- id: check-merge-conflict
66
- id: check-toml
@@ -9,26 +9,31 @@ repos:
99
- id: trailing-whitespace
1010
args: [--markdown-linebreak-ext=md]
1111
- repo: https://github.com/pre-commit/pygrep-hooks
12-
rev: v1.6.0
12+
rev: v1.9.0
1313
hooks:
1414
- id: python-check-blanket-noqa
15+
- repo: https://github.com/PyCQA/isort
16+
rev: 5.10.1
17+
hooks:
18+
- id: isort
19+
- repo: https://github.com/psf/black
20+
rev: 22.3.0
21+
hooks:
22+
- id: black
23+
language_version: "3.10"
1524
- repo: https://github.com/PyCQA/flake8
16-
rev: &flake8_version 3.8.4
25+
rev: &flake8_version 4.0.1
1726
hooks:
1827
- &flake8_hook
1928
id: flake8
2029
additional_dependencies:
21-
- flake8-annotations~=2.5.0
22-
- flake8-bugbear~=20.11
23-
- flake8-docstrings~=1.5
24-
- flake8-formatter-junit-xml~=0.0.6
25-
- flake8-import-order~=0.18.1
26-
- flake8-quotes~=3.2
30+
- flake8-annotations~=2.7
31+
- flake8-bugbear==22.4.25
32+
- flake8-docstrings~=1.4
2733
- flake8-string-format~=0.3.0
28-
- flake8-tidy-imports~=4.2
2934
- flake8-todo~=0.7
30-
- pep8-naming~=0.11.1
31-
- pydocstyle~=5.1
35+
- pep8-naming~=0.12.1
36+
- pydocstyle~=6.1,!=6.1.0
3237
- repo: https://github.com/PyCQA/flake8
3338
rev: *flake8_version
3439
hooks:

Diff for: docker-compose.yml

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ services:
66
hostname: snekbox_dev
77
privileged: true
88
image: ghcr.io/python-discord/snekbox${IMAGE_SUFFIX:--venv:dev}
9+
pull_policy: never
910
ports:
1011
- 8060:8060
1112
init: true

Diff for: pyproject.toml

+13-4
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,17 @@ exclude_lines = [
5959
branch = true
6060
data_file = "${COVERAGE_DATAFILE-.coverage}"
6161
include = ["snekbox/*"]
62-
omit = [
63-
"snekbox/api/app.py",
64-
"snekbox/config_pb2.py"
65-
]
62+
omit = ["snekbox/config_pb2.py"]
6663
relative_files = true
64+
65+
[tool.black]
66+
line-length = 100
67+
target-version = ["py310"]
68+
force-exclude = ["snekbox/config_pb2.py"]
69+
70+
[tool.isort]
71+
line_length = 100
72+
profile = "black"
73+
skip_gitignore = true
74+
src_paths = ["snekbox"]
75+
extend_skip = ["snekbox/config_pb2.py"]

Diff for: snekbox/__main__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def parse_args() -> argparse.Namespace:
2727
# Can't use double dash because that has special semantics for argparse already.
2828
split = unknown.index("---")
2929
args.nsjail_args = unknown[:split]
30-
args.py_args = unknown[split + 1:]
30+
args.py_args = unknown[split + 1 :]
3131
except ValueError:
3232
args.nsjail_args = unknown
3333

Diff for: snekbox/api/resources/eval.py

+4-16
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,10 @@ class EvalResource:
2323
REQ_SCHEMA = {
2424
"type": "object",
2525
"properties": {
26-
"input": {
27-
"type": "string"
28-
},
29-
"args": {
30-
"type": "array",
31-
"items": {
32-
"type": "string"
33-
}
34-
}
26+
"input": {"type": "string"},
27+
"args": {"type": "array", "items": {"type": "string"}},
3528
},
36-
"required": [
37-
"input"
38-
]
29+
"required": ["input"],
3930
}
4031

4132
def __init__(self):
@@ -91,7 +82,4 @@ def on_post(self, req: falcon.Request, resp: falcon.Response) -> None:
9182
log.exception("An exception occurred while trying to process the request")
9283
raise falcon.HTTPInternalServerError
9384

94-
resp.media = {
95-
"stdout": result.stdout,
96-
"returncode": result.returncode
97-
}
85+
resp.media = {"stdout": result.stdout, "returncode": result.returncode}

Diff for: snekbox/nsjail.py

+15-13
Original file line numberDiff line numberDiff line change
@@ -133,11 +133,7 @@ def _consume_stdout(nsjail: subprocess.Popen) -> str:
133133
return "".join(output)
134134

135135
def python3(
136-
self,
137-
code: str,
138-
*,
139-
nsjail_args: Iterable[str] = (),
140-
py_args: Iterable[str] = ("-c",)
136+
self, code: str, *, nsjail_args: Iterable[str] = (), py_args: Iterable[str] = ("-c",)
141137
) -> CompletedProcess:
142138
"""
143139
Execute Python 3 code in an isolated environment and return the completed process.
@@ -153,17 +149,26 @@ def python3(
153149

154150
if self.ignore_swap_limits:
155151
nsjail_args = (
156-
"--cgroup_mem_memsw_max", "0", "--cgroup_mem_swap_max", "-1", *nsjail_args
152+
"--cgroup_mem_memsw_max",
153+
"0",
154+
"--cgroup_mem_swap_max",
155+
"-1",
156+
*nsjail_args,
157157
)
158158

159159
with NamedTemporaryFile() as nsj_log:
160160
args = (
161161
self.nsjail_binary,
162-
"--config", NSJAIL_CFG,
163-
"--log", nsj_log.name,
162+
"--config",
163+
NSJAIL_CFG,
164+
"--log",
165+
nsj_log.name,
164166
*nsjail_args,
165167
"--",
166-
self.config.exec_bin.path, *self.config.exec_bin.arg, *py_args, code
168+
self.config.exec_bin.path,
169+
*self.config.exec_bin.arg,
170+
*py_args,
171+
code,
167172
)
168173

169174
msg = "Executing code..."
@@ -173,10 +178,7 @@ def python3(
173178

174179
try:
175180
nsjail = subprocess.Popen(
176-
args,
177-
stdout=subprocess.PIPE,
178-
stderr=subprocess.STDOUT,
179-
text=True
181+
args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
180182
)
181183
except ValueError:
182184
return CompletedProcess(args, None, "ValueError: embedded null byte", None)

Diff for: snekbox/utils/cgroup.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def get_version(config: NsJailConfig) -> int:
1919
config.cgroup_mem_mount,
2020
config.cgroup_pids_mount,
2121
config.cgroup_net_cls_mount,
22-
config.cgroup_cpu_mount
22+
config.cgroup_cpu_mount,
2323
)
2424
v1_exists = any(Path(mount).exists() for mount in cgroup_mounts)
2525

Diff for: snekbox/utils/gunicorn.py

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from gunicorn.config import Config
55

66
from snekbox import DEBUG
7+
78
from .logging import FORMAT
89

910
__all__ = ("GunicornLogger",)

Diff for: snekbox/utils/logging.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
from falcon.util.deprecation import DeprecatedWarning
77

8-
98
__all__ = ("FORMAT", "init_logger", "init_sentry")
109

1110
FORMAT = "%(asctime)s | %(process)5s | %(name)30s | %(levelname)8s | %(message)s"
@@ -38,5 +37,5 @@ def init_sentry(version: str) -> None:
3837
dsn=os.environ.get("SNEKBOX_SENTRY_DSN", ""),
3938
integrations=[FalconIntegration()],
4039
send_default_pii=True,
41-
release=f"snekbox@{version}"
40+
release=f"snekbox@{version}",
4241
)

Diff for: tests/api/__init__.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ def setUp(self):
1414
self.patcher = mock.patch("snekbox.api.resources.eval.NsJail", autospec=True)
1515
self.mock_nsjail = self.patcher.start()
1616
self.mock_nsjail.return_value.python3.return_value = CompletedProcess(
17-
args=[],
18-
returncode=0,
19-
stdout="output",
20-
stderr="error"
17+
args=[], returncode=0, stdout="output", stderr="error"
2118
)
2219
self.addCleanup(self.patcher.stop)
2320

Diff for: tests/api/test_eval.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,13 @@ def test_post_invalid_schema_400(self):
2020

2121
expected = {
2222
"title": "Request data failed validation",
23-
"description": "'input' is a required property"
23+
"description": "'input' is a required property",
2424
}
2525

2626
self.assertEqual(expected, result.json)
2727

2828
def test_post_invalid_data_400(self):
29-
bodies = (
30-
{"input": 400}, {"input": "", "args": [400]}
31-
)
29+
bodies = ({"input": 400}, {"input": "", "args": [400]})
3230

3331
for body in bodies:
3432
with self.subTest():
@@ -38,7 +36,7 @@ def test_post_invalid_data_400(self):
3836

3937
expected = {
4038
"title": "Request data failed validation",
41-
"description": "400 is not of type 'string'"
39+
"description": "400 is not of type 'string'",
4240
}
4341

4442
self.assertEqual(expected, result.json)
@@ -52,7 +50,7 @@ def test_post_invalid_content_type_415(self):
5250

5351
expected = {
5452
"title": "415 Unsupported Media Type",
55-
"description": "application/xml is an unsupported media type."
53+
"description": "application/xml is an unsupported media type.",
5654
}
5755

5856
self.assertEqual(expected, result.json)

Diff for: tests/gunicorn_utils.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,14 @@ def load_config(self):
2929

3030
def _proc_target(config_path: str, event: multiprocessing.Event, **kwargs) -> None:
3131
"""Run a Gunicorn app with the given config and set `event` when Gunicorn is ready."""
32+
3233
def when_ready(_):
3334
event.set()
3435

3536
app = _StandaloneApplication(config_path, when_ready=when_ready, **kwargs)
3637

3738
import logging
39+
3840
logging.disable(logging.INFO)
3941

4042
app.run()
@@ -62,7 +64,7 @@ def run_gunicorn(config_path: str = "config/gunicorn.conf.py", **kwargs) -> Iter
6264
concurrent.futures.wait(
6365
[executor.submit(proc.join), executor.submit(event.wait)],
6466
timeout=60,
65-
return_when=concurrent.futures.FIRST_COMPLETED
67+
return_when=concurrent.futures.FIRST_COMPLETED,
6668
)
6769
# Can't use the context manager cause wait=False needs to be set.
6870
executor.shutdown(wait=False, cancel_futures=True)

Diff for: tests/test_integration.py

-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ def run_code_in_snekbox(code: str) -> tuple[str, int]:
2121

2222

2323
class IntegrationTests(unittest.TestCase):
24-
2524
def test_memory_limit_separate_per_process(self):
2625
"""
2726
Each NsJail process should have its own memory limit.

Diff for: tests/test_main.py

+6-12
Original file line numberDiff line numberDiff line change
@@ -12,30 +12,24 @@
1212
class ArgParseTests(unittest.TestCase):
1313
def test_parse_args(self):
1414
subtests = (
15-
(
16-
["", "code"],
17-
Namespace(code="code", nsjail_args=[], py_args=["-c"])
18-
),
15+
(["", "code"], Namespace(code="code", nsjail_args=[], py_args=["-c"])),
1916
(
2017
["", "code", "--time_limit", "0"],
21-
Namespace(code="code", nsjail_args=["--time_limit", "0"], py_args=["-c"])
18+
Namespace(code="code", nsjail_args=["--time_limit", "0"], py_args=["-c"]),
2219
),
2320
(
2421
["", "code", "---", "-m", "timeit"],
25-
Namespace(code="code", nsjail_args=[], py_args=["-m", "timeit"])
22+
Namespace(code="code", nsjail_args=[], py_args=["-m", "timeit"]),
2623
),
2724
(
2825
["", "code", "--time_limit", "0", "---", "-m", "timeit"],
29-
Namespace(code="code", nsjail_args=["--time_limit", "0"], py_args=["-m", "timeit"])
26+
Namespace(code="code", nsjail_args=["--time_limit", "0"], py_args=["-m", "timeit"]),
3027
),
3128
(
3229
["", "code", "--time_limit", "0", "---"],
33-
Namespace(code="code", nsjail_args=["--time_limit", "0"], py_args=[])
30+
Namespace(code="code", nsjail_args=["--time_limit", "0"], py_args=[]),
3431
),
35-
(
36-
["", "code", "---"],
37-
Namespace(code="code", nsjail_args=[], py_args=[])
38-
)
32+
(["", "code", "---"], Namespace(code="code", nsjail_args=[], py_args=[])),
3933
)
4034

4135
for argv, expected in subtests:

0 commit comments

Comments
 (0)