|
7 | 7 | import plotly.graph_objs as go
|
8 | 8 | import plotly.io as pio
|
9 | 9 | from plotly.io._utils import plotly_cdn_url
|
| 10 | +from plotly.offline.offline import get_plotlyjs |
| 11 | +from plotly.io._html import _generate_sri_hash |
10 | 12 |
|
11 | 13 |
|
12 | 14 | if sys.version_info >= (3, 3):
|
@@ -46,3 +48,37 @@ def test_html_deterministic(fig1):
|
46 | 48 | assert pio.to_html(fig1, include_plotlyjs="cdn", div_id=div_id) == pio.to_html(
|
47 | 49 | fig1, include_plotlyjs="cdn", div_id=div_id
|
48 | 50 | )
|
| 51 | + |
| 52 | + |
| 53 | +def test_cdn_includes_integrity_attribute(fig1): |
| 54 | + """Test that the CDN script tag includes an integrity attribute with SHA256 hash""" |
| 55 | + html_output = pio.to_html(fig1, include_plotlyjs="cdn") |
| 56 | + |
| 57 | + # Check that the script tag includes integrity attribute |
| 58 | + assert 'integrity="sha256-' in html_output |
| 59 | + assert 'crossorigin="anonymous"' in html_output |
| 60 | + |
| 61 | + # Verify it's in the correct script tag |
| 62 | + import re |
| 63 | + cdn_pattern = re.compile(r'<script[^>]*src="' + re.escape(plotly_cdn_url()) + r'"[^>]*integrity="sha256-[A-Za-z0-9+/=]+"[^>]*>') |
| 64 | + match = cdn_pattern.search(html_output) |
| 65 | + assert match is not None, "CDN script tag with integrity attribute not found" |
| 66 | + |
| 67 | + |
| 68 | +def test_cdn_integrity_hash_matches_bundled_content(fig1): |
| 69 | + """Test that the SRI hash in CDN script tag matches the bundled plotly.js content""" |
| 70 | + html_output = pio.to_html(fig1, include_plotlyjs="cdn") |
| 71 | + |
| 72 | + # Extract the integrity hash from the HTML output |
| 73 | + import re |
| 74 | + integrity_pattern = re.compile(r'integrity="(sha256-[A-Za-z0-9+/=]+)"') |
| 75 | + match = integrity_pattern.search(html_output) |
| 76 | + assert match is not None, "Integrity attribute not found" |
| 77 | + extracted_hash = match.group(1) |
| 78 | + |
| 79 | + # Generate expected hash from bundled content |
| 80 | + plotlyjs_content = get_plotlyjs() |
| 81 | + expected_hash = _generate_sri_hash(plotlyjs_content) |
| 82 | + |
| 83 | + # Verify they match |
| 84 | + assert extracted_hash == expected_hash, f"Hash mismatch: expected {expected_hash}, got {extracted_hash}" |
0 commit comments