-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathtest_axe.py
More file actions
211 lines (156 loc) · 6.03 KB
/
test_axe.py
File metadata and controls
211 lines (156 loc) · 6.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import json
from os import getcwd
from os import getenv
from os import path
import pytest
from selenium import webdriver
from axe_selenium_python import Axe
_DEFAULT_TEST_FILE = path.join(path.dirname(__file__), "test_page.html")
@pytest.fixture
def firefox_driver():
driver = webdriver.Firefox()
yield driver
driver.close()
@pytest.fixture
def chrome_driver():
opts = webdriver.ChromeOptions()
opts.headless = True
opts.add_argument("--no-sandbox")
opts.add_argument("--headless")
driver_path = getenv("CHROMEDRIVER_PATH")
driver = (
webdriver.Chrome(options=opts, executable_path=driver_path)
if driver_path
else webdriver.Chrome(options=opts)
)
yield driver
driver.close()
@pytest.mark.nondestructive
def test_run_axe_sample_page_firefox(firefox_driver):
"""Run axe against sample page and verify JSON output is as expected."""
data = _perform_axe_run(firefox_driver)
assert len(data["inapplicable"]) == 75
assert len(data["incomplete"]) == 0
assert len(data["passes"]) == 6
assert len(data["violations"]) == 9
@pytest.mark.nondestructive
def test_run_axe_sample_page_chrome(chrome_driver):
"""Run axe against sample page and verify JSON output is as expected."""
data = _perform_axe_run(chrome_driver)
assert len(data["inapplicable"]) == 75
assert len(data["incomplete"]) == 0
assert len(data["passes"]) == 6
assert len(data["violations"]) == 9
def _perform_axe_run(driver):
driver.get("file://" + _DEFAULT_TEST_FILE)
axe = Axe(driver)
axe.inject()
data = axe.run()
return data
def test_write_results_to_file(tmpdir, mocker):
axe = Axe(mocker.MagicMock())
data = {"testKey": "testValue"}
filename = path.join(str(tmpdir), "results.json")
axe.write_results(data, filename)
with open(filename) as f:
actual_file_contents = json.loads(f.read())
assert data == actual_file_contents
def test_write_results_without_filepath(mocker):
axe = Axe(mocker.MagicMock())
data = {"testKey": "testValue"}
cwd = getcwd()
filename = path.join(cwd, "results.json")
axe.write_results(data, filename)
with open(filename) as f:
actual_file_contents = json.loads(f.read())
assert data == actual_file_contents
assert path.dirname(filename) == cwd
def test_inject_reads_and_executes_script(tmp_path, mocker):
mock_selenium = mocker.MagicMock()
script_file = tmp_path / "axe.min.js"
script_file.write_text("console.log('axe injected');")
axe = Axe(mock_selenium, str(script_file))
axe.inject()
mock_selenium.execute_script.assert_called_once_with("console.log('axe injected');")
def test_inject_missing_script_raises_error(mocker):
mock_selenium = mocker.MagicMock()
axe = Axe(mock_selenium, "nonexistent.js")
with pytest.raises(FileNotFoundError):
axe.inject()
def test_run_with_context_and_options(mocker):
mock_selenium = mocker.MagicMock()
mock_selenium.execute_async_script.return_value = {"passes": []}
axe = Axe(mock_selenium)
context = {"include": [["#main"]]}
options = {"runOnly": {"type": "tag", "values": ["wcag2a"]}}
result = axe.run(context, options)
assert result == {"passes": []}
assert mock_selenium.execute_async_script.called
command = mock_selenium.execute_async_script.call_args[0][0]
assert "axe.run" in command
assert "wcag2a" in command
@pytest.mark.parametrize("context,options", [
({"include": [["#main"]]}, None),
(None, {"runOnly": {"type": "tag", "values": ["wcag2aa"]}}),
])
def test_run_with_single_arg_cases(mocker, context, options):
mock_selenium = mocker.MagicMock()
mock_selenium.execute_async_script.return_value = {"result": "ok"}
axe = Axe(mock_selenium)
axe.run(context, options)
called_script = mock_selenium.execute_async_script.call_args[0][0]
assert "axe.run" in called_script
def test_run_with_invalid_script_raises(mocker):
mock_selenium = mocker.MagicMock()
mock_selenium.execute_async_script.side_effect = Exception("JS failed")
axe = Axe(mock_selenium)
with pytest.raises(Exception, match="JS failed"):
axe.run()
def test_report_generates_expected_string(mocker):
axe = Axe(mocker.MagicMock())
violations = [{
"id": "color-contrast",
"description": "Elements must have sufficient color contrast",
"helpUrl": "https://example.com",
"impact": "serious",
"tags": ["wcag2aa", "contrast"],
"nodes": [{
"target": ["#header"],
"all": [{"message": "Check color contrast"}],
"any": [],
"none": []
}]
}]
report = axe.report(violations)
assert "Found 1 accessibility violations" in report
assert "color-contrast" in report
assert "#header" in report
assert "serious" in report
def test_report_with_empty_list_returns_no_violation_text(mocker):
axe = Axe(mocker.MagicMock())
report = axe.report([])
assert "Found 0 accessibility violations" in report
def test_write_results_default_name(tmp_path, mocker, monkeypatch):
axe = Axe(mocker.MagicMock())
monkeypatch.chdir(tmp_path)
data = {"k": "v"}
axe.write_results(data)
default_file = tmp_path / "results.json"
assert default_file.exists()
def test_write_results_with_invalid_path(mocker):
axe = Axe(mocker.MagicMock())
data = {"key": "value"}
# Attempt writing to directory that does not exist
bad_path = "/invalid_dir/results.json"
with pytest.raises(OSError):
axe.write_results(data, bad_path)
def test_write_results_with_unserializable_data(mocker, tmp_path):
axe = Axe(mocker.MagicMock())
filename = tmp_path / "results.json"
# Functions are not JSON-serializable
data = {"func": lambda x: x}
with pytest.raises(TypeError):
axe.write_results(data, str(filename))