diff --git a/tests/wpt/metadata-layout-2020/css/css-backgrounds/border-image-repeat-space-011.html.ini b/tests/wpt/metadata-layout-2020/css/css-backgrounds/border-image-repeat-space-011.html.ini new file mode 100644 index 00000000000..9042ba61fa2 --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-backgrounds/border-image-repeat-space-011.html.ini @@ -0,0 +1,2 @@ +[border-image-repeat-space-011.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-backgrounds/color-mix-currentcolor-border-repaint-parent.html.ini b/tests/wpt/metadata-layout-2020/css/css-backgrounds/color-mix-currentcolor-border-repaint-parent.html.ini new file mode 100644 index 00000000000..c9d7cc70385 --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-backgrounds/color-mix-currentcolor-border-repaint-parent.html.ini @@ -0,0 +1,2 @@ +[color-mix-currentcolor-border-repaint-parent.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-backgrounds/color-mix-currentcolor-border-repaint.html.ini b/tests/wpt/metadata-layout-2020/css/css-backgrounds/color-mix-currentcolor-border-repaint.html.ini new file mode 100644 index 00000000000..1173d4884b2 --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-backgrounds/color-mix-currentcolor-border-repaint.html.ini @@ -0,0 +1,2 @@ +[color-mix-currentcolor-border-repaint.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-color/parsing/color-computed-lab.html.ini b/tests/wpt/metadata-layout-2020/css/css-color/parsing/color-computed-lab.html.ini index a495d8a21c8..a83c6abc5d4 100644 --- a/tests/wpt/metadata-layout-2020/css/css-color/parsing/color-computed-lab.html.ini +++ b/tests/wpt/metadata-layout-2020/css/css-color/parsing/color-computed-lab.html.ini @@ -397,3 +397,15 @@ [Property color value 'oklch(calc(0 / 0) 0 0)'] expected: FAIL + + [Property color value 'lab(20% -50% 90%/0.5)'] + expected: FAIL + + [Property color value 'oklab(20% 70% -80%/0.5)'] + expected: FAIL + + [Property color value 'lch(20% 80% 10/0.5)'] + expected: FAIL + + [Property color value 'oklch(20% 60% 10/0.5)'] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-color/parsing/color-valid-lab.html.ini b/tests/wpt/metadata-layout-2020/css/css-color/parsing/color-valid-lab.html.ini index 31148265ab3..9d60cf5d19c 100644 --- a/tests/wpt/metadata-layout-2020/css/css-color/parsing/color-valid-lab.html.ini +++ b/tests/wpt/metadata-layout-2020/css/css-color/parsing/color-valid-lab.html.ini @@ -418,3 +418,15 @@ [e.style['color'\] = "oklch(calc(0 / 0) 0 0)" should set the property value] expected: FAIL + + [e.style['color'\] = "lab(20% -50% 90%/0.5)" should set the property value] + expected: FAIL + + [e.style['color'\] = "oklab(20% 70% -80%/0.5)" should set the property value] + expected: FAIL + + [e.style['color'\] = "lch(20% 80% 10/0.5)" should set the property value] + expected: FAIL + + [e.style['color'\] = "oklch(20% 60% 10/0.5)" should set the property value] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-001.html.ini b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-001.html.ini new file mode 100644 index 00000000000..475ea8859ca --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-001.html.ini @@ -0,0 +1,2 @@ +[quotes-first-letter-001.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-002.html.ini b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-002.html.ini new file mode 100644 index 00000000000..ac6448ef250 --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-002.html.ini @@ -0,0 +1,2 @@ +[quotes-first-letter-002.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-003.html.ini b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-003.html.ini new file mode 100644 index 00000000000..0aa7222bd06 --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-003.html.ini @@ -0,0 +1,2 @@ +[quotes-first-letter-003.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-004.html.ini b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-004.html.ini new file mode 100644 index 00000000000..25ab55b56c7 --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-004.html.ini @@ -0,0 +1,2 @@ +[quotes-first-letter-004.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-005.html.ini b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-005.html.ini new file mode 100644 index 00000000000..38d34096ee2 --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-content/quotes-first-letter-005.html.ini @@ -0,0 +1,2 @@ +[quotes-first-letter-005.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-002.html.ini b/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-002.html.ini new file mode 100644 index 00000000000..59f0ee2071e --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-002.html.ini @@ -0,0 +1,2 @@ +[flexbox-safe-overflow-position-002.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-003.html.ini b/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-003.html.ini new file mode 100644 index 00000000000..fe53a3a6fef --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-003.html.ini @@ -0,0 +1,2 @@ +[flexbox-safe-overflow-position-003.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-005.html.ini b/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-005.html.ini new file mode 100644 index 00000000000..43358703cf5 --- /dev/null +++ b/tests/wpt/metadata-layout-2020/css/css-flexbox/flexbox-safe-overflow-position-005.html.ini @@ -0,0 +1,2 @@ +[flexbox-safe-overflow-position-005.html] + expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-001.html.ini b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-001.html.ini index f73951f8025..1d8a6be9487 100644 --- a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-001.html.ini +++ b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-001.html.ini @@ -53,63 +53,9 @@ [background-position length(px) / events] expected: FAIL - [text-indent length(pt) / values] - expected: FAIL - - [text-indent length(pc) / values] - expected: FAIL - - [text-indent length(px) / values] - expected: FAIL - - [text-indent length(em) / values] - expected: FAIL - - [text-indent length(ex) / values] - expected: FAIL - - [text-indent length(mm) / values] - expected: FAIL - - [text-indent length(cm) / values] - expected: FAIL - - [text-indent length(in) / values] - expected: FAIL - - [text-indent percentage(%) / values] - expected: FAIL - [text-shadow shadow(shadow) / values] expected: FAIL - [text-indent length(pt) / events] - expected: FAIL - - [text-indent length(pc) / events] - expected: FAIL - - [text-indent length(px) / events] - expected: FAIL - - [text-indent length(em) / events] - expected: FAIL - - [text-indent length(ex) / events] - expected: FAIL - - [text-indent length(mm) / events] - expected: FAIL - - [text-indent length(cm) / events] - expected: FAIL - - [text-indent length(in) / events] - expected: FAIL - - [text-indent percentage(%) / events] - expected: FAIL - [text-shadow shadow(shadow) / events] expected: FAIL @@ -268,126 +214,3 @@ [vertical-align percentage(%) / events] expected: FAIL - - [background-color color(rgba) / values] - expected: FAIL - - [border-top-width length(pt) / values] - expected: FAIL - - [border-top-width length(pc) / values] - expected: FAIL - - [border-top-width length(px) / values] - expected: FAIL - - [border-top-width length(em) / values] - expected: FAIL - - [border-top-width length(ex) / values] - expected: FAIL - - [border-top-width length(mm) / values] - expected: FAIL - - [border-top-width length(cm) / values] - expected: FAIL - - [border-top-width length(in) / values] - expected: FAIL - - [border-right-width length(pt) / values] - expected: FAIL - - [border-right-width length(pc) / values] - expected: FAIL - - [border-right-width length(px) / values] - expected: FAIL - - [border-right-width length(em) / values] - expected: FAIL - - [border-right-width length(ex) / values] - expected: FAIL - - [border-right-width length(mm) / values] - expected: FAIL - - [border-right-width length(cm) / values] - expected: FAIL - - [border-right-width length(in) / values] - expected: FAIL - - [border-bottom-width length(pt) / values] - expected: FAIL - - [border-bottom-width length(pc) / values] - expected: FAIL - - [border-bottom-width length(px) / values] - expected: FAIL - - [border-bottom-width length(em) / values] - expected: FAIL - - [border-bottom-width length(ex) / values] - expected: FAIL - - [border-bottom-width length(mm) / values] - expected: FAIL - - [border-bottom-width length(cm) / values] - expected: FAIL - - [border-bottom-width length(in) / values] - expected: FAIL - - [border-left-width length(pt) / values] - expected: FAIL - - [border-left-width length(pc) / values] - expected: FAIL - - [border-left-width length(px) / values] - expected: FAIL - - [border-left-width length(em) / values] - expected: FAIL - - [border-left-width length(ex) / values] - expected: FAIL - - [border-left-width length(mm) / values] - expected: FAIL - - [border-left-width length(cm) / values] - expected: FAIL - - [border-left-width length(in) / values] - expected: FAIL - - [border-top-color color(rgba) / values] - expected: FAIL - - [border-right-color color(rgba) / values] - expected: FAIL - - [border-bottom-color color(rgba) / values] - expected: FAIL - - [border-left-color color(rgba) / values] - expected: FAIL - - [padding-bottom length(pt) / values] - expected: FAIL - - [padding-bottom length(pc) / values] - expected: FAIL - - [padding-bottom length(px) / values] - expected: FAIL - - [padding-bottom length(em) / values] - expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-implicit-001.html.ini b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-implicit-001.html.ini index fd2fc3fe626..66e5b35bd3a 100644 --- a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-implicit-001.html.ini +++ b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-implicit-001.html.ini @@ -5,9 +5,6 @@ [background-position length-em(em) / values] expected: FAIL - [text-indent length-em(em) / values] - expected: FAIL - [outline-offset length-em(em) / values] expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-001.html.ini b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-001.html.ini index 52b2a279b94..1625a9d90d0 100644 --- a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-001.html.ini +++ b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-001.html.ini @@ -56,63 +56,9 @@ [background-position length(px) / events] expected: FAIL - [text-indent length(pt) / events] - expected: FAIL - - [text-indent length(pc) / events] - expected: FAIL - - [text-indent length(px) / events] - expected: FAIL - - [text-indent length(em) / events] - expected: FAIL - - [text-indent length(ex) / events] - expected: FAIL - - [text-indent length(mm) / events] - expected: FAIL - - [text-indent length(cm) / events] - expected: FAIL - - [text-indent length(in) / events] - expected: FAIL - - [text-indent percentage(%) / events] - expected: FAIL - [text-shadow shadow(shadow) / events] expected: FAIL - [text-indent length(pt) / values] - expected: FAIL - - [text-indent length(pc) / values] - expected: FAIL - - [text-indent length(px) / values] - expected: FAIL - - [text-indent length(em) / values] - expected: FAIL - - [text-indent length(ex) / values] - expected: FAIL - - [text-indent length(mm) / values] - expected: FAIL - - [text-indent length(cm) / values] - expected: FAIL - - [text-indent length(in) / values] - expected: FAIL - - [text-indent percentage(%) / values] - expected: FAIL - [text-shadow shadow(shadow) / values] expected: FAIL @@ -272,156 +218,6 @@ [vertical-align percentage(%) / events] expected: FAIL - [padding-bottom length(ex) / events] - expected: FAIL - - [padding-bottom length(mm) / events] - expected: FAIL - - [padding-bottom length(cm) / events] - expected: FAIL - - [padding-bottom length(in) / events] - expected: FAIL - - [padding-left length(pt) / events] - expected: FAIL - - [padding-left length(pc) / events] - expected: FAIL - - [padding-left length(px) / events] - expected: FAIL - - [padding-left length(em) / events] - expected: FAIL - - [padding-left length(ex) / events] - expected: FAIL - - [padding-left length(mm) / events] - expected: FAIL - - [padding-left length(cm) / events] - expected: FAIL - - [padding-left length(in) / events] - expected: FAIL - - [padding-right length(pt) / events] - expected: FAIL - - [padding-right length(pc) / events] - expected: FAIL - - [padding-right length(px) / events] - expected: FAIL - - [padding-right length(em) / events] - expected: FAIL - - [padding-right length(ex) / events] - expected: FAIL - - [padding-right length(mm) / events] - expected: FAIL - - [padding-right length(cm) / events] - expected: FAIL - - [padding-right length(in) / events] - expected: FAIL - - [padding-top length(pt) / events] - expected: FAIL - - [padding-top length(pc) / events] - expected: FAIL - - [padding-top length(px) / events] - expected: FAIL - - [padding-top length(em) / events] - expected: FAIL - - [padding-top length(ex) / events] - expected: FAIL - - [padding-top length(mm) / events] - expected: FAIL - - [padding-top length(cm) / events] - expected: FAIL - - [padding-top length(in) / events] - expected: FAIL - - [margin-bottom length(pt) / events] - expected: FAIL - - [margin-bottom length(pc) / events] - expected: FAIL - - [margin-bottom length(px) / events] - expected: FAIL - - [margin-bottom length(em) / events] - expected: FAIL - - [margin-bottom length(ex) / events] - expected: FAIL - - [margin-bottom length(mm) / events] - expected: FAIL - - [margin-bottom length(cm) / events] - expected: FAIL - - [margin-bottom length(in) / events] - expected: FAIL - - [margin-left length(pt) / events] - expected: FAIL - - [margin-left length(pc) / events] - expected: FAIL - - [margin-left length(px) / events] - expected: FAIL - - [margin-left length(em) / events] - expected: FAIL - - [margin-left length(ex) / events] - expected: FAIL - - [margin-left length(mm) / events] - expected: FAIL - - [margin-left length(cm) / events] - expected: FAIL - - [margin-left length(in) / events] - expected: FAIL - - [margin-right length(pt) / events] - expected: FAIL - - [margin-right length(pc) / events] - expected: FAIL - - [margin-right length(px) / events] - expected: FAIL - - [margin-right length(em) / events] - expected: FAIL - - [margin-right length(ex) / events] - expected: FAIL - - [margin-right length(mm) / events] - expected: FAIL - [background-color color(rgba) / events] expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-002.html.ini b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-002.html.ini index 86e0ec5506e..ee265267026 100644 --- a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-002.html.ini +++ b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-002.html.ini @@ -53,63 +53,9 @@ [background-position length(px) / events] expected: FAIL - [text-indent length(pt) / values] - expected: FAIL - - [text-indent length(pc) / values] - expected: FAIL - - [text-indent length(px) / values] - expected: FAIL - - [text-indent length(em) / values] - expected: FAIL - - [text-indent length(ex) / values] - expected: FAIL - - [text-indent length(mm) / values] - expected: FAIL - - [text-indent length(cm) / values] - expected: FAIL - - [text-indent length(in) / values] - expected: FAIL - - [text-indent percentage(%) / values] - expected: FAIL - [text-shadow shadow(shadow) / values] expected: FAIL - [text-indent length(pt) / events] - expected: FAIL - - [text-indent length(pc) / events] - expected: FAIL - - [text-indent length(px) / events] - expected: FAIL - - [text-indent length(em) / events] - expected: FAIL - - [text-indent length(ex) / events] - expected: FAIL - - [text-indent length(mm) / events] - expected: FAIL - - [text-indent length(cm) / events] - expected: FAIL - - [text-indent length(in) / events] - expected: FAIL - - [text-indent percentage(%) / events] - expected: FAIL - [text-shadow shadow(shadow) / events] expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-003.html.ini b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-003.html.ini index 9627921e283..6a2778b1be9 100644 --- a/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-003.html.ini +++ b/tests/wpt/metadata-layout-2020/css/css-transitions/properties-value-inherit-003.html.ini @@ -5,12 +5,6 @@ [background-position length-em(em) / values] expected: FAIL - [text-indent length-em(em) / values] - expected: FAIL - - [text-indent length-em(em) / events] - expected: FAIL - [outline-offset length-em(em) / values] expected: FAIL diff --git a/tests/wpt/metadata-layout-2020/css/cssom-view/MediaQueryList-addListener-removeListener.html.ini b/tests/wpt/metadata-layout-2020/css/cssom-view/MediaQueryList-addListener-removeListener.html.ini index 153b135b9a9..314dca9c1f5 100644 --- a/tests/wpt/metadata-layout-2020/css/cssom-view/MediaQueryList-addListener-removeListener.html.ini +++ b/tests/wpt/metadata-layout-2020/css/cssom-view/MediaQueryList-addListener-removeListener.html.ini @@ -1,9 +1,3 @@ [MediaQueryList-addListener-removeListener.html] [listeners are called when + + diff --git a/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-002.html b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-002.html new file mode 100644 index 00000000000..6164411b64c --- /dev/null +++ b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-002.html @@ -0,0 +1,28 @@ + + + + + + + +

Test passes if there is a filled green square and no red.

+ + + diff --git a/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-003.html b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-003.html new file mode 100644 index 00000000000..4bf7183c15b --- /dev/null +++ b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-003.html @@ -0,0 +1,28 @@ + + + + + + + +

Test passes if there is a filled green square and no red.

+ + + diff --git a/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-004.html b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-004.html new file mode 100644 index 00000000000..c01497e1eaf --- /dev/null +++ b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-004.html @@ -0,0 +1,28 @@ + + + + + + + +

Test passes if there is a filled green square and no red.

+ + + diff --git a/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-005.html b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-005.html new file mode 100644 index 00000000000..927086a723a --- /dev/null +++ b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-005.html @@ -0,0 +1,28 @@ + + + + + + + +

Test passes if there is a filled green square and no red.

+ + + diff --git a/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-006.html b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-006.html new file mode 100644 index 00000000000..5ed7d4f3025 --- /dev/null +++ b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-006.html @@ -0,0 +1,28 @@ + + + + + + + +

Test passes if there is a filled green square and no red.

+ + + diff --git a/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-007.html b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-007.html new file mode 100644 index 00000000000..0b403b2aafc --- /dev/null +++ b/tests/wpt/web-platform-tests/css/css-writing-modes/orthogonal-root-resize-icb-007.html @@ -0,0 +1,28 @@ + + + + + + + +

Test passes if there is a filled green square and no red.

+ + + diff --git a/tests/wpt/web-platform-tests/css/cssom/cssimportrule.html b/tests/wpt/web-platform-tests/css/cssom/cssimportrule.html index 89269f1c24c..2703b9a69b5 100644 --- a/tests/wpt/web-platform-tests/css/cssom/cssimportrule.html +++ b/tests/wpt/web-platform-tests/css/cssom/cssimportrule.html @@ -15,6 +15,7 @@ @import url("support/a-green.css"); @import url("support/a-green.css") screen; @import url("support/a-green.css") all; + @import url("support/a-green") supports((display: flex) or (display: block)); @page { background-color: red; } @@ -22,13 +23,14 @@
diff --git a/tests/wpt/web-platform-tests/css/tools/META.yml b/tests/wpt/web-platform-tests/css/tools/META.yml deleted file mode 100644 index e08d85a38fe..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/META.yml +++ /dev/null @@ -1,4 +0,0 @@ -suggested_reviewers: - - plinss - - kojiishi - - jgraham diff --git a/tests/wpt/web-platform-tests/css/tools/README.md b/tests/wpt/web-platform-tests/css/tools/README.md deleted file mode 100644 index 8310d89d7ad..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/README.md +++ /dev/null @@ -1,15 +0,0 @@ -This directory contains the CSS build system. - -It is recommended that it is run with `build.sh`, as -this ensures all dependencies are installed. Note that it is not -required to build the testsuites to run tests; you can just run tests -as with any other web-platform-tests tests (see ../../docs/). - -The build system is formed of build.py in this directory, the -w3ctestlib package in w3ctestlib/, and the apiclient package in -apiclient/apiclient/. Note that apiclient exists as a separate -upstream project at https://hg.csswg.org/dev/apiclient/, and that -ideally any changes here should make it upstream. - -Warning: The CSS build system is not tested in CI at all, so don't make any -changes without ensuring that it still works locally. diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/.gitignore b/tests/wpt/web-platform-tests/css/tools/apiclient/.gitignore deleted file mode 100644 index d43a721ddd2..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.xcodeproj -*.DS_Store -local/* -*.log -*.pyc -*.orig -uritemplate-test/* -.hg/* diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/.hgignore b/tests/wpt/web-platform-tests/css/tools/apiclient/.hgignore deleted file mode 100644 index 07d6d3d104d..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/.hgignore +++ /dev/null @@ -1,10 +0,0 @@ -syntax: glob -*.xcodeproj -*.DS_Store -local/* -*.log -*.pyc -*.orig -uritemplate-test/* -.git/* -._* diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/README.md b/tests/wpt/web-platform-tests/css/tools/apiclient/README.md deleted file mode 100644 index 6e332b852ad..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/README.md +++ /dev/null @@ -1,174 +0,0 @@ -apiclient -========== - -Client class for calling http+json APIs in Python. Requires Python 2.7. - -Supports json home pages per: -http://tools.ietf.org/html/draft-nottingham-json-home-03 - - -Installation ------------- -Standard python package installation: - - python setup.py install - - -Usage ------ -Import the apiclient package and instantiate a client. - - import apiclient - - api = apiclient.APIClient('http://api.example.com') - -Call APIs: - - result = api.call('foo', var1=arg1, var2=arg2) - print result.data - - -APIClient class ---------------- -**class apiclient.APIClient(baseURI, version = None, username = None, password = None)** - -The APIClient constructor takes the base URI for the api, an optional request version identifier, username and password. - -**APIClient.baseURI** - -The base URI set in the constructor, read-only. - -**APIClient.resourceNames** - -A list of available API resource names. - -**APIClient.resource(name)** - -Get a named APIResource. - -**APIClient.setVersion(name, version)** - -Set the request version identifier for a specific resource. If not set, the default version identifier will be used. - -**APIClient.setAccept(name, mimeType)** - -Set the requested Content-Type for a specific resource. If not set, 'application/json' will be used. - -**APIClient.get(name, [kwargs])** - -Perform an HTTP GET on the named resource. Any named arguments supplied may be used in computing the actual URI to call. Returns an APIResponse or None if the resource name is not known. - -**APIClient.postForm(name, payload = None, [kwargs])** - -Perform an HTTP POST on the named resource. The payload, if present, may be either a dict or sequence of two-tuples and will be form encoded. Any named arguments supplied may be used in computing the actual URI to call. Returns an APIResponse or None if the resource name is not known. - -**APIClient.put(name, payload = None, payloadType = None, [kwargs])** - -Perform an HTTP PUT on the named resource. The payload, if present, will be sent to the server using the payloadType Content-Type. The payload must be pre-encoded and will not be processed by the APIClient. Any named arguments supplied may be used in computing the actual URI to call. Returns an APIResponse or None if the resource name is not known. - -**APIClient.patch(name, patch = None, [kwargs])** - -Perform an HTTP PATCH on the named resource. The patch, if present, will be encoded in JSON and sent to the server as a 'application/json-patch'. Any named arguments supplied may be used in computing the actual URI to call. Returns an APIResponse or None if the resource name is not known. - -**APIClient.delete(name, [kwargs])** - -Perform an HTTP DELETE on the named resource. Any named arguments supplied may be used in computing the actual URI to call. Returns an APIResponse or None if the resource name is not known. - - -APIResponse class ------------------ -**APIResponse.status** - -The HTTP status code of the response. - -**APIResponse.headers** - -A dict of HTTP response headers. - -**APIResponse.contentType** - -The Content-Type of the response. - -**APIResponse.encoding** - -The encoding of the response. - -**APIResponse.data** - -The body of the response. If the contentType is json, the data will be decoded into native objects. - - -APIResource class ------------------ -Describes the properties of an available API resource. - -**APIResource.template** - -The URITemplate used when calling the resource. - -**APIResource.variables** - -A dict of variables that may be passed to the resource. Keys are variable names, values are the URI identifier of the variable, if available (see http://tools.ietf.org/html/draft-nottingham-json-home-03#section-3.1 ). - -**APIResource.hints** - -An APIHints object describing any hints for the resource (see http://tools.ietf.org/html/draft-nottingham-json-home-03#section-4 ). - - -APIHints class --------------- -**APIHints.httpMethods** - -A list of HTTP methods the resource may be called with. - -**APIHints.formats** - -A dict of formats available for each HTTP method. Keys are HTTP methods, values are a list of Content-Types available. - -**APIHints.ranges** - -Not yet implemented. - -**APIHints.preferences** - -Not yet implemented. - -**APIHints.preconditions** - -Not yet implemented. - -**APIHints.auth** - -Not yet implemented. - -**APIHints.docs** - -A URI for documentation for the resource. - -**APIHints.status** - -The status of the resource. - - -URITemplate class ------------------ -Parses and expands URITemplates per RFC 6750 (plus a few extensions). - -**class uritemplate.URITemplate(template)** - -Construct a URITemplate. Raises exceptions if malformed. - -**URITemplate.variables** - -A set of variables available in the template. - -**URITemplate.expand([kwargs])** - -Return the expanded template substituting any passed keyword arguments. - - -Notes ------ -Resource names may be absolute URIs or relative to the base URI of the API. - - diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/__init__.py b/tests/wpt/web-platform-tests/css/tools/apiclient/__init__.py deleted file mode 100644 index b49652b48de..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -# Copyright © 2013 Hewlett-Packard Development Company, L.P. -# -# This work is distributed under the W3C® Software License [1] -# in the hope that it will be useful, but WITHOUT ANY -# WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# -# [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 -# - -# define package for direct inclusion when not installed - -__all__ = ['apiclient'] \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/__init__.py b/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/__init__.py deleted file mode 100644 index 9be8333de28..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -# Copyright © 2013 Hewlett-Packard Development Company, L.P. -# -# This work is distributed under the W3C® Software License [1] -# in the hope that it will be useful, but WITHOUT ANY -# WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# -# [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 -# - -__all__ = ['apiclient', 'uritemplate'] - -import apiclient diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/apiclient.py b/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/apiclient.py deleted file mode 100644 index 99f30e62710..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/apiclient.py +++ /dev/null @@ -1,283 +0,0 @@ -# coding=utf-8 -# -# Copyright © 2013 Hewlett-Packard Development Company, L.P. -# -# This work is distributed under the W3C® Software License [1] -# in the hope that it will be useful, but WITHOUT ANY -# WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# -# [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 -# - -# Process URI templates per http://tools.ietf.org/html/rfc6570 - - -import urllib2 -import urlparse -import json -import base64 -import contextlib -import collections -import UserString - -import uritemplate - -class MimeType(UserString.MutableString): - def __init__(self, mimeType): - UserString.MutableString.__init__(self, mimeType) - self._type = None - self._subtype = None - self._structure = None - - slashIndex = mimeType.find('/') - if (-1 < slashIndex): - self._type = mimeType[:slashIndex] - mimeType = mimeType[slashIndex + 1:] - plusIndex = mimeType.find('+') - if (-1 < plusIndex): - self._subtype = mimeType[:plusIndex] - self._structure = mimeType[plusIndex + 1:] - else: - self._structure = mimeType - else: - self._type = mimeType - - def _update(self): - if (self._structure): - if (self._subtype): - self.data = self._type + '/' + self._subtype + '+' + self._structure - else: - self.data = self._type + '/' + self._structure - else: - self.data = self._type - - def set(self, type, structure, subtype = None): - self._type = type - self._subtype = subtype - self._structure = structure - self._update() - - @property - def type(self): - return self._type - - @type.setter - def type(self, value): - self._type = value - self._update() - - @property - def subtype(self): - return self._subtype - - @subtype.setter - def subtype(self, value): - self._subtype = value - self._update() - - @property - def structure(self): - return self._structure - - @structure.setter - def structure(self, value): - self._structure = value - self._update() - - -class APIResponse(object): - def __init__(self, response): - self.status = response.getcode() if (response) else 0 - self.headers = response.info() if (response) else {} - self.data = response.read() if (200 == self.status) else None - - if (self.data and - (('json' == self.contentType.structure) or ('json-home' == self.contentType.structure))): - try: - self.data = json.loads(self.data, object_pairs_hook = collections.OrderedDict) - except: - pass - - @property - def contentType(self): - contentType = self.headers.get('content-type') if (self.headers) else None - return MimeType(contentType.split(';')[0]) if (contentType and (';' in contentType)) else MimeType(contentType) - - @property - def encoding(self): - contentType = self.headers.get('content-type') if (self.headers) else None - if (contentType and (';' in contentType)): - encoding = contentType.split(';', 1)[1] - if ('=' in encoding): - return encoding.split('=', 1)[1].strip() - return 'utf-8' - - -class APIHints(object): - def __init__(self, data): - self.httpMethods = [method.upper() for method in data['allow'] if method] if ('allow' in data) else ['GET'] - self.formats = {} - formats = [MimeType(format) for format in data['formats']] if ('formats' in data) else [] - if (formats): - if ('GET' in self.httpMethods): - self.formats['GET'] = formats - if ('PUT' in self.httpMethods): - self.formats['PUT'] = formats - - if (('PATCH' in self.httpMethods) and ('accept-patch' in data)): - self.formats['PATCH'] = [MimeType(format) for format in data['accept-patch']] - if (('POST' in self.httpMethods) and ('accept-post' in data)): - self.formats['POST'] = [MimeType(format) for format in data['accept-post']] - - # TODO: ranges from 'accept-ranges'; preferece tokens from 'accept-prefer'; - # preconditions from 'precondition-req'; auth from 'auth-req' - self.ranges = None - self.preferences = None - self.preconditions = None - self.auth = None - - self.docs = data.get('docs') - self.status = data.get('status') - - -class APIResource(object): - def __init__(self, baseURI, uri, variables = None, hints = None): - try: - self.template = uritemplate.URITemplate(urlparse.urljoin(baseURI, uri)) - if (variables): - self.variables = {variable: urlparse.urljoin(baseURI, variables[variable]) for variable in variables} - else: - self.variables = {variable: '' for variable in self.template.variables} - self.hints = hints - except Exception as e: - self.template = uritemplate.URITemplate('') - self.variables = {} - self.hints = None - - -class APIClient(object): - def __init__(self, baseURI, version = None, username = None, password = None): - self._baseURI = baseURI - self.defaultVersion = version - self.defaultAccept = 'application/json' - self.username = username - self.password = password - self._resources = {} - self._versions = {} - self._accepts = {} - - self._loadHome() - - - @property - def baseURI(self): - return self._baseURI - - def _loadHome(self): - home = self._callURI('GET', self.baseURI, 'application/home+json, application/json-home, application/json') - if (home): - if ('application/json' == home.contentType): - for name in home.data: - apiKey = urlparse.urljoin(self.baseURI, name) - self._resources[apiKey] = APIResource(self.baseURI, home.data[name]) - elif (('application/home+json' == home.contentType) or - ('application/json-home' == home.contentType)): - resources = home.data.get('resources') - if (resources): - for name in resources: - apiKey = urlparse.urljoin(self.baseURI, name) - data = resources[name] - uri = data['href'] if ('href' in data) else data.get('href-template') - variables = data.get('href-vars') - hints = APIHints(data['hints']) if ('hints' in data) else None - self._resources[apiKey] = APIResource(self.baseURI, uri, variables, hints) - - - def relativeURI(self, uri): - if (uri.startswith(self.baseURI)): - relative = uri[len(self.baseURI):] - if (relative.startswith('/') and not self.baseURI.endswith('/')): - relative = relative[1:] - return relative - return uri - - @property - def resourceNames(self): - return [self.relativeURI(apiKey) for apiKey in self._resources] - - def resource(self, name): - return self._resources.get(urlparse.urljoin(self.baseURI, name)) - - def addResource(self, name, uri): - resource = APIResource(self.baseURI, uri) - apiKey = urlparse.urljoin(self.baseURI, name) - self._resources[apiKey] = resource - - def _accept(self, resource): - version = None - if (api and (api in self._versions)): - version = self._versions[api] - if (not version): - version = self.defaultVersion - return ('application/' + version + '+json, application/json') if (version) else 'application/json' - - def _callURI(self, method, uri, accept, payload = None, payloadType = None): - try: - request = urllib2.Request(uri, data = payload, headers = { 'Accept' : accept }) - if (self.username and self.password): - request.add_header('Authorization', b'Basic ' + base64.b64encode(self.username + b':' + self.password)) - if (payload and payloadType): - request.add_header('Content-Type', payloadType) - request.get_method = lambda: method - - with contextlib.closing(urllib2.urlopen(request)) as response: - return APIResponse(response) - except Exception as e: - pass - return None - - def _call(self, method, name, arguments, payload = None, payloadType = None): - apiKey = urlparse.urljoin(self.baseURI, name) - resource = self._resources.get(apiKey) - - if (resource): - uri = resource.template.expand(**arguments) - if (uri): - version = self._versions.get(apiKey) if (apiKey in self._versions) else self.defaultVersion - accept = MimeType(self._accepts(apiKey) if (apiKey in self._accepts) else self.defaultAccept) - if (version): - accept.subtype = version - return self._callURI(method, uri, accept, payload, payloadType) - return None - - def setVersion(self, name, version): - apiKey = urlparse.urljoin(self.baseURI, name) - self._versions[apiKey] = version - - def setAccept(self, name, mimeType): - apiKey = urlparse.urljoin(self.baseURI, name) - self._accepts[apiKey] = mimeType - - def get(self, name, **kwargs): - return self._call('GET', name, kwargs) - - def post(self, name, payload = None, payloadType = None, **kwargs): - return self._call('POST', name, kwargs, payload, payloadType) - - def postForm(self, name, payload = None, **kwargs): - return self._call('POST', name, kwargs, urllib.urlencode(payload), 'application/x-www-form-urlencoded') - - def postJSON(self, name, payload = None, **kwargs): - return self._call('POST', name, kwargs, json.dumps(payload), 'application/json') - - def put(self, name, payload = None, payloadType = None, **kwargs): - return self._call('PUT', name, kwargs, payload, payloadType) - - def patch(self, name, patch = None, **kwargs): - return self._call('PATCH', name, kwargs, json.dumps(patch), 'application/json-patch') - - def delete(self, name, **kwargs): - return self._call('DELETE', name, kwargs) - - diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/uritemplate.py b/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/uritemplate.py deleted file mode 100644 index 737cbe78184..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/apiclient/uritemplate.py +++ /dev/null @@ -1,379 +0,0 @@ -# coding=utf-8 -# -# Copyright © 2013 Hewlett-Packard Development Company, L.P. -# -# This work is distributed under the W3C® Software License [1] -# in the hope that it will be useful, but WITHOUT ANY -# WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# -# [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 -# - -# Process URI templates per http://tools.ietf.org/html/rfc6570 - -import re - - -class UnsupportedExpression(Exception): - def __init__(self, expression): - self.expression = expression - - def __unicode__(self): - return u'Unsopported expression: ' + self.expression - -class BadExpression(Exception): - def __init__(self, expression): - self.expression = expression - - def __unicode__(self): - return u'Bad expression: ' + self.expression - -class BadVariable(Exception): - def __init__(self, variable): - self.variable = variable - - def __unicode__(self): - return u'Bad variable: ' + self.variable - -class BadExpansion(Exception): - def __init__(self, variable): - self.variable = variable - - def __unicode__(self): - return u'Bad expansion: ' + self.variable - -class URITemplate(object): - alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' - digit = '0123456789' - hexdigit = '0123456789ABCDEFabcdef' - genDelims = ':/?#[]@' - subDelims = "!$&'()*+,;=" - varstart = alpha + digit + '_' - varchar = varstart + '.' - unreserved = alpha + digit + '-._~' - reserved = genDelims + subDelims - - def __init__(self, template): - self.template = template - - self.parts = [] - parts = re.split(r'(\{[^\}]*\})', self.template) - for part in parts: - if (part): - if (('{' == part[0]) and ('}' == part[-1])): - expression = part[1:-1] - if (re.match('^([a-zA-Z0-9_]|%[0-9a-fA-F][0-9a-fA-F]).*$', expression)): - self.parts.append(SimpleExpansion(expression)) - elif ('+' == part[1]): - self.parts.append(ReservedExpansion(expression)) - elif ('#' == part[1]): - self.parts.append(FragmentExpansion(expression)) - elif ('.' == part[1]): - self.parts.append(LabelExpansion(expression)) - elif ('/' == part[1]): - self.parts.append(PathExpansion(expression)) - elif (';' == part[1]): - self.parts.append(PathStyleExpansion(expression)) - elif ('?' == part[1]): - self.parts.append(FormStyleQueryExpansion(expression)) - elif ('&' == part[1]): - self.parts.append(FormStyleQueryContinuation(expression)) - elif (part[1] in '=,!@|'): - raise UnsupportedExpression(part) - else: - raise BadExpression(part) - else: - if (('{' not in part) and ('}' not in part)): - self.parts.append(Literal(part)) - else: - raise BadExpression(part) - - @property - def variables(self): - vars = set() - for part in self.parts: - vars.update(part.variables) - return vars - - def expand(self, **kwargs): - try: - expanded = [part.expand(kwargs) for part in self.parts] - except (BadExpansion): - return None - return ''.join([expandedPart for expandedPart in expanded if (expandedPart is not None)]) - - def __str__(self): - return self.template.encode('ascii', 'replace') - - def __unicode__(self): - return unicode(self.template) - - -class Variable(object): - def __init__(self, name): - self.name = '' - self.maxLength = None - self.explode = False - self.array = False - - if (name[0:1] not in URITemplate.varstart): - raise BadVariable(name) - - if (':' in name): - name, maxLength = name.split(':', 1) - if ((0 < len(maxLength)) and (len(maxLength) < 4)): - for digit in maxLength: - if (digit not in URITemplate.digit): - raise BadVariable(name + ':' + maxLength) - self.maxLength = int(maxLength) - if (not self.maxLength): - raise BadVariable(name + ':' + maxLength) - else: - raise BadVariable(name + ':' + maxLength) - elif ('*' == name[-1]): - name = name[:-1] - self.explode = True - elif ('[]' == name[-2:]): - name = name[:-2] - self.array = True - self.explode = True - - index = 0 - while (index < len(name)): - codepoint = name[index] - if (('%' == codepoint) and - ((index + 2) < len(name)) and - (name[index + 1] in URITemplate.hexdigit) and - (name[index + 2] in URITemplate.hexdigit)): - self.name += name[index:index + 3] - index += 2 - elif (codepoint in URITemplate.varchar): - self.name += codepoint - else: - raise BadVariable(name + ((':' + self.maxLength) if (self.maxLength) else '') + ('[]' if (self.array) else ('*' if (self.explode) else ''))) - index += 1 - - -class Expression(object): - def __init__(self): - pass - - @property - def variables(self): - return [] - - def _encode(self, value, legal, pctEncoded): - output = '' - index = 0 - while (index < len(value)): - codepoint = value[index] - if (codepoint in legal): - output += codepoint - elif (pctEncoded and ('%' == codepoint) and - ((index + 2) < len(value)) and - (value[index + 1] in URITemplate.hexdigit) and - (value[index + 2] in URITemplate.hexdigit)): - output += value[index:index + 3] - index += 2 - else: - utf8 = codepoint.encode('utf8') - for byte in utf8: - output += '%' + URITemplate.hexdigit[ord(byte) / 16] + URITemplate.hexdigit[ord(byte) % 16] - index += 1 - return output - - def _uriEncodeValue(self, value): - return self._encode(value, URITemplate.unreserved, False) - - def _uriEncodeName(self, name): - return self._encode(unicode(name), URITemplate.unreserved + URITemplate.reserved, True) if (name) else '' - - def _join(self, prefix, joiner, value): - if (prefix): - return prefix + joiner + value - return value - - def _encodeStr(self, variable, name, value, prefix, joiner, first): - if (variable.maxLength): - if (not first): - raise BadExpansion(variable) - return self._join(prefix, joiner, self._uriEncodeValue(value[:variable.maxLength])) - return self._join(prefix, joiner, self._uriEncodeValue(value)) - - def _encodeDictItem(self, variable, name, key, item, delim, prefix, joiner, first): - joiner = '=' if (variable.explode) else ',' - if (variable.array): - prefix = (prefix + '[' + self._uriEncodeName(key) + ']') if (prefix and not first) else self._uriEncodeName(key) - else: - prefix = self._join(prefix, '.', self._uriEncodeName(key)) - return self._encodeVar(variable, key, item, delim, prefix, joiner, False) - - def _encodeListItem(self, variable, name, index, item, delim, prefix, joiner, first): - if (variable.array): - prefix = prefix + '[' + unicode(index) + ']' if (prefix) else '' - return self._encodeVar(variable, None, item, delim, prefix, joiner, False) - return self._encodeVar(variable, name, item, delim, prefix, '.', False) - - def _encodeVar(self, variable, name, value, delim = ',', prefix = '', joiner = '=', first = True): - if (isinstance(value, basestring)): - return self._encodeStr(variable, name, value, prefix, joiner, first) - elif (hasattr(value, 'keys') and hasattr(value, '__getitem__')): # dict-like - if (len(value)): - encodedItems = [self._encodeDictItem(variable, name, key, value[key], delim, prefix, joiner, first) for key in value.keys()] - return delim.join([item for item in encodedItems if (item is not None)]) - return None - elif (hasattr(value, '__getitem__')): # list-like - if (len(value)): - encodedItems = [self._encodeListItem(variable, name, index, item, delim, prefix, joiner, first) for index, item in enumerate(value)] - return delim.join([item for item in encodedItems if (item is not None)]) - return None - else: - return self._encodeStr(variable, name, unicode(value).lower(), prefix, joiner, first) - - def expand(self, values): - return None - - -class Literal(Expression): - def __init__(self, value): - Expression.__init__(self) - self.value = value - - def expand(self, values): - return self._encode(self.value, (URITemplate.unreserved + URITemplate.reserved), True) - - -class Expansion(Expression): - operator = '' - varJoiner = ',' - - def __init__(self, variables): - Expression.__init__(self) - self.vars = [Variable(var) for var in variables.split(',')] - - @property - def variables(self): - return [var.name for var in self.vars] - - def _expandVar(self, variable, value): - return self._encodeVar(variable, self._uriEncodeName(variable.name), value) - - def expand(self, values): - expandedVars = [] - for var in self.vars: - if ((var.name in values) and (values[var.name] is not None)): - expandedVar = self._expandVar(var, values[var.name]) - if (expandedVar is not None): - expandedVars.append(expandedVar) - if (len(expandedVars)): - expanded = self.varJoiner.join(expandedVars) - if (expanded is not None): - return self.operator + expanded - return None - - -class SimpleExpansion(Expansion): - def __init__(self, variables): - Expansion.__init__(self, variables) - - -class ReservedExpansion(Expansion): - def __init__(self, variables): - Expansion.__init__(self, variables[1:]) - - def _uriEncodeValue(self, value): - return self._encode(value, (URITemplate.unreserved + URITemplate.reserved), True) - - -class FragmentExpansion(ReservedExpansion): - operator = '#' - - def __init__(self, variables): - ReservedExpansion.__init__(self, variables) - - -class LabelExpansion(Expansion): - operator = '.' - varJoiner = '.' - - def __init__(self, variables): - Expansion.__init__(self, variables[1:]) - - def _expandVar(self, variable, value): - return self._encodeVar(variable, self._uriEncodeName(variable.name), value, delim = ('.' if variable.explode else ',')) - - -class PathExpansion(Expansion): - operator = '/' - varJoiner = '/' - - def __init__(self, variables): - Expansion.__init__(self, variables[1:]) - - def _expandVar(self, variable, value): - return self._encodeVar(variable, self._uriEncodeName(variable.name), value, delim = ('/' if variable.explode else ',')) - - -class PathStyleExpansion(Expansion): - operator = ';' - varJoiner = ';' - - def __init__(self, variables): - Expansion.__init__(self, variables[1:]) - - def _encodeStr(self, variable, name, value, prefix, joiner, first): - if (variable.array): - if (name): - prefix = prefix + '[' + name + ']' if (prefix) else name - elif (variable.explode): - prefix = self._join(prefix, '.', name) - return Expansion._encodeStr(self, variable, name, value, prefix, joiner, first) - - def _encodeDictItem(self, variable, name, key, item, delim, prefix, joiner, first): - if (variable.array): - if (name): - prefix = prefix + '[' + name + ']' if (prefix) else name - prefix = (prefix + '[' + self._uriEncodeName(key) + ']') if (prefix and not first) else self._uriEncodeName(key) - elif (variable.explode): - prefix = self._join(prefix, '.', name) if (not first) else '' - else: - prefix = self._join(prefix, '.', self._uriEncodeName(key)) - joiner = ',' - return self._encodeVar(variable, self._uriEncodeName(key) if (not variable.array) else '', item, delim, prefix, joiner, False) - - def _encodeListItem(self, variable, name, index, item, delim, prefix, joiner, first): - if (variable.array): - if (name): - prefix = prefix + '[' + name + ']' if (prefix) else name - return self._encodeVar(variable, unicode(index), item, delim, prefix, joiner, False) - return self._encodeVar(variable, name, item, delim, prefix, '=' if (variable.explode) else '.', False) - - def _expandVar(self, variable, value): - if (variable.explode): - return self._encodeVar(variable, self._uriEncodeName(variable.name), value, delim = ';') - value = self._encodeVar(variable, self._uriEncodeName(variable.name), value, delim = ',') - return (self._uriEncodeName(variable.name) + '=' + value) if (value) else variable.name - - -class FormStyleQueryExpansion(PathStyleExpansion): - operator = '?' - varJoiner = '&' - - def __init__(self, variables): - PathStyleExpansion.__init__(self, variables) - - def _expandVar(self, variable, value): - if (variable.explode): - return self._encodeVar(variable, self._uriEncodeName(variable.name), value, delim = '&') - value = self._encodeVar(variable, self._uriEncodeName(variable.name), value, delim = ',') - return (self._uriEncodeName(variable.name) + '=' + value) if (value is not None) else None - - -class FormStyleQueryContinuation(FormStyleQueryExpansion): - operator = '&' - - def __init__(self, variables): - FormStyleQueryExpansion.__init__(self, variables) - - diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/setup.py b/tests/wpt/web-platform-tests/css/tools/apiclient/setup.py deleted file mode 100644 index e3b09376387..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/setup.py +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env python - -from distutils.core import setup - -setup(name='apiclient', - version='0.10', - description='Client for JSPN APIs', - author='Peter Linss', - author_email='peter.linss@hp.com', - url='http://github.com/plinss/apiclient/', - packages = ['apiclient'] - ) diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/test.py b/tests/wpt/web-platform-tests/css/tools/apiclient/test.py deleted file mode 100755 index e485367f840..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/test.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python -# coding=utf-8 -# -# Copyright © 2013 Hewlett-Packard Development Company, L.P. -# -# This work is distributed under the W3C® Software License [1] -# in the hope that it will be useful, but WITHOUT ANY -# WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# -# [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 -# - -from __future__ import print_function -import sys -import os -import glob -import json -import exceptions -import collections - -from apiclient import uritemplate -from apiclient import apiclient - - -def runTests(testFileSearch): - for testFilePath in glob.glob(testFileSearch): - print('Running tests from: ' + testFilePath) - with open(testFilePath) as testFile: - testData = json.load(testFile, object_pairs_hook = collections.OrderedDict) - for testSetName in testData: - print(testSetName + ':') - testSet = testData[testSetName] - vars = testSet['variables'] - for test in testSet['testcases']: - expectedResult = test[1] - try: - template = uritemplate.URITemplate(test[0]) - except Exception as e: - if (expectedResult): - print('* FAIL: "' + test[0] + '" got: None, expected "' + expectedResult + '"') - else: - print(' PASS: "' + test[0] + '" == None') - continue - - result = template.expand(**vars) - if (isinstance(expectedResult, basestring)): - if (expectedResult != result): - print('* FAIL: "' + test[0] + '" got: "' + unicode(result) + '", expected "' + expectedResult + '"') - continue - elif (isinstance(expectedResult, list)): - for possibleResult in expectedResult: - if (possibleResult == result): - break - else: - print('* FAIL: "' + test[0] + '" got: "' + unicode(result) + '", expected:') - print(" or\n".join([' "' + possibleResult + '"' for possibleResult in expectedResult])) - continue - elif (not expectedResult): - if (result): - print('* FAIL "' + test[0] + '" got: "' + unicode(result) + '", expected None') - continue - else: - print('** Unknown expected result type: ' + repr(expectedResult)) - print(' PASS: "' + test[0] + '" == "' + result + '"') - -def debugHook(type, value, tb): - if hasattr(sys, 'ps1') or not sys.stderr.isatty(): - # we are in interactive mode or we don't have a tty-like - # device, so we call the default hook - sys.__excepthook__(type, value, tb) - else: - import traceback, pdb - # we are NOT in interactive mode, print the exception... - traceback.print_exception(type, value, tb) - print() - # ...then start the debugger in post-mortem mode. - pdb.pm() - - -if __name__ == "__main__": # called from the command line - sys.excepthook = debugHook - -# runTests(os.path.join('test', '*.json')) - -# runTests(os.path.join('uritemplate-test', 'spec-examples.json')) -# runTests(os.path.join('uritemplate-test', '*.json')) -### more tests @ https://github.com/uri-templates/uritemplate-test - - - github = apiclient.APIClient('https://api.github.com/', version = 'vnd.github.beta') - print(github.get('user_url', user = 'plinss').data) - -# shepherd = apiclient.APIClient('https://api.csswg.org/shepherd/', version = 'vnd.csswg.shepherd.v1') - shepherd = apiclient.APIClient('https://test.linss.com/shepherd/api', version = 'vnd.csswg.shepherd.v1') - print(shepherd.resourceNames) - specs = shepherd.resource('specifications') - print(specs.variables) -# print specs.hints.docs - print(shepherd.get('specifications', spec = 'compositing-1', anchors = False).data) - - suites = shepherd.resource('test_suites') - print(suites.variables) - print(shepherd.get('test_suites', spec = 'css-shapes-1').data) - - diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/test/corners.json b/tests/wpt/web-platform-tests/css/tools/apiclient/test/corners.json deleted file mode 100644 index fd0a5a80f88..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/test/corners.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "Explode Non-composite" : - { - "level": 4, - "variables": { - "token": "12345" - }, - "testcases" : [ - ["{token}", "12345"], - ["{token*}", "12345"], - ["{.token}", ".12345"], - ["{.token*}", ".12345"], - ["{/token}", "/12345"], - ["{/token*}", "/12345"], - ["{?token}", "?token=12345"], - ["{?token*}", "?token=12345"] - ] - }, - "Non-string Values" : - { - "level": 4, - "variables": { - "positive": true, - "negative": false, - "zero" : 0, - "number" : 42.24, - "list" : ["one", 2, true, false, 0], - "dict" : { "one": "1", "two": 2, "positive": true, "negative": false, "zero": 0 } - }, - "testcases" : [ - ["{positive}", "true"], - ["{positive*}", "true"], - ["{negative}", "false"], - ["{negative*}", "false"], - ["{zero}", "0"], - ["{zero*}", "0"], - ["{number}", "42.24"], - ["{number*}", "42.24"], - ["{.positive}", ".true"], - ["{.positive*}", ".true"], - ["{.negative}", ".false"], - ["{.negative*}", ".false"], - ["{.zero}", ".0"], - ["{.zero*}", ".0"], - ["{.number}", ".42.24"], - ["{.number*}", ".42.24"], - ["{/positive}", "/true"], - ["{/positive*}", "/true"], - ["{/negative}", "/false"], - ["{/negative*}", "/false"], - ["{/zero}", "/0"], - ["{/zero*}", "/0"], - ["{/number}", "/42.24"], - ["{/number*}", "/42.24"], - ["{?positive}", "?positive=true"], - ["{?positive*}", "?positive=true"], - ["{?negative}", "?negative=false"], - ["{?negative*}", "?negative=false"], - ["{?zero}", "?zero=0"], - ["{?zero*}", "?zero=0"], - ["{?number}", "?number=42.24"], - ["{?number*}", "?number=42.24"], - ["{list}", "one,2,true,false,0"], - ["{list*}", "one,2,true,false,0"], - ["{.list}", ".one,2,true,false,0"], - ["{.list*}", ".one.2.true.false.0"], - ["{/list}", "/one,2,true,false,0"], - ["{/list*}", "/one/2/true/false/0"], - ["{?list}", "?list=one,2,true,false,0"], - ["{?list*}", "?list=one&list=2&list=true&list=false&list=0"], - ["{dict}", "one,1,two,2,positive,true,negative,false,zero,0"], - ["{dict*}", "one=1,two=2,positive=true,negative=false,zero=0"], - ["{.dict}", ".one,1,two,2,positive,true,negative,false,zero,0"], - ["{.dict*}", ".one=1.two=2.positive=true.negative=false.zero=0"], - ["{/dict}", "/one,1,two,2,positive,true,negative,false,zero,0"], - ["{/dict*}", "/one=1/two=2/positive=true/negative=false/zero=0"], - ["{?dict}", "?dict=one,1,two,2,positive,true,negative,false,zero,0"], - ["{?dict*}", "?one=1&two=2&positive=true&negative=false&zero=0"] - ] - } -} diff --git a/tests/wpt/web-platform-tests/css/tools/apiclient/test/extensions.json b/tests/wpt/web-platform-tests/css/tools/apiclient/test/extensions.json deleted file mode 100644 index 0c493620bd6..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/apiclient/test/extensions.json +++ /dev/null @@ -1,210 +0,0 @@ -{ - "Nested Structures" : - { - "level": 5, - "variables": { - "list" : ["one", "two", "three", "four"], - "dict" : {"semi": ";", "dot": ".", "comma": ","}, - "lists" : [["one", "two"], ["three"], "four"], - "dicts" : {"one": {"semi": ";", "dot": "."}, "two": {"comma": ","}}, - "mixed" : {"list": ["one", ["two", "three"]], "dict": {"one": {"semi": ";", "dot": "."}, "two": {"comma": ","}}}, - "dlist" : [{"semi": ";", "dot": "."}, {"comma": ","}] - }, - "testcases" : [ - ["{list}", "one,two,three,four"], - ["{list*}", "one,two,three,four"], - ["{?list}", "?list=one,two,three,four"], - ["{?list*}", "?list=one&list=two&list=three&list=four"], - ["{lists}", "one,two,three,four"], - ["{lists*}", "one,two,three,four"], - ["{?lists}", "?lists=one,two,three,four"], - ["{?lists*}", "?lists=one&lists=two&lists=three&lists=four"], - ["{dict}", [ - "comma,%2C,dot,.,semi,%3B", - "comma,%2C,semi,%3B,dot,.", - "dot,.,comma,%2C,semi,%3B", - "dot,.,semi,%3B,comma,%2C", - "semi,%3B,comma,%2C,dot,.", - "semi,%3B,dot,.,comma,%2C" - ]], - ["{dict*}", [ - "comma=%2C,dot=.,semi=%3B", - "comma=%2C,semi=%3B,dot=.", - "dot=.,comma=%2C,semi=%3B", - "dot=.,semi=%3B,comma=%2C", - "semi=%3B,comma=%2C,dot=.", - "semi=%3B,dot=.,comma=%2C" - ]], - ["{?dict}", [ - "?dict=comma,%2C,dot,.,semi,%3B", - "?dict=comma,%2C,semi,%3B,dot,.", - "?dict=dot,.,comma,%2C,semi,%3B", - "?dict=dot,.,semi,%3B,comma,%2C", - "?dict=semi,%3B,comma,%2C,dot,.", - "?dict=semi,%3B,dot,.,comma,%2C" - ]], - ["{?dict*}", [ - "?comma=%2C&dot=.&semi=%3B", - "?comma=%2C&semi=%3B&dot=.", - "?dot=.&comma=%2C&semi=%3B", - "?dot=.&semi=%3B&comma=%2C", - "?semi=%3B&comma=%2C&dot=.", - "?semi=%3B&dot=.&comma=%2C" - ]], - ["{dicts}", [ - "two.comma,%2C,one.dot,.,one.semi,%3B", - "two.comma,%2C,one.semi,%3B,one.dot,.", - "one.dot,.,two.comma,%2C,one.semi,%3B", - "one.dot,.,one.semi,%3B,two.comma,%2C", - "one.semi,%3B,two.comma,%2C,one.dot,.", - "one.semi,%3B,one.dot,.,two.comma,%2C" - ]], - ["{dicts*}", [ - "two.comma=%2C,one.dot=.,one.semi=%3B", - "two.comma=%2C,one.semi=%3B,one.dot=.", - "one.dot=.,two.comma=%2C,one.semi=%3B", - "one.dot=.,one.semi=%3B,two.comma=%2C", - "one.semi=%3B,two.comma=%2C,one.dot=.", - "one.semi=%3B,one.dot=.,two.comma=%2C" - ]], - ["{?dicts}", [ - "?dicts=two.comma,%2C,one.dot,.,one.semi,%3B", - "?dicts=two.comma,%2C,one.semi,%3B,one.dot,.", - "?dicts=one.dot,.,two.comma,%2C,one.semi,%3B", - "?dicts=one.dot,.,one.semi,%3B,two.comma,%2C", - "?dicts=one.semi,%3B,two.comma,%2C,one.dot,.", - "?dicts=one.semi,%3B,one.dot,.,two.comma,%2C" - ]], - ["{?dicts*}", [ - "?two.comma=%2C&one.dot=.&one.semi=%3B", - "?two.comma=%2C&one.semi=%3B&one.dot=.", - "?one.dot=.&two.comma=%2C&one.semi=%3B", - "?one.dot=.&one.semi=%3B&two.comma=%2C", - "?one.semi=%3B&two.comma=%2C&one.dot=.", - "?one.semi=%3B&one.dot=.&two.comma=%2C" - ]], - ["{mixed}", [ - "list.one,list.two,list.three,dict.two.comma,%2C,dict.one.dot,.,dict.one.semi,%3B", - "list.one,list.two,list.three,dict.two.comma,%2C,dict.one.semi,%3B,dict.one.dot,.", - "list.one,list.two,list.three,dict.one.dot,.,dict.two.comma,%2C,dict.one.semi,%3B", - "list.one,list.two,list.three,dict.one.dot,.,dict.one.semi,%3B,dict.two.comma,%2C", - "list.one,list.two,list.three,dict.one.semi,%3B,dict.two.comma,%2C,dict.one.dot,.", - "list.one,list.two,list.three,dict.one.semi,%3B,dict.one.dot,.,dict.two.comma,%2C" - ]], - ["{mixed*}", [ - "list.one,list.two,list.three,dict.two.comma=%2C,dict.one.dot=.,dict.one.semi=%3B", - "list.one,list.two,list.three,dict.two.comma=%2C,dict.one.semi=%3B,dict.one.dot=.", - "list.one,list.two,list.three,dict.one.dot=.,dict.two.comma=%2C,dict.one.semi=%3B", - "list.one,list.two,list.three,dict.one.dot=.,dict.one.semi=%3B,dict.two.comma=%2C", - "list.one,list.two,list.three,dict.one.semi=%3B,dict.two.comma=%2C,dict.one.dot=.", - "list.one,list.two,list.three,dict.one.semi=%3B,dict.one.dot=.,dict.two.comma=%2C" - ]], - ["{?mixed}", [ - "?mixed=list.one,list.two,list.three,dict.two.comma,%2C,dict.one.dot,.,dict.one.semi,%3B", - "?mixed=list.one,list.two,list.three,dict.two.comma,%2C,dict.one.semi,%3B,dict.one.dot,.", - "?mixed=list.one,list.two,list.three,dict.one.dot,.,dict.two.comma,%2C,dict.one.semi,%3B", - "?mixed=list.one,list.two,list.three,dict.one.dot,.,dict.one.semi,%3B,dict.two.comma,%2C", - "?mixed=list.one,list.two,list.three,dict.one.semi,%3B,dict.two.comma,%2C,dict.one.dot,.", - "?mixed=list.one,list.two,list.three,dict.one.semi,%3B,dict.one.dot,.,dict.two.comma,%2C" - ]], - ["{?mixed*}", [ - "?list=one&list=two&list=three&dict.two.comma=%2C&dict.one.dot=.&dict.one.semi=%3B", - "?list=one&list=two&list=three&dict.two.comma,%2C&dict.one.semi=%3B&dict.one.dot=.", - "?list=one&list=two&list=three&dict.one.dot=.&dict.two.comma=%2C&dict.one.semi=%3B", - "?list=one&list=two&list=three&dict.one.dot=.&dict.one.semi=%3B&dict.two.comma=%2C", - "?list=one&list=two&list=three&dict.one.semi=%3B&dict.two.comma=%2C&dict.one.dot=.", - "?list=one&list=two&list=three&dict.one.semi=%3B&dict.one.dot=.&dict.two.comma=%2C" - ]], - ["{dlist}", [ - "dot,.,semi,%3B,comma,%2C", - "semi,%3B,dot,.,comma,%2C" - ]], - ["{dlist*}", [ - "dot=.,semi=%3B,comma=%2C", - "semi=%3B,dot=.,comma=%2C" - ]], - ["{?dlist}", [ - "?dlist=dot,.,semi,%3B,comma,%2C", - "?dlist=semi,%3B,dot,.,comma,%2C" - ]], - ["{?dlist*}", [ - "?dlist.dot=.&dlist.semi=%3B&dlist.comma=%2C", - "?dlist.semi=%3B&dlist.dot=.&dlist.comma=%2C" - ]] - ] - }, - "Array Modifier" : - { - "level": 5, - "variables": { - "list" : ["one", "two", "three", "four"], - "dict" : {"semi": ";", "dot": ".", "comma": ","}, - "lists" : [["one", "two"], ["three"], "four"], - "dicts" : {"one": {"semi": ";", "dot": "."}, "two": {"comma": ","}}, - "mixed" : {"list": ["one", ["two", "three"]], "dict": {"one": {"semi": ";", "dot": "."}, "two": {"comma": ","}}}, - "dlist" : [{"semi": ";", "dot": "."}, {"comma": ","}] - }, - "testcases" : [ - ["{list[]}", "one,two,three,four"], - ["{?list[]}", "?list[0]=one&list[1]=two&list[2]=three&list[3]=four"], - ["{lists[]}", "one,two,three,four"], - ["{?lists[]}", "?lists[0][0]=one&lists[0][1]=two&lists[1][0]=three&lists[2]=four"], - ["{dict[]}", [ - "comma=%2C,dot=.,semi=%3B", - "comma=%2C,semi=%3B,dot=.", - "dot=.,comma=%2C,semi=%3B", - "dot=.,semi=%3B,comma=%2C", - "semi=%3B,comma=%2C,dot=.", - "semi=%3B,dot=.,comma=%2C" - ]], - ["{?dict[]}", [ - "?comma=%2C&dot=.&semi=%3B", - "?comma=%2C&semi=%3B&dot=.", - "?dot=.&comma=%2C&semi=%3B", - "?dot=.&semi=%3B&comma=%2C", - "?semi=%3B&comma=%2C&dot=.", - "?semi=%3B&dot=.&comma=%2C" - ]], - ["{dicts[]}", [ - "two[comma]=%2C,one[dot]=.,one[semi]=%3B", - "two[comma]=%2C,one[semi]=%3B,one[dot]=.", - "one[dot]=.,two[comma]=%2C,one[semi]=%3B", - "one[dot]=.,one[semi]=%3B,two[comma]=%2C", - "one[semi]=%3B,two[comma]=%2C,one[dot]=.", - "one[semi]=%3B,one[dot]=.,two[comma]=%2C" - ]], - ["{?dicts[]}", [ - "?two[comma]=%2C&one[dot]=.&one[semi]=%3B", - "?two[comma]=%2C&one[semi]=%3B&one[dot]=.", - "?one[dot]=.&two[comma]=%2C&one[semi]=%3B", - "?one[dot]=.&one[semi]=%3B&two[comma]=%2C", - "?one[semi]=%3B&two[comma]=%2C&one[dot]=.", - "?one[semi]=%3B&one[dot]=.&two[comma]=%2C" - ]], - ["{mixed[]}", [ - "list[0]=one,list[1][0]=two,list[1][1]=three,dict[two][comma]=%2C,dict[one][dot]=.,dict[one][semi]=%3B", - "list[0]=one,list[1][0]=two,list[1][1]=three,dict[two][comma]=%2C,dict[one][semi]=%3B,dict[one][dot]=.", - "list[0]=one,list[1][0]=two,list[1][1]=three,dict[one][dot]=.,dict[two][comma]=%2C,dict[one][semi]=%3B", - "list[0]=one,list[1][0]=two,list[1][1]=three,dict[one][dot]=.,dict[one][semi]=%3B,dict[two][comma]=%2C", - "list[0]=one,list[1][0]=two,list[1][1]=three,dict[one][semi]=%3B,dict[two][comma]=%2C,dict[one][dot]=.", - "list[0]=one,list[1][0]=two,list[1][1]=three,dict[one][semi]=%3B,dict[one][dot]=.,dict[two][comma]=%2C" - ]], - ["{?mixed[]}", [ - "?list[0]=one&list[1][0]=two&list[1][1]=three&dict[two][comma]=%2C&dict[one][dot]=.&dict[one][semi]=%3B", - "?list[0]=one&list[1][0]=two&list[1][1]=three&dict[two][comma]=%2C&dict[one][semi]=%3B&dict[one][dot]=.", - "?list[0]=one&list[1][0]=two&list[1][1]=three&dict[one][dot]=.&dict[two][comma]=%2C&dict[one][semi]=%3B", - "?list[0]=one&list[1][0]=two&list[1][1]=three&dict[one][dot]=.&dict[one][semi]=%3B&dict[two][comma]=%2C", - "?list[0]=one&list[1][0]=two&list[1][1]=three&dict[one][semi]=%3B&dict[two][comma]=%2C&dict[one][dot]=.", - "?list[0]=one&list[1][0]=two&list[1][1]=three&dict[one][semi]=%3B&dict[one][dot]=.&dict[two][comma]=%2C" - ]], - ["{dlist[]}", [ - "dot=.,semi=%3B,comma=%2C", - "semi=%3B,dot=.,comma=%2C" - ]], - ["{?dlist[]}", [ - "?dlist[0][dot]=.&dlist[0][semi]=%3B&dlist[1][comma]=%2C", - "?dlist[0][semi]=%3B&dlist[0][dot]=.&dlist[1][comma]=%2C" - ]] - ] - } -} diff --git a/tests/wpt/web-platform-tests/css/tools/build.py b/tests/wpt/web-platform-tests/css/tools/build.py deleted file mode 100644 index 9bbc2a5e753..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/build.py +++ /dev/null @@ -1,386 +0,0 @@ -#!/usr/bin/env python - -# CSS Test Suite Build Script -# Copyright 2011 Hewlett-Packard Development Company, L.P. -# Initial code by fantasai, joint copyright 2010 W3C and Microsoft -# Licensed under BSD 3-Clause: - -import sys -import os -import json -import optparse -import shutil -from collections import defaultdict -from apiclient import apiclient -from w3ctestlib import Sources, Utils, Suite, Indexer -from mercurial import ui - - - -class Builder(object): - def __init__(self, ui, outputPath, backupPath, ignorePaths, onlyCache): - self.reset(onlyCache) - self.ui = ui - self.skipDirs = ('support') - self.rawDirs = {'other-formats': 'other'} - self.sourceTree = Sources.SourceTree() - self.sourceCache = Sources.SourceCache(self.sourceTree) - self.cacheDir = 'tools/cache' - self.outputPath = outputPath.rstrip('/') if (outputPath) else 'dist' - self.backupPath = backupPath.rstrip('/') if (backupPath) else None - self.ignorePaths = [path.rstrip('/') for path in ignorePaths] if (ignorePaths) else [] - self.workPath = 'build-temp' - self.ignorePaths += (self.outputPath, self.backupPath, self.workPath) - - def reset(self, onlyCache): - self.useCacheOnly = onlyCache - self.shepherd = apiclient.apiclient.APIClient('https://api.csswg.org/shepherd/', version = 'vnd.csswg.shepherd.v1') if (not onlyCache) else None - self.cacheData = False - self.testSuiteData = {} - self.specificationData = {} - self.flagData = {} - self.specNames = {} - self.specAnchors = {} - self.buildSuiteNames = [] - self.buildSpecNames = {} - self.testSuites = {} - - - def _loadShepherdData(self, apiName, description, **kwargs): - self.ui.status("Loading ", description, " information\n") - cacheFile = os.path.join(self.cacheDir, apiName + '.json') - if (not self.useCacheOnly or (not os.path.exists(cacheFile))): - result = self.shepherd.get(apiName, **kwargs) - if (result and (200 == result.status)): - data = {} - for name in result.data: # trim leading _ - data[name[1:]] = result.data[name] - with open(cacheFile, 'w') as file: - json.dump(data, file) - return data - self.ui.status("Shepherd API call failed, result: ", result.status if result else 'None', "\n") - if (os.path.exists(cacheFile)): - self.ui.status("Loading cached data.\n") - try: - with open(cacheFile, 'r') as file: - return json.load(file) - except: - pass - return None - - def _addAnchors(self, anchors, specName): - for anchor in anchors: - self.specAnchors[specName].add(anchor['uri'].lower()) - if ('children' in anchor): - self._addAnchors(anchor['children'], specName) - - def _normalizeScheme(self, url): - if (url and url.startswith('http:')): - return 'https:' + url[5:] - return url - - def getSpecName(self, url): - if (not self.specNames): - for specName in self.specificationData: - specData = self.specificationData[specName] - officialURL = self._normalizeScheme(specData.get('base_uri')) - if (officialURL): - if (officialURL.endswith('/')): - officialURL = officialURL[:-1] - self.specNames[officialURL.lower()] = specName - draftURL = self._normalizeScheme(specData.get('draft_uri')) - if (draftURL): - if (draftURL.endswith('/')): - draftURL = draftURL[:-1] - self.specNames[draftURL.lower()] = specName - self.specAnchors[specName] = set() - if ('anchors' in specData): - self._addAnchors(specData['anchors'], specName) - if ('draft_anchors' in specData): - self._addAnchors(specData['draft_anchors'], specName) - - url = self._normalizeScheme(url.lower()) - for specURL in self.specNames: - if (url.startswith(specURL) and - ((url == specURL) or - url.startswith(specURL + '/') or - url.startswith(specURL + '#'))): - anchorURL = url[len(specURL):] - if (anchorURL.startswith('/')): - anchorURL = anchorURL[1:] - specName = self.specNames[specURL] - if (anchorURL in self.specAnchors[specName]): - return (specName, anchorURL) - return (specName, None) - return (None, None) - - def gatherTests(self, dir): - dirName = os.path.basename(dir) - if (dirName in self.skipDirs): - return - - self.ui.note("Scanning directory: ", dir, "\n") - suiteFileNames = defaultdict(set) - for fileName in Utils.listfiles(dir): - filePath = os.path.join(dir, fileName) - if not self.sourceTree.isTestCase(filePath): - continue - - source = self.sourceCache.generateSource(filePath, fileName) - if not source.isTest(): - continue - - try: - metaData = source.getMetadata(True) - except Exception as error: - self.ui.warn("Exception parsing '", filePath, "': ", error, "\n") - continue - - if not metaData: - if (source.errors): - self.ui.warn("Error parsing '", filePath, "': ", ' '.join(source.errors), "\n") - else: - self.ui.warn("No metadata available for '", filePath, "'\n") - continue - - for specURL in metaData['links']: - specName, anchorURL = self.getSpecName(specURL) - if not specName: - self.ui.note("Unknown specification URL: ", specURL, "\n in: ", filePath, "\n") - continue - - if not specName in self.buildSpecNames: - continue - - if not anchorURL: - self.ui.warn("Test links to unknown specification anchor: ", specURL, "\n in: ", filePath, "\n") - continue - - for testSuiteName in self.buildSpecNames[specName]: - formats = self.testSuiteData[testSuiteName].get('formats') - if (formats): - for formatName in formats: - if (((formatName) in self.formatData) and - (self.formatData[formatName].get('mime_type') == source.mimetype)): - suiteFileNames[testSuiteName].add(fileName) - break - else: - self.ui.note("Test not in acceptable format: ", source.mimetype, "\n for: ", filePath, "\n") - - for testSuiteName in suiteFileNames: - if (dirName in self.rawDirs): - self.testSuites[testSuiteName].addRaw(dir, self.rawDirs[dirName]) - else: - self.testSuites[testSuiteName].addTestsByList(dir, suiteFileNames[testSuiteName]) - - for subDir in Utils.listdirs(dir): - subDirPath = os.path.join(dir, subDir) - if (not (self.sourceTree.isIgnoredDir(subDirPath) or (subDirPath in self.ignorePaths))): - self.gatherTests(subDirPath) - - - def _findSections(self, baseURL, anchors, sectionData, parentSectionName = ''): - if (anchors): - for anchor in anchors: - if ('section' in anchor): - sectionData.append((baseURL + anchor['uri'], anchor['name'], - anchor['title'] if 'title' in anchor else 'Untitled')) - else: - sectionData.append((baseURL + anchor['uri'], parentSectionName + '.#' + anchor['name'], None)) - if ('children' in anchor): - self._findSections(baseURL, anchor['children'], sectionData, anchor['name']) - return sectionData - - def getSections(self, specName): - specData = self.specificationData[specName] - specURL = specData['base_uri'] if ('base_uri' in specData) else specData.get('draft_uri') - anchorData = specData['anchors'] if ('anchors' in specData) else specData['draft_anchors'] - sectionData = [] - self._findSections(specURL, anchorData, sectionData) - return sectionData - - def _user(self, user): - if (user): - data = user['full_name'] - if ('organization' in user): - data += ', ' + user['organization'] - if ('uri' in user): - data += ', ' + user['uri'] - elif ('email' in user): - data += ', <' + user['email'].replace('@', ' @') + '>' - return data - return 'None Yet' - - def getSuiteData(self): - data = {} - for testSuiteName in self.testSuiteData: - testSuiteData = self.testSuiteData[testSuiteName] - specData = self.specificationData[testSuiteData['specs'][0]] - data[testSuiteName] = { - 'title': testSuiteData['title'] if ('title' in testSuiteData) else 'Untitled', - 'spec': specData['title'] if ('title' in specData) else specData['name'], - 'specroot': specData['base_uri'] if ('base_uri' in specData) else specData.get('draft_uri'), - 'draftroot': specData['draft_uri'] if ('draft_uri' in specData) else specData.get('base_uri'), - 'owner': self._user(testSuiteData['owners'][0] if ('owners' in testSuiteData) else None), - 'harness': testSuiteName, - 'status': testSuiteData['status'] if ('status' in testSuiteData) else 'Unknown' - } - return data - - def getFlags(self): - data = {} - for flag in self.flagData: - flagData = self.flagData[flag] - data[flag] = { - 'title': flagData['description'] if ('description' in flagData) else 'Unknown', - 'abbr': flagData['title'] if ('title' in flagData) else flag - } - return data - - - def build(self, testSuiteNames): - try: - os.makedirs(self.cacheDir) - except: - pass - self.testSuiteData = self._loadShepherdData('test_suites', 'test suite', repo = 'css') - if (not self.testSuiteData): - self.ui.warn("ERROR: Unable to load test suite information.\n") - return -1 - if (testSuiteNames): - self.buildSuiteNames = [] - for testSuiteName in testSuiteNames: - if (testSuiteName in self.testSuiteData): - self.buildSuiteNames.append(testSuiteName) - else: - self.ui.status("Unknown test suite: ", testSuiteName, "\n") - else: - self.buildSuiteNames = [testSuiteName for testSuiteName in self.testSuiteData if self.testSuiteData[testSuiteName].get('build')] - - self.buildSpecNames = defaultdict(list) - if (self.buildSuiteNames): - self.specificationData = self._loadShepherdData('specifications', 'specification', anchors = True, draft = True) - if (not self.specificationData): - self.ui.warn("ERROR: Unable to load specification information.\n") - return -2 - for testSuiteName in self.buildSuiteNames: - specNames = self.testSuiteData[testSuiteName].get('specs') - if (specNames): - for specName in specNames: - if (specName in self.specificationData): - self.buildSpecNames[specName].append(testSuiteName) - else: - self.ui.warn("WARNING: Test suite '", testSuiteName, "' references unknown specification: '", specName, "'.\n") - else: - self.ui.warn("ERROR: Test suite '", testSuiteName, "' does not have target specifications.\n") - return -6 - else: - self.ui.status("No test suites identified\n") - return 0 - - if (not self.buildSpecNames): - self.ui.status("No target specifications identified\n") - return -3 - - self.flagData = self._loadShepherdData('test_flags', 'test flag') - if (not self.flagData): - self.ui.warn("ERROR: Unable to load flag information\n") - return -4 - - self.formatData = self._loadShepherdData('test_formats', 'test format') - if (not self.formatData): - self.ui.warn("ERROR: Unable to load format information\n") - return -5 - - - self.buildSuiteNames.sort() - - for testSuiteName in self.buildSuiteNames: - data = self.testSuiteData[testSuiteName] - specData = self.specificationData[data['specs'][0]] - specURL = specData['base_uri'] if ('base_uri' in specData) else specData.get('draft_uri') - draftURL = specData['draft_uri'] if ('draft_uri' in specData) else specData.get('base_uri') - self.testSuites[testSuiteName] = Suite.TestSuite(testSuiteName, data['title'], specURL, draftURL, self.sourceCache, self.ui) # XXX need to support multiple specs - if ('formats' in data): - self.testSuites[testSuiteName].setFormats(data['formats']) - - self.ui.status("Scanning test files\n") - - for dir in Utils.listdirs('.'): - if (not (self.sourceTree.isIgnoredDir(dir) or (dir in self.ignorePaths))): - self.gatherTests(dir) - - - if (os.path.exists(self.workPath)): - self.ui.note("Clearing work path: ", self.workPath, "\n") - shutil.rmtree(self.workPath) - - suiteData = self.getSuiteData() - flagData = self.getFlags() - templatePath = os.path.join('tools', 'templates') - for testSuiteName in self.buildSuiteNames: - testSuite = self.testSuites[testSuiteName] - self.ui.status("Building ", testSuiteName, "\n") - specSections = self.getSections(self.testSuiteData[testSuiteName]['specs'][0]) - indexer = Indexer.Indexer(testSuite, specSections, suiteData, flagData, True, - templatePathList = [templatePath], - extraData = {'devel' : False, 'official' : True }) - workPath = os.path.join(self.workPath, testSuiteName) - testSuite.buildInto(workPath, indexer) - - # move from work path to output path - for testSuiteName in self.buildSuiteNames: - workPath = os.path.join(self.workPath, testSuiteName) - outputPath = os.path.join(self.outputPath, testSuiteName) - backupPath = os.path.join(self.backupPath, testSuiteName) if (self.backupPath) else None - if (os.path.exists(workPath)): - if (os.path.exists(outputPath)): - if (backupPath): - if (os.path.exists(backupPath)): - self.ui.note("Removing ", backupPath, "\n") - shutil.rmtree(backupPath) # delete old backup - self.ui.note("Backing up ", outputPath, " to ", backupPath, "\n") - shutil.move(outputPath, backupPath) # backup old output - else: - self.ui.note("Removing ", outputPath, "\n") - shutil.rmtree(outputPath) # no backups, delete old output - self.ui.note("Moving ", workPath, " to ", outputPath, "\n") - shutil.move(workPath, outputPath) - if (os.path.exists(self.workPath)): - shutil.rmtree(self.workPath) - return 0 - - - -if __name__ == "__main__": # called from the command line - parser = optparse.OptionParser(usage = "usage: %prog [options] test_suite [...]") - parser.add_option("-q", "--quiet", - action = "store_true", dest = "quiet", default = False, - help = "don't print status messages to stdout") - parser.add_option("-d", "--debug", - action = "store_true", dest = "debug", default = False, - help = "print detailed debugging information to stdout") - parser.add_option("-v", "--verbose", - action = "store_true", dest = "verbose", default = False, - help = "print more detailed debugging information to stdout") - parser.add_option("-o", "--output", dest = "output", metavar = "OUTPUT_PATH", - help = "Path to build into (default 'dist')") - parser.add_option("-b", "--backup", dest = "backup", metavar = "BACKUP_PATH", - help = "Path to preserve old version to") - parser.add_option("-i", "--ignore", - action = "append", dest = "ignore", metavar = "IGNORE_PATH", - help = "Ignore files in this path") - parser.add_option("-c", "--cache", - action = "store_true", dest = "cache", default = False, - help = "use cached test suite and specification data only") - (options, args) = parser.parse_args() - - - ui = ui.ui() - ui.setconfig('ui', 'debug', str(options.debug)) - ui.setconfig('ui', 'quiet', str(options.quiet)) - ui.setconfig('ui', 'verbose', str(options.verbose)) - - builder = Builder(ui, options.output, options.backup, options.ignore, options.cache) - result = builder.build(args) - quit(result) diff --git a/tests/wpt/web-platform-tests/css/tools/build.sh b/tests/wpt/web-platform-tests/css/tools/build.sh deleted file mode 100755 index 326fe632a8c..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/build.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env sh -set -ex - -SCRIPT_DIR=$(cd $(dirname "$0") && pwd -P) - -main() { - cd $SCRIPT_DIR - - if [ -z $VENV ]; then - VENV=_virtualenv - fi - - # Create the virtualenv - if [ ! -d $VENV ]; then - if [ -z $PYTHON ]; then - command -v python - if [ $? -eq 0 ]; then - if [ `python -c 'import sys; print(sys.version[0:3])'` == "2.7" ]; then - PYTHON=python - fi - fi - fi - - if [ -z $PYTHON ]; then - command -v python2 - if [ $? -eq 0 ]; then - PYTHON=python2 - fi - fi - - if [ -z $PYTHON ]; then - echo "Please ensure Python 2.7 is installed" - exit 1 - fi - - # The maximum Unicode code point is U+10FFFF = 1114111 - if [ `$PYTHON -c 'import sys; print(sys.maxunicode)'` != "1114111" ]; then - echo "UCS-4 support for Python is required" - exit 1 - fi - - virtualenv -p $PYTHON $VENV || { echo "Please ensure virtualenv is installed"; exit 2; } - fi - - # Install dependencies - $VENV/bin/pip install -r requirements.txt - - # Run the build script - $VENV/bin/python build.py "$@" -} - -main "$@" diff --git a/tests/wpt/web-platform-tests/css/tools/requirements.txt b/tests/wpt/web-platform-tests/css/tools/requirements.txt deleted file mode 100644 index 1dd5c6e8384..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/requirements.txt +++ /dev/null @@ -1,8 +0,0 @@ -# Warning: The CSS build system is not tested in CI at all, so do not bump these -# dependencies without making sure that the build script still works. -Template-Python==0.1.post1 -html5lib==1.1 -lxml==4.9.1 -mercurial==4.6.1 -six==1.16.0 -webencodings==0.5.1 diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/.hgignore b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/.hgignore deleted file mode 100644 index 26c28932237..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/.hgignore +++ /dev/null @@ -1,7 +0,0 @@ -syntax: glob - -*.xcodeproj -*.DS_Store -*.pyc -*.svn -*.directory diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Groups.py b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Groups.py deleted file mode 100644 index 192ae9b6fdf..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Groups.py +++ /dev/null @@ -1,201 +0,0 @@ -#!/usr/bin/python -# CSS Test Suite Manipulation Library -# Initial code by fantasai, joint copyright 2010 W3C and Microsoft -# Licensed under BSD 3-Clause: - -import shutil -import filecmp -import os.path -import Utils -from os.path import exists, join -from Sources import SourceCache, SourceSet, ConfigSource, ReftestManifest -from Utils import listfiles - -excludeDirs = ['CVS', '.svn', '.hg'] - -class TestGroup: - """Base class for test groups. Should never be used directly. - """ - - @staticmethod - def combine(groupA, groupB): - """Merge TestGroup `groupB` into `groupA`. Return the result of the merge. - Can accept none as arguments. - """ - if groupA and groupB: - groupA.merge(groupB) - return groupA or groupB - - def __init__(self, sourceCache, importDir, name=None, title=None, ui = None, **kwargs): - """Initialize with: - SourceCache `sourceCache` - Group name `name`, which must be a possible directory name or None - Directory path `importDir`, whose context is imported into the group - Option: Tuple of support directory names `supportDirNames` defaults - to ('support',). - Kwarg: File path manifestPath relative to `importDir` that - identifies the reftest manifest file (usually called 'reftest.list'). - Kwarg: File path manifestDest as destination (relative) path for - the reftest manifest file. Defaults to value of manifestPath. - If manifest provided, assumes that only the files listed in the manifest, - the .htaccess files in its parent directory, and the `importDir`'s - .htaccess file and support directory are relevant to the test suite. - """ - assert exists(importDir), "Directory to import %s does not exist" % importDir - - # Save name - self.name = name - self.title = title - - self.ui = ui - - sourceTree = sourceCache.sourceTree - - # Load htaccess - htapath = join(importDir, '.htaccess') - self.htaccess = ConfigSource(sourceTree, htapath, '.htaccess') \ - if exists(htapath) else None - - # Load support files - self.support = SourceSet(sourceCache) - supportDirNames = kwargs.get('supportDirNames', ('support',)) - for supportName in supportDirNames: - supportDir = join(importDir, supportName) - if exists(supportDir): - for (root, dirs, files) in os.walk(supportDir): - for dir in excludeDirs: - if dir in dirs: - dirs.remove(dir) - for name in files: - sourcepath = join(root, name) - relpath = Utils.relpath(sourcepath, importDir) - self.support.add(sourcepath, relpath, self.ui) - - # Load tests - self.tests = SourceSet(sourceCache) - self.refs = SourceSet(sourceCache) - - # Read manifest - manifestPath = kwargs.get('manifestPath', None) - manifestDest = kwargs.get('manifestDest', manifestPath) - if (manifestPath): - self.manifest = ReftestManifest(join(importDir, manifestPath), manifestDest) - - # Import tests - for (testSrc, refSrc), (testRel, refRel), refType in self.manifest: - test = sourceCache.generateSource(testSrc, testRel) - ref = sourceCache.generateSource(refSrc, refRel) - test.addReference(ref, refType) - self.tests.addSource(test, self.ui) - else: - self.manifest = None - # Import tests - fileNameList = [] - if kwargs.get('selfTestExt'): - fileNameList += listfiles(importDir, kwargs['selfTestExt']) - if kwargs.get('selfTestList'): - fileNameList += kwargs['selfTestList'] - for fileName in fileNameList: - filePath = join(importDir, fileName) - if sourceTree.isTestCase(filePath): - test = sourceCache.generateSource(filePath, fileName) - if (test.isTest()): - self.tests.addSource(test, self.ui) - - for test in self.tests.iter(): - if (test.isReftest()): - usedRefs = {} - usedRefs[test.sourcepath] = '==' - def loadReferences(source): # XXX need to verify refType for mutual exclusion (ie: a == b != a) - for refSrcPath, refRelPath, refType in source.getReferencePaths(): - if (exists(refSrcPath)): - ref = sourceCache.generateSource(refSrcPath, refRelPath) - source.addReference(ref) - if (refSrcPath not in usedRefs): - usedRefs[refSrcPath] = refType - if (ref not in self.tests): - self.refs.addSource(ref, self.ui) - loadReferences(ref) - else: - ui.warn("Missing Reference file: ", refSrcPath, "\n referenced from: ", source.sourcepath, "\n") - loadReferences(test) - - - def sourceCache(self): - return self.support.sourceCache - - def count(self): - """Returns number of tests. - """ - return len(self.tests) - - def iterTests(self): - return self.tests.iter() - - def _initFrom(self, group=None): - """Initialize with data from TestGroup `group`.""" - # copy - self.name = group.name if group else None - self.title = group.title if group else None - self.htaccess = group.htaccess if group else None - self.support = group.support if group else None - self.tests = group.tests if group else None - - def merge(self, other): - """Merge Group `other`'s contents into this Group and clear its contents. - """ - assert isinstance(other, TestGroup), \ - "Expected Group instance, got %s" % type(other) - if self.htaccess and other.htaccess: - self.htaccess.append(other.htaccess) - else: - self.htaccess = self.htaccess or other.htaccess - other.htaccess = None - - self.support = SourceSet.combine(self.support, other.support, self.ui) - other.support = None - - self.tests = SourceSet.combine(self.tests, other.tests, self.ui) - other.tests = None - - self.refs = SourceSet.combine(self.refs, other.refs, self.ui) - other.refs = None - if self.manifest and other.manifest: - self.manifest.append(other.manifest) - else: - self.manifest = self.manifest or other.manifest - other.manifest = None - - - def build(self, format): - """Build Group's contents through OutputFormat `format`. - """ - format.setSubDir(self.name) - - # Write .htaccess - if self.htaccess: - format.write(self.htaccess) - - # Write support files - format.convert = False # XXX hack turn off format conversion - self.support.write(format) - format.convert = True # XXX undo hack - - # Write tests - self.tests.adjustContentPaths(format) - self.tests.write(format) - - # Write refs - self.refs.write(format) - if self.manifest: - format.write(self.manifest) - - # copy support files to reference directory (XXX temp until proper support path fixup) - formatDir = format.destDir() - supportDir = join(formatDir, 'support') - referenceDir = join(formatDir, 'reference') - if exists(supportDir) and exists(referenceDir): - shutil.copytree(supportDir, join(referenceDir, 'support')) - - format.setSubDir() - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/HTMLSerializer.py b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/HTMLSerializer.py deleted file mode 100644 index 7f73bc17ec8..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/HTMLSerializer.py +++ /dev/null @@ -1,277 +0,0 @@ -#!/usr/bin/python -# CSS Test Source Manipulation Library -# Initial code by fantasai, joint copyright 2010 W3C and Microsoft -# additions by peter.linss@hp.com copyright 2013 Hewlett-Packard -# Licensed under BSD 3-Clause: - -import lxml -from lxml import etree -import htmlentitydefs -import copy - - -class HTMLSerializer(object): - - gXMLns = 'http://www.w3.org/XML/1998/namespace' - gHTMLns = 'http://www.w3.org/1999/xhtml' - - gDefaultNamespaces = {'http://www.w3.org/XML/1998/namespace': 'xmlns', - 'http://www.w3.org/2000/xmlns/': 'xmlns', - 'http://www.w3.org/1999/xlink': 'xlink'} - - gVoidElements = frozenset(( - 'base', - 'command', - 'event-source', - 'link', - 'meta', - 'hr', - 'br', - 'img', - 'embed', - 'param', - 'area', - 'col', - 'input', - 'source' - )) - - gCDataElements = frozenset(( - 'style', - 'script' - )) - - gInvisibleChars = frozenset( - # ASCII control chars - range(0x0, 0x9) + range(0xB, 0xD) + range(0xE, 0x20) + - # Other control chars - # fixed-width spaces, zero-width marks, bidi marks - range(0x2000, 0x2010) + - # LS, PS, bidi control codes - range(0x2028, 0x2030) + - # nbsp, mathsp, ideosp, WJ, interlinear - [0x00A0, 0x205F, 0x3000, 0x2060, 0xFFF9, 0xFFFA, 0xFFFB] - ) - - gXMLEscapes = frozenset(gInvisibleChars | - frozenset((ord('&'), ord('<'), ord('>')))) - - gXMLEntityNames = {'"': 'quot', '&': 'amp', "'": 'apos', '<': 'lt', '>': 'gt'} - - gDocTypes = { - 'html': '', - 'html4': - '', - 'html4-transitional': - '', - 'html4-frameset': - '', - 'svg11': - '', - 'svg11-tiny': - '', - 'xhtml10': - '', - 'xhtml10-transitional': - '', - 'xhtml10-frameset': - '', - 'xhtml11': - '', - 'xhtml-basic11': - '' - } - - - def __init__(self): - self._reset() - - def _reset(self, xhtml = False): - self.mOutput = u'' - self.mXHTML = xhtml - - def _output(self, *args): - for arg in args: - self.mOutput += unicode(arg) - - def _escape(self, text, escapeChars): - # This algorithm is O(MN) for M len(text) and N num escapable - # But it doesn't modify the text when N is zero (common case) and - # N is expected to be small (usually 1 or 2) in most other cases. - escapable = set() - for char in text: - if ord(char) in escapeChars: - escapable.add(char) - for char in escapable: - if (self.mXHTML): - name = self.gXMLEntityNames.get(char) - else: - name = htmlentitydefs.codepoint2name.get(ord(char)) - escape = u'&%s;' % name if name else u'&#x%X;' % ord(char) - text = text.replace(char, escape) - return text - - def _escapeXML(self, text): - return self._escape(text, self.gXMLEscapes) - - def _escapeInvisible(self, text): - return self._escape(text, self.gInvisibleChars) - - def _serializeElement(self, element, namespacePrefixes): - qName = etree.QName(element) - attrs = element.attrib.items() # in tree order - - if (not namespacePrefixes): - namespacePrefixes = self.gDefaultNamespaces - - if (self.mXHTML): - namespacePrefixes = copy.copy(namespacePrefixes) - for attr, value in attrs: - attrQName = etree.QName(attr) - if (self.gXMLns == attrQName.namespace): - namespacePrefixes[value] = attrQName.localname - elif ('xmlns' == attrQName.localname): - namespacePrefixes[value] = '' - - if (self.mXHTML and qName.namespace and namespacePrefixes[qName.namespace]): - self._output('<', namespacePrefixes[qName.namespace], ':', qName.localname) - else: - self._output('<', qName.localname) - - for attr, value in attrs: - attrQName = etree.QName(attr) - if ((attrQName.namespace == self.gXMLns) and ('lang' == attrQName.localname)): - if (self.mXHTML): - attr = 'xml:lang' - else: - attr = 'lang' - elif (attrQName.namespace and namespacePrefixes[attrQName.namespace]): - attr = namespacePrefixes[attrQName.namespace] + ':' + attrQName.localname - else: - attr = attrQName.localname - - self._output(' ', attr, '=') - value = value.replace('&', '&') - if (self.mXHTML): - value = value.replace('<', '<') - - if (('"' in value) and ("'" not in value)): - self._output("'", self._escapeInvisible(value), "'") - else: - self._output('"', self._escapeInvisible(value.replace('"', '"')), '"') - - if ((qName.namespace == self.gHTMLns) and (qName.localname in self.gVoidElements)): - if (self.mXHTML): - self._output(' />') - else: - self._output('>') - else: - self._output('>') - - if (None != element.text): - if ((qName.namespace == self.gHTMLns) and (qName.localname in self.gCDataElements)): - if (self.mXHTML): - self._output(self._escapeXML(element.text)) # or self._output('') - else: - self._output(element.text) - else: - self._output(self._escapeXML(element.text)) - - for child in list(element): - self._serializeNode(child, namespacePrefixes) - - self._output('') - - if (None != element.tail): - self._output(self._escapeXML(element.tail)) - - def _serializeEntity(self, entity): - self._output(entity.text) - if (None != entity.tail): - self._output(self._escapeXML(entity.tail)) - - def _serializePI(self, pi): - if (self.mXHTML): - self._output('') - else: - raise Exception("Processing Instructions can't be converted to HTML") - if (None != pi.tail): - self._output(self._escapeXML(pi.tail)) - - def _serializeComment(self, comment): - self._output('') # XXX escape comment? - if (None != comment.tail): - self._output(self._escapeXML(comment.tail)) - - def _serializeNode(self, node, namespacePrefixes = None): - if (isinstance(node, etree._Entity)): - self._serializeEntity(node) - elif (isinstance(node, etree._ProcessingInstruction)): - self._serializePI(node) - elif (isinstance(node, etree._Comment)): - self._serializeComment(node) - else: - self._serializeElement(node, namespacePrefixes) - - - def _serializeTree(self, tree): - root = tree.getroot() - preceding = [node for node in root.itersiblings(preceding = True)] - preceding.reverse() - for node in preceding: - self._serializeNode(node) - self._serializeNode(root) - for node in root.itersiblings(): - self._serializeNode(node) - - def _serializeDoctype(self, tree, doctype, default): - if (doctype): - self._output(self.gDocTypes[doctype], '\n') - else: - if (hasattr(tree, 'docinfo') and tree.docinfo and tree.docinfo.doctype): - doctypeSearch = tree.docinfo.doctype.lower() - for doctype in self.gDocTypes: - if (self.gDocTypes[doctype].lower() == doctypeSearch): - break - else: - doctype = None - if (self.mXHTML): - if ('html' == doctype): - doctype = 'xhtml10' - elif ('html4' == doctype): - doctype = 'xhtml10' - elif ('html4-transitional' == doctype): - doctype = 'xhtml10-transitional' - elif ('html4-frameset' == doctype): - doctype = 'xhtml10-frameset' - else: - if ('xhtml10' == doctype): - doctype = 'html4' - elif ('xhtml10-transitional' == doctype): - doctype = 'html4-transitional' - elif ('xhtml10-frameset' == doctype): - doctype = 'html4-frameset' - elif ('xhtml11' == doctype): - doctype = 'html4' - if (doctype): - self._output(self.gDocTypes[doctype], '\n') - else: - self._output(tree.docinfo.doctype, '\n') - else: - self._output(self.gDocTypes[default], '\n') - - - def serializeHTML(self, tree, doctype = None): - self._reset() - self._serializeDoctype(tree, doctype, 'html') - self._serializeTree(tree) - return self.mOutput - - def serializeXHTML(self, tree, doctype = None): - self._reset(True) - # XXX ' - -# Define contains vmethod for Template Toolkit -from template.stash import list_op -@list_op("contains") -def list_contains(l, x): - return x in l - -import sys -import re -import os -import codecs -from os.path import join, exists, abspath -from template import Template -import w3ctestlib -from Utils import listfiles, escapeToNamedASCII -from OutputFormats import ExtensionMap -import shutil - -class Section: - def __init__(self, uri, title, numstr): - self.uri = uri - self.title = title - self.numstr = numstr - self.tests = [] - def __cmp__(self, other): - return cmp(self.natsortkey(), other.natsortkey()) - def chapterNum(self): - return self.numstr.partition('.')[0] - def natsortkey(self): - chunks = self.numstr.partition('.#')[0].split('.') - for index in range(len(chunks)): - if chunks[index].isdigit(): - # wrap in tuple with '0' to explicitly specify numbers come first - chunks[index] = (0, int(chunks[index])) - else: - chunks[index] = (1, chunks[index]) - return (chunks, self.numstr) - -class Indexer: - - def __init__(self, suite, sections, suites, flags, splitChapter=False, templatePathList=None, - extraData=None, overviewTmplNames=None, overviewCopyExts=('.css', 'htaccess')): - """Initialize indexer with TestSuite `suite` toc data file - `tocDataPath` and additional template paths in list `templatePathList`. - - The toc data file should be list of tab-separated records, one - per line, of each spec section's uri, number/letter, and title. - `splitChapter` selects a single page index if False, chapter - indicies if True. - `extraData` can be a dictionary whose data gets passed to the templates. - `overviewCopyExts` lists file extensions that should be found - and copied from the template path into the main build directory. - The default value is ['.css', 'htaccess']. - `overviewTemplateNames` lists template names that should be - processed from the template path into the main build directory. - The '.tmpl' extension, if any, is stripped from the output filename. - The default value is ['index.htm.tmpl', 'index.xht.tmpl', 'testinfo.data.tmpl'] - """ - self.suite = suite - self.splitChapter = splitChapter - self.extraData = extraData - self.overviewCopyExtPat = re.compile('.*(%s)$' % '|'.join(overviewCopyExts)) - self.overviewTmplNames = overviewTmplNames if overviewTmplNames is not None \ - else ['index.htm.tmpl', 'index.xht.tmpl', 'testinfo.data.tmpl', - 'implementation-report-TEMPLATE.data.tmpl'] - - # Initialize template engine - self.templatePath = [join(w3ctestlib.__path__[0], 'templates')] - if templatePathList: - self.templatePath.extend(templatePathList) - self.templatePath = [abspath(path) for path in self.templatePath] - self.tt = Template({ - 'INCLUDE_PATH': self.templatePath, - 'ENCODING' : 'utf-8', - 'PRE_CHOMP' : 1, - 'POST_CHOMP' : 0, - }) - - # Load toc data - self.sections = {} - for uri, numstr, title in sections: - uri = intern(uri.encode('utf-8')) - uriKey = intern(self._normalizeScheme(uri)) - numstr = escapeToNamedASCII(numstr) - title = escapeToNamedASCII(title) if title else None - self.sections[uriKey] = Section(uri, title, numstr) - - self.suites = suites - self.flags = flags - - # Initialize storage - self.errors = {} - self.contributors = {} - self.alltests = [] - - def _normalizeScheme(self, uri): - if (uri and uri.startswith('http:')): - return 'https:' + uri[5:] - return uri - - def indexGroup(self, group): - for test in group.iterTests(): - data = test.getMetadata() - if data: # Shallow copy for template output - data = dict(data) - data['file'] = '/'.join((group.name, test.relpath)) \ - if group.name else test.relpath - if (data['scripttest']): - data['flags'].append(intern('script')) - self.alltests.append(data) - for uri in data['links']: - uri = self._normalizeScheme(uri) - uri = uri.replace(self._normalizeScheme(self.suite.draftroot), self._normalizeScheme(self.suite.specroot)) - if self.sections.has_key(uri): - testlist = self.sections[uri].tests.append(data) - for credit in data['credits']: - self.contributors[credit[0]] = credit[1] - else: - self.errors[test.sourcepath] = test.errors - - def __writeTemplate(self, template, data, outfile): - o = self.tt.process(template, data) - with open(outfile, 'w') as f: - f.write(o.encode('utf-8')) - - def writeOverview(self, destDir, errorOut=sys.stderr, addTests=[]): - """Write format-agnostic pages such as test suite overview pages, - test data files, and error reports. - - Indexed errors are reported to errorOut, which must be either - an output handle such as sys.stderr, a tuple of - (template filename string, output filename string) - or None to suppress error output. - - `addTests` is a list of additional test paths, relative to the - overview root; it is intended for indexing raw tests - """ - - # Set common values - data = self.extraData.copy() - data['suitetitle'] = self.suite.title - data['suite'] = self.suite.name - data['specroot'] = self.suite.specroot - data['draftroot'] = self.suite.draftroot - data['contributors'] = self.contributors - data['tests'] = self.alltests - data['extmap'] = ExtensionMap({'.xht':'', '.html':'', '.htm':'', '.svg':''}) - data['formats'] = self.suite.formats - data['addtests'] = addTests - data['suites'] = self.suites - data['flagInfo'] = self.flags - data['formatInfo'] = { 'html4': { 'report': True, 'path': 'html4', 'ext': 'htm', 'filter': 'nonHTML'}, - 'html5': { 'report': True, 'path': 'html', 'ext': 'htm', 'filter': 'nonHTML' }, - 'xhtml1': { 'report': True, 'path': 'xhtml1', 'ext': 'xht', 'filter': 'HTMLonly' }, - 'xhtml1print': { 'report': False, 'path': 'xhtml1print', 'ext': 'xht', 'filter': 'HTMLonly' }, - 'svg': { 'report': True, 'path': 'svg', 'ext': 'svg', 'filter': 'HTMLonly' } - } - - # Copy simple copy files - for tmplDir in reversed(self.templatePath): - files = listfiles(tmplDir) - for file in files: - if self.overviewCopyExtPat.match(file): - shutil.copy(join(tmplDir, file), join(destDir, file)) - - # Generate indexes - for tmpl in self.overviewTmplNames: - out = tmpl[0:-5] if tmpl.endswith('.tmpl') else tmpl - self.__writeTemplate(tmpl, data, join(destDir, out)) - - # Report errors - if (self.errors): - if type(errorOut) is type(('tmpl','out')): - data['errors'] = errors - self.__writeTemplate(errorOut[0], data, join(destDir, errorOut[1])) - else: - sys.stdout.flush() - for errorLocation in self.errors: - print >> errorOut, "Error in %s: %s" % \ - (errorLocation, ' '.join([str(error) for error in self.errors[errorLocation]])) - - def writeIndex(self, format): - """Write indices into test suite build output through format `format`. - """ - - # Set common values - data = self.extraData.copy() - data['suitetitle'] = self.suite.title - data['suite'] = self.suite.name - data['specroot'] = self.suite.specroot - data['draftroot'] = self.suite.draftroot - - data['indexext'] = format.indexExt - data['isXML'] = format.indexExt.startswith('.x') - data['formatdir'] = format.formatDirName - data['extmap'] = format.extMap - data['tests'] = self.alltests - data['suites'] = self.suites - data['flagInfo'] = self.flags - - # Generate indices: - - # Reftest indices - self.__writeTemplate('reftest-toc.tmpl', data, - format.dest('reftest-toc%s' % format.indexExt)) - self.__writeTemplate('reftest.tmpl', data, - format.dest('reftest.list')) - - # Table of Contents - sectionlist = sorted(self.sections.values()) - if self.splitChapter: - # Split sectionlist into chapters - chapters = [] - lastChapNum = '$' # some nonmatching initial char - chap = None - for section in sectionlist: - if (section.title and (section.chapterNum() != lastChapNum)): - lastChapNum = section.chapterNum() - chap = section - chap.sections = [] - chap.testcount = 0 - chap.testnames = set() - chapters.append(chap) - chap.testnames.update([test['name'] for test in section.tests]) - chap.testcount = len(chap.testnames) - chap.sections.append(section) - - # Generate main toc - data['chapters'] = chapters - self.__writeTemplate('chapter-toc.tmpl', data, - format.dest('toc%s' % format.indexExt)) - del data['chapters'] - - # Generate chapter tocs - for chap in chapters: - data['chaptertitle'] = chap.title - data['testcount'] = chap.testcount - data['sections'] = chap.sections - self.__writeTemplate('test-toc.tmpl', data, format.dest('chapter-%s%s' \ - % (chap.numstr, format.indexExt))) - - else: # not splitChapter - data['chapters'] = sectionlist - self.__writeTemplate('test-toc.tmpl', data, - format.dest('toc%s' % format.indexExt)) - del data['chapters'] diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/OutputFormats.py b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/OutputFormats.py deleted file mode 100644 index 084e66d02f2..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/OutputFormats.py +++ /dev/null @@ -1,207 +0,0 @@ -#!/usr/bin/python -# CSS Test Source Manipulation Library -# Initial code by fantasai, joint copyright 2010 W3C and Microsoft -# Licensed under BSD 3-Clause: - -import re -import os -from os.path import join, exists, splitext, dirname, basename -from Sources import XHTMLSource, HTMLSource, SVGSource, SourceTree - -class ExtensionMap: - """ Given a file extension mapping (e.g. {'.xht' : '.htm'}), provides - a translate function for paths. - """ - def __init__(self, extMap): - self.extMap = extMap - - def translate(self, path): - for ext in self.extMap: - if path.endswith(ext): - return splitext(path)[0] + self.extMap[ext] - return path - -class BasicFormat: - """Base class. A Format manages all the conversions and location - transformations (e.g. subdirectory for all tests in that format) - associated with a test suite format. - - The base class implementation performs no conversions or - format-specific location transformations.""" - formatDirName = None - indexExt = '.htm' - convert = True # XXX hack to supress format conversion in support dirs, need to clean up output code to make this cleaner - - def __init__(self, destroot, sourceTree, extMap=None, outputDirName=None): - """Creates format root of the output tree. `destroot` is the root path - of the output tree. - - extMap provides a file extension mapping, e.g. {'.xht' : '.htm'} - """ - self.root = join(destroot, outputDirName) if outputDirName else destroot - self.sourceTree = sourceTree - self.formatDirName = outputDirName - if not exists(self.root): - os.makedirs(self.root) - self.extMap = ExtensionMap(extMap or {}) - self.subdir = None - - def setSubDir(self, name=None): - """Sets format to write into group subdirectory `name`. - """ - self.subdir = name - - def destDir(self): - return join(self.root, self.subdir) if self.subdir else self.root - - def dest(self, relpath): - """Returns final destination of relpath in this format and ensures that the - parent directory exists.""" - # Translate path - if (self.convert): - relpath = self.extMap.translate(relpath) - if (self.sourceTree.isReferenceAnywhere(relpath)): - relpath = join('reference', basename(relpath)) - # XXX when forcing support files into support path, need to account for support/support - dest = join(self.root, self.subdir, relpath) if self.subdir \ - else join(self.root, relpath) - # Ensure parent - parent = dirname(dest) - if not exists(parent): - os.makedirs(parent) - - return dest - - def write(self, source): - """Write FileSource to destination, following all necessary - conversion methods.""" - source.write(self, source) - - testTransform = False - # def testTransform(self, outputString, source) if needed - -class XHTMLFormat(BasicFormat): - """Base class for XHTML test suite format. Builds into 'xhtml1' subfolder - of root. - """ - indexExt = '.xht' - - def __init__(self, destroot, sourceTree, extMap=None, outputDirName='xhtml1'): - if not extMap: - extMap = {'.htm' : '.xht', '.html' : '.xht', '.xhtml' : '.xht' } - BasicFormat.__init__(self, destroot, sourceTree, extMap, outputDirName) - - def write(self, source): - # skip HTMLonly tests - if hasattr(source, 'hasFlag') and source.hasFlag('HTMLonly'): - return - if isinstance(source, HTMLSource) and self.convert: - source.write(self, source.serializeXHTML()) - else: - source.write(self) - -class HTMLFormat(BasicFormat): - """Base class for HTML test suite format. Builds into 'html4' subfolder - of root. - """ - - def __init__(self, destroot, sourceTree, extMap=None, outputDirName='html4'): - if not extMap: - extMap = {'.xht' : '.htm', '.xhtml' : '.htm', '.html' : '.htm' } - BasicFormat.__init__(self, destroot, sourceTree, extMap, outputDirName) - - def write(self, source): - # skip nonHTML tests - if hasattr(source, 'hasFlag') and source.hasFlag('nonHTML'): - return - if isinstance(source, XHTMLSource) and self.convert: - source.write(self, source.serializeHTML()) - else: - source.write(self) - - -class HTML5Format(HTMLFormat): - def __init__(self, destroot, sourceTree, extMap=None, outputDirName='html'): - HTMLFormat.__init__(self, destroot, sourceTree, extMap, outputDirName) - - def write(self, source): - # skip nonHTML tests - if hasattr(source, 'hasFlag') and source.hasFlag('nonHTML'): - return - if isinstance(source, XHTMLSource) and self.convert: - source.write(self, source.serializeHTML()) - else: - source.write(self) - - -class SVGFormat(BasicFormat): - def __init__(self, destroot, sourceTree, extMap=None, outputDirName='svg'): - if not extMap: - extMap = {'.svg' : '.svg' } - BasicFormat.__init__(self, destroot, sourceTree, extMap, outputDirName) - - def write(self, source): - # skip non SVG tests - if isinstance(source, SVGSource): - source.write(self) - - -class XHTMLPrintFormat(XHTMLFormat): - """Base class for XHTML Print test suite format. Builds into 'xhtml1print' - subfolder of root. - """ - - def __init__(self, destroot, sourceTree, testSuiteName, extMap=None, outputDirName='xhtml1print'): - if not extMap: - extMap = {'.htm' : '.xht', '.html' : '.xht', '.xhtml' : '.xht' } - BasicFormat.__init__(self, destroot, sourceTree, extMap, outputDirName) - self.testSuiteName = testSuiteName - - def write(self, source): - if (isinstance(source, XHTMLSource)): - if not source.hasFlag('HTMLonly'): - source.write(self, self.testTransform(source)) - else: - XHTMLFormat.write(self, source) - - def testTransform(self, source): - assert isinstance(source, XHTMLSource) - output = source.serializeXHTML('xhtml10') - - headermeta = {'suitename' : self.testSuiteName, - 'testid' : source.name(), - 'margin' : '', - } - if re.search('@page\s*{[^}]*@', output): - # Don't use headers and footers when page tests margin boxes - output = re.sub('(]*>)', - '\1\n' + self.__htmlstart % headermeta, - output); - output = re.sub('(]*>)', - '\1\n' + self.__htmlend % headermeta, - output); - else: - # add margin rule only when @page statement does not exist - if not re.search('@page', output): - headermeta['margin'] = self.__margin - output = re.sub('', - '\n ' % \ - (self.__css % headermeta), - output); - return output; - - # template bits - __margin = 'margin: 7%;'; - __font = 'font: italic 8pt sans-serif; color: gray;' - __css = """ - @page { %s - %%(margin)s - counter-increment: page; - @top-left { content: "%%(suitename)s"; } - @top-right { content: "Test %%(testid)s"; } - @bottom-right { content: counter(page); } - } -""" % __font - __htmlstart = '

Start of %%(suitename)s %%(testid)s.

' % __font - __htmlend = '

End of %%(suitename)s %%(testid)s.

' % __font - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Sources.py b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Sources.py deleted file mode 100644 index f3848030ba5..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Sources.py +++ /dev/null @@ -1,1473 +0,0 @@ -#!/usr/bin/python -# CSS Test Source Manipulation Library -# Initial code by fantasai, joint copyright 2010 W3C and Microsoft -# Licensed under BSD 3-Clause: - -from __future__ import print_function -from os.path import basename, exists, join -import os -import filecmp -import shutil -import re -import codecs -import collections -from xml import dom -import html5lib -from html5lib import treebuilders -from lxml import etree -from lxml.etree import ParseError -from Utils import getMimeFromExt, escapeToNamedASCII, basepath, isPathInsideBase, relativeURL, assetName -import HTMLSerializer -import warnings -import hashlib - -class SourceTree(object): - """Class that manages structure of test repository source. - Temporarily hard-coded path and filename rules, this should be configurable. - """ - - def __init__(self, repository = None): - self.mTestExtensions = ['.xht', '.html', '.xhtml', '.htm', '.xml', '.svg'] - self.mReferenceExtensions = ['.xht', '.html', '.xhtml', '.htm', '.xml', '.png', '.svg'] - self.mRepository = repository - - def _splitDirs(self, dir): - if ('' == dir): - pathList = [] - elif ('/' in dir): - pathList = dir.split('/') - else: - pathList = dir.split(os.path.sep) - return pathList - - def _splitPath(self, filePath): - """split a path into a list of directory names and the file name - paths may come form the os or mercurial, which always uses '/' as the - directory separator - """ - dir, fileName = os.path.split(filePath.lower()) - return (self._splitDirs(dir), fileName) - - def isTracked(self, filePath): - pathList, fileName = self._splitPath(filePath) - return (not self._isIgnored(pathList, fileName)) - - def _isApprovedPath(self, pathList): - return ((1 < len(pathList)) and ('approved' == pathList[0]) and (('support' == pathList[1]) or ('src' in pathList))) - - def isApprovedPath(self, filePath): - pathList, fileName = self._splitPath(filePath) - return (not self._isIgnored(pathList, fileName)) and self._isApprovedPath(pathList) - - def _isIgnoredPath(self, pathList): - return (('.hg' in pathList) or ('.git' in pathList) or - ('.svn' in pathList) or ('cvs' in pathList) or - ('incoming' in pathList) or ('work-in-progress' in pathList) or - ('data' in pathList) or ('archive' in pathList) or - ('reports' in pathList) or ('tools' == pathList[0]) or - ('test-plan' in pathList) or ('test-plans' in pathList)) - - def _isIgnored(self, pathList, fileName): - if (pathList): # ignore files in root - return (self._isIgnoredPath(pathList) or - fileName.startswith('.directory') or ('lock' == fileName) or - ('.ds_store' == fileName) or - fileName.startswith('.hg') or fileName.startswith('.git') or - ('sections.dat' == fileName) or ('get-spec-sections.pl' == fileName)) - return True - - def isIgnored(self, filePath): - pathList, fileName = self._splitPath(filePath) - return self._isIgnored(pathList, fileName) - - def isIgnoredDir(self, dir): - pathList = self._splitDirs(dir) - return self._isIgnoredPath(pathList) - - def _isToolPath(self, pathList): - return ('tools' in pathList) - - def _isTool(self, pathList, fileName): - return self._isToolPath(pathList) - - def isTool(self, filePath): - pathList, fileName = self._splitPath(filePath) - return (not self._isIgnored(pathList, fileName)) and self._isTool(pathList, fileName) - - def _isSupportPath(self, pathList): - return ('support' in pathList) - - def _isSupport(self, pathList, fileName): - return (self._isSupportPath(pathList) or - ((not self._isTool(pathList, fileName)) and - (not self._isReference(pathList, fileName)) and - (not self._isTestCase(pathList, fileName)))) - - def isSupport(self, filePath): - pathList, fileName = self._splitPath(filePath) - return (not self._isIgnored(pathList, fileName)) and self._isSupport(pathList, fileName) - - def _isReferencePath(self, pathList): - return (('reftest' in pathList) or ('reference' in pathList)) - - def _isReference(self, pathList, fileName): - if ((not self._isSupportPath(pathList)) and (not self._isToolPath(pathList))): - baseName, fileExt = os.path.splitext(fileName)[:2] - if (bool(re.search('(^ref-|^notref-).+', baseName)) or - bool(re.search('.+(-ref[0-9]*$|-notref[0-9]*$)', baseName)) or - ('-ref-' in baseName) or ('-notref-' in baseName)): - return (fileExt in self.mReferenceExtensions) - if (self._isReferencePath(pathList)): - return (fileExt in self.mReferenceExtensions) - return False - - def isReference(self, filePath): - pathList, fileName = self._splitPath(filePath) - return (not self._isIgnored(pathList, fileName)) and self._isReference(pathList, fileName) - - def isReferenceAnywhere(self, filePath): - pathList, fileName = self._splitPath(filePath) - return self._isReference(pathList, fileName) - - def _isTestCase(self, pathList, fileName): - if ((not self._isToolPath(pathList)) and (not self._isSupportPath(pathList)) and (not self._isReference(pathList, fileName))): - fileExt = os.path.splitext(fileName)[1] - return (fileExt in self.mTestExtensions) - return False - - def isTestCase(self, filePath): - pathList, fileName = self._splitPath(filePath) - return (not self._isIgnored(pathList, fileName)) and self._isTestCase(pathList, fileName) - - def getAssetName(self, filePath): - pathList, fileName = self._splitPath(filePath) - if (self._isReference(pathList, fileName) or self._isTestCase(pathList, fileName)): - return assetName(fileName) - return fileName.lower() # support files keep full name - - def getAssetType(self, filePath): - pathList, fileName = self._splitPath(filePath) - if (self._isReference(pathList, fileName)): - return intern('reference') - if (self._isTestCase(pathList, fileName)): - return intern('testcase') - if (self._isTool(pathList, fileName)): - return intern('tool') - return intern('support') - - -class SourceCache: - """Cache for FileSource objects. Supports one FileSource object - per sourcepath. - """ - def __init__(self, sourceTree): - self.__cache = {} - self.sourceTree = sourceTree - - def generateSource(self, sourcepath, relpath, data = None): - """Return a FileSource or derivative based on the extensionMap. - - Uses a cache to avoid creating more than one of the same object: - does not support creating two FileSources with the same sourcepath; - asserts if this is tried. (.htaccess files are not cached.) - - Cache is bypassed if loading form a change context - """ - if ((None == data) and self.__cache.has_key(sourcepath)): - source = self.__cache[sourcepath] - assert relpath == source.relpath - return source - - if basename(sourcepath) == '.htaccess': - return ConfigSource(self.sourceTree, sourcepath, relpath, data) - mime = getMimeFromExt(sourcepath) - if (mime == 'application/xhtml+xml'): - source = XHTMLSource(self.sourceTree, sourcepath, relpath, data) - elif (mime == 'text/html'): - source = HTMLSource(self.sourceTree, sourcepath, relpath, data) - elif (mime == 'image/svg+xml'): - source = SVGSource(self.sourceTree, sourcepath, relpath, data) - elif (mime == 'application/xml'): - source = XMLSource(self.sourceTree, sourcepath, relpath, data) - else: - source = FileSource(self.sourceTree, sourcepath, relpath, mime, data) - if (None == data): - self.__cache[sourcepath] = source - return source - -class SourceSet: - """Set of FileSource objects. No two FileSources of the same type in the set may - have the same name (except .htaccess files, which are merged). - """ - def __init__(self, sourceCache): - self.sourceCache = sourceCache - self.pathMap = {} # type/name -> source - - def __len__(self): - return len(self.pathMap) - - def _keyOf(self, source): - return source.type() + '/' + source.keyName() - - def __contains__(self, source): - return self._keyOf(source) in self.pathMap - - - def iter(self): - """Iterate over FileSource objects in SourceSet. - """ - return self.pathMap.itervalues() - - def addSource(self, source, ui): - """Add FileSource `source`. Throws exception if we already have - a FileSource with the same path relpath but different contents. - (ConfigSources are exempt from this requirement.) - """ - cachedSource = self.pathMap.get(self._keyOf(source)) - if not cachedSource: - self.pathMap[self._keyOf(source)] = source - else: - if source != cachedSource: - if isinstance(source, ConfigSource): - cachedSource.append(source) - else: - ui.warn("File merge mismatch %s vs %s for %s\n" % \ - (cachedSource.sourcepath, source.sourcepath, source.name())) - - def add(self, sourcepath, relpath, ui): - """Generate and add FileSource from sourceCache. Return the resulting - FileSource. - - Throws exception if we already have a FileSource with the same path - relpath but different contents. - """ - source = self.sourceCache.generateSource(sourcepath, relpath) - self.addSource(source, ui) - return source - - @staticmethod - def combine(a, b, ui): - """Merges a and b, and returns whichever one contains the merger (which - one is chosen based on merge efficiency). Can accept None as an argument. - """ - if not (a and b): - return a or b - if len(a) < len(b): - return b.merge(a, ui) - return a.merge(b, ui) - - def merge(self, other, ui): - """Merge sourceSet's contents into this SourceSet. - - Throws a RuntimeError if there's a sourceCache mismatch. - Throws an Exception if two files with the same relpath mismatch. - Returns merge result (i.e. self) - """ - if self.sourceCache is not other.sourceCache: - raise RuntimeError - - for source in other.pathMap.itervalues(): - self.addSource(source, ui) - return self - - def adjustContentPaths(self, format): - for source in self.pathMap.itervalues(): - source.adjustContentPaths(format) - - def write(self, format): - """Write files out through OutputFormat `format`. - """ - for source in self.pathMap.itervalues(): - format.write(source) - - -class StringReader(object): - """Wrapper around a string to give it a file-like api - """ - def __init__(self, string): - self.mString = string - self.mIndex = 0 - - def read(self, maxSize = None): - if (self.mIndex < len(self.mString)): - if (maxSize and (0 < maxSize)): - slice = self.mString[self.mIndex:self.mIndex + maxSize] - self.mIndex += len(slice) - return slice - else: - self.mIndex = len(self.mString) - return self.mString - return '' - - -class NamedDict(object): - def get(self, key): - if (key in self): - return self[key] - return None - - def __eq__(self, other): - for key in self.__slots__: - if (self[key] != other[key]): - return False - return True - - def __ne__(self, other): - for key in self.__slots__: - if (self[key] != other[key]): - return True - return False - - def __len__(self): - return len(self.__slots__) - - def __iter__(self): - return iter(self.__slots__) - - def __contains__(self, key): - return (key in self.__slots__) - - def copy(self): - clone = self.__class__() - for key in self.__slots__: - clone[key] = self[key] - return clone - - def keys(self): - return self.__slots__ - - def has_key(self, key): - return (key in self) - - def items(self): - return [(key, self[key]) for key in self.__slots__] - - def iteritems(self): - return iter(self.items()) - - def iterkeys(self): - return self.__iter__() - - def itervalues(self): - return iter(self.items()) - - def __str__(self): - return '{ ' + ', '.join([key + ': ' + str(self[key]) for key in self.__slots__]) + ' }' - - -class Metadata(NamedDict): - __slots__ = ('name', 'title', 'asserts', 'credits', 'reviewers', 'flags', 'links', 'references', 'revision', 'selftest', 'scripttest') - - def __init__(self, name = None, title = None, asserts = [], credits = [], reviewers = [], flags = [], links = [], - references = [], revision = None, selftest = True, scripttest = False): - self.name = name - self.title = title - self.asserts = asserts - self.credits = credits - self.reviewers = reviewers - self.flags = flags - self.links = links - self.references = references - self.revision = revision - self.selftest = selftest - self.scripttest = scripttest - - def __getitem__(self, key): - if ('name' == key): - return self.name - if ('title' == key): - return self.title - if ('asserts' == key): - return self.asserts - if ('credits' == key): - return self.credits - if ('reviewers' == key): - return self.reviewers - if ('flags' == key): - return self.flags - if ('links' == key): - return self.links - if ('references' == key): - return self.references - if ('revision' == key): - return self.revision - if ('selftest' == key): - return self.selftest - if ('scripttest' == key): - return self.scripttest - return None - - def __setitem__(self, key, value): - if ('name' == key): - self.name = value - elif ('title' == key): - self.title = value - elif ('asserts' == key): - self.asserts = value - elif ('credits' == key): - self.credits = value - elif ('reviewers' == key): - self.reviewers = value - elif ('flags' == key): - self.flags = value - elif ('links' == key): - self.links = value - elif ('references' == key): - self.references = value - elif ('revision' == key): - self.revision = value - elif ('selftest' == key): - self.selftest = value - elif ('scripttest' == key): - self.scripttest = value - else: - raise KeyError() - - -class ReferenceData(NamedDict): - __slots__ = ('name', 'type', 'relpath', 'repopath') - - def __init__(self, name = None, type = None, relpath = None, repopath = None): - self.name = name - self.type = type - self.relpath = relpath - self.repopath = repopath - - def __getitem__(self, key): - if ('name' == key): - return self.name - if ('type' == key): - return self.type - if ('relpath' == key): - return self.relpath - if ('repopath' == key): - return self.repopath - return None - - def __setitem__(self, key, value): - if ('name' == key): - self.name = value - elif ('type' == key): - self.type = value - elif ('relpath' == key): - self.relpath = value - elif ('repopath' == key): - self.repopath = value - else: - raise KeyError() - -UserData = collections.namedtuple('UserData', ('name', 'link')) - -class LineString(str): - def __new__(cls, value, line): - self = str.__new__(cls, value) - self.line = line - return self - - def lineValue(self): - return 'Line ' + str(self.line) + ': ' + str.__str__(self) if (self.line) else str.__str__(self) - - -class FileSource: - """Object representing a file. Two FileSources are equal if they represent - the same file contents. It is recommended to use a SourceCache to generate - FileSources. - """ - - def __init__(self, sourceTree, sourcepath, relpath, mimetype = None, data = None): - """Init FileSource from source path. Give it relative path relpath. - - `mimetype` should be the canonical MIME type for the file, if known. - If `mimetype` is None, guess type from file extension, defaulting to - the None key's value in extensionMap. - - `data` if provided, is a the contents of the file. Otherwise the file is read - from disk. - """ - self.sourceTree = sourceTree - self.sourcepath = sourcepath - self.relpath = relpath - self.mimetype = mimetype or getMimeFromExt(sourcepath) - self._data = data - self.errors = None - self.encoding = 'utf-8' - self.refs = {} - self.scripts = {} - self.metadata = None - self.metaSource = None - - def __eq__(self, other): - if not isinstance(other, FileSource): - return False - return self.sourcepath == other.sourcepath or \ - filecmp.cmp(self.sourcepath, other.sourcepath) - - def __ne__(self, other): - return not self == other - - def __cmp__(self, other): - return cmp(self.name(), other.name()) - - def name(self): - return self.sourceTree.getAssetName(self.sourcepath) - - def keyName(self): - if ('support' == self.type()): - return os.path.relpath(self.relpath, 'support') - return self.name() - - def type(self): - return self.sourceTree.getAssetType(self.sourcepath) - - def relativeURL(self, other): - return relativeURL(self.relpath, other.relpath) - - def data(self): - """Return file contents as a byte string.""" - if (self._data is None): - with open(self.sourcepath, 'r') as f: - self._data = f.read() - if (self._data.startswith(codecs.BOM_UTF8)): - self.encoding = 'utf-8-sig' # XXX look for other unicode BOMs - return self._data - - def unicode(self): - try: - return self.data().decode(self.encoding) - except UnicodeDecodeError: - return None - - def parse(self): - """Parses and validates FileSource data from sourcepath.""" - self.loadMetadata() - - def validate(self): - """Ensure data is loaded from sourcepath.""" - self.parse() - - def adjustContentPaths(self, format): - """Adjust any paths in file content for output format - XXX need to account for group paths""" - if (self.refs): - seenRefs = {} - seenRefs[self.sourcepath] = '==' - def adjustReferences(source): - newRefs = {} - for refName in source.refs: - refType, refPath, refNode, refSource = source.refs[refName] - if refSource: - refPath = relativeURL(format.dest(self.relpath), format.dest(refSource.relpath)) - if (refSource.sourcepath not in seenRefs): - seenRefs[refSource.sourcepath] = refType - adjustReferences(refSource) - else: - refPath = relativeURL(format.dest(self.relpath), format.dest(refPath)) - if (refPath != refNode.get('href')): - refNode.set('href', refPath) - newRefs[refName] = (refType, refPath, refNode, refSource) # update path in metadata - source.refs = newRefs - adjustReferences(self) - - if (self.scripts): # force testharness.js scripts to absolute path - for src in self.scripts: - if (src.endswith('/resources/testharness.js')): # accept relative paths to testharness.js - scriptNode = self.scripts[src] - scriptNode.set('src', '/resources/testharness.js') - elif (src.endswith('/resources/testharnessreport.js')): - scriptNode = self.scripts[src] - scriptNode.set('src', '/resources/testharnessreport.js') - - - def write(self, format): - """Writes FileSource.data() out to `self.relpath` through Format `format`.""" - data = self.data() - with open(format.dest(self.relpath), 'w') as f: - f.write(data) - if (self.metaSource): - self.metaSource.write(format) # XXX need to get output path from format, but not let it choose actual format - - def compact(self): - """Clears all cached data, preserves computed data.""" - pass - - def revision(self): - """Returns hash of the contents of this file and any related file, references, support files, etc. - XXX also needs to account for .meta file - """ - sha = hashlib.sha1() - sha.update(self.data()) - seenRefs = set(self.sourcepath) - def hashReference(source): - for refName in source.refs: - refSource = source.refs[refName][3] - if (refSource and (refSource.sourcepath not in seenRefs)): - sha.update(refSource.data()) - seenRefs.add(refSource.sourcepath) - hashReference(refSource) - hashReference(self) - return sha.hexdigest() - - def loadMetadata(self): - """Look for .meta file and load any metadata from it if present - """ - pass - - def augmentMetadata(self, next=None, prev=None, reference=None, notReference=None): - if (self.metaSource): - return self.metaSource.augmentMetadata(next, prev, reference, notReference) - return None - - # See http://wiki.csswg.org/test/css2.1/format for more info on metadata - def getMetadata(self, asUnicode = False): - """Return dictionary of test metadata. Stores list of errors - in self.errors if there are parse or metadata errors. - Data fields include: - - asserts [list of strings] - - credits [list of (name string, url string) tuples] - - reviewers [ list of (name string, url string) tuples] - - flags [list of token strings] - - links [list of url strings] - - name [string] - - title [string] - - references [list of ReferenceData per reference; None if not reftest] - - revision [revision id of last commit] - - selftest [bool] - - scripttest [bool] - Strings are given in ascii unless asUnicode==True. - """ - - self.validate() - - def encode(str): - return str if (hasattr(str, 'line')) else intern(str.encode('utf-8')) - - def escape(str, andIntern = True): - return str.encode('utf-8') if asUnicode else intern(escapeToNamedASCII(str)) if andIntern else escapeToNamedASCII(str) - - def listReferences(source, seen): - refGroups = [] - for refType, refRelPath, refNode, refSource in source.refs.values(): - if ('==' == refType): - if (refSource): - refSourcePath = refSource.sourcepath - else: - refSourcePath = os.path.normpath(join(basepath(source.sourcepath), refRelPath)) - if (refSourcePath in seen): - continue - seen.add(refSourcePath) - if (refSource): - sourceData = ReferenceData(name = self.sourceTree.getAssetName(refSourcePath), type = refType, - relpath = refRelPath, repopath = refSourcePath) - if (refSource.refs): - subRefLists = listReferences(refSource, seen.copy()) - if (subRefLists): - for subRefList in subRefLists: - refGroups.append([sourceData] + subRefList) - else: - refGroups.append([sourceData]) - else: - refGroups.append([sourceData]) - else: - sourceData = ReferenceData(name = self.sourceTree.getAssetName(refSourcePath), type = refType, - relpath = relativeURL(self.sourcepath, refSourcePath), - repopath = refSourcePath) - refGroups.append([sourceData]) - notRefs = {} - for refType, refRelPath, refNode, refSource in source.refs.values(): - if ('!=' == refType): - if (refSource): - refSourcePath = refSource.sourcepath - else: - refSourcePath = os.path.normpath(join(basepath(source.sourcepath), refRelPath)) - if (refSourcePath in seen): - continue - seen.add(refSourcePath) - if (refSource): - sourceData = ReferenceData(name = self.sourceTree.getAssetName(refSourcePath), type = refType, - relpath = refRelPath, repopath = refSourcePath) - notRefs[sourceData.name] = sourceData - if (refSource.refs): - for subRefList in listReferences(refSource, seen): - for subRefData in subRefList: - notRefs[subRefData.name] = subRefData - else: - sourceData = ReferenceData(name = self.sourceTree.getAssetName(refSourcePath), type = refType, - relpath = relativeURL(self.sourcepath, refSourcePath), - repopath = refSourcePath) - notRefs[sourceData.name] = sourceData - if (notRefs): - for refData in notRefs.values(): - refData.type = '!=' - if (refGroups): - for refGroup in refGroups: - for notRef in notRefs.values(): - for ref in refGroup: - if (ref.name == notRef.name): - break - else: - refGroup.append(notRef) - else: - refGroups.append(notRefs.values()) - return refGroups - - references = listReferences(self, set([self.sourcepath])) if (self.refs) else None - - if (self.metadata): - data = Metadata( - name = encode(self.name()), - title = escape(self.metadata['title'], False), - asserts = [escape(assertion, False) for assertion in self.metadata['asserts']], - credits = [UserData(escape(name), encode(link)) for name, link in self.metadata['credits']], - reviewers = [UserData(escape(name), encode(link)) for name, link in self.metadata['reviewers']], - flags = [encode(flag) for flag in self.metadata['flags']], - links = [encode(link) for link in self.metadata['links']], - references = references, - revision = self.revision(), - selftest = self.isSelftest(), - scripttest = self.isScripttest() - ) - return data - return None - - def addReference(self, referenceSource, match = None): - """Add reference source.""" - self.validate() - refName = referenceSource.name() - refPath = self.relativeURL(referenceSource) - if refName not in self.refs: - node = None - if match == '==': - node = self.augmentMetadata(reference=referenceSource).reference - elif match == '!=': - node = self.augmentMetadata(notReference=referenceSource).notReference - self.refs[refName] = (match, refPath, node, referenceSource) - else: - node = self.refs[refName][2] - node.set('href', refPath) - if (match): - node.set('rel', 'mismatch' if ('!=' == match) else 'match') - else: - match = self.refs[refName][0] - self.refs[refName] = (match, refPath, node, referenceSource) - - def getReferencePaths(self): - """Get list of paths to references as tuple(path, relPath, refType).""" - self.validate() - return [(os.path.join(os.path.dirname(self.sourcepath), ref[1]), - os.path.join(os.path.dirname(self.relpath), ref[1]), - ref[0]) - for ref in self.refs.values()] - - def isTest(self): - self.validate() - return bool(self.metadata) and bool(self.metadata.get('links')) - - def isReftest(self): - return self.isTest() and bool(self.refs) - - def isSelftest(self): - return self.isTest() and (not bool(self.refs)) - - def isScripttest(self): - if (self.isTest() and self.scripts): - for src in self.scripts: - if (src.endswith('/resources/testharness.js')): # accept relative paths to testharness.js - return True - return False - - def hasFlag(self, flag): - data = self.getMetadata() - if data: - return flag in data['flags'] - return False - - - -class ConfigSource(FileSource): - """Object representing a text-based configuration file. - Capable of merging multiple config-file contents. - """ - - def __init__(self, sourceTree, sourcepath, relpath, mimetype = None, data = None): - """Init ConfigSource from source path. Give it relative path relpath. - """ - FileSource.__init__(self, sourceTree, sourcepath, relpath, mimetype, data) - self.sourcepath = [sourcepath] - - def __eq__(self, other): - if not isinstance(other, ConfigSource): - return False - if self is other or self.sourcepath == other.sourcepath: - return True - if len(self.sourcepath) != len(other.sourcepath): - return False - for this, that in zip(self.sourcepath, other.sourcepath): - if not filecmp.cmp(this, that): - return False - return True - - def __ne__(self, other): - return not self == other - - def name(self): - return '.htaccess' - - def type(self): - return intern('support') - - def data(self): - """Merge contents of all config files represented by this source.""" - data = '' - for src in self.sourcepath: - with open(src) as f: - data += f.read() - data += '\n' - return data - - def getMetadata(self, asUnicode = False): - return None - - def append(self, other): - """Appends contents of ConfigSource `other` to this source. - Asserts if self.relpath != other.relpath. - """ - assert isinstance(other, ConfigSource) - assert self != other and self.relpath == other.relpath - self.sourcepath.extend(other.sourcepath) - -class ReftestFilepathError(Exception): - pass - -class ReftestManifest(ConfigSource): - """Object representing a reftest manifest file. - Iterating the ReftestManifest returns (testpath, refpath) tuples - with paths relative to the manifest. - """ - def __init__(self, sourceTree, sourcepath, relpath, data = None): - """Init ReftestManifest from source path. Give it relative path `relpath` - and load its .htaccess file. - """ - ConfigSource.__init__(self, sourceTree, sourcepath, relpath, mimetype = 'config/reftest', data = data) - - def basepath(self): - """Returns the base relpath of this reftest manifest path, i.e. - the parent of the manifest file. - """ - return basepath(self.relpath) - - baseRE = re.compile(r'^#\s*relstrip\s+(\S+)\s*') - stripRE = re.compile(r'#.*') - parseRE = re.compile(r'^\s*([=!]=)\s*(\S+)\s+(\S+)') - - def __iter__(self): - """Parse the reftest manifest files represented by this ReftestManifest - and return path information about each reftest pair as - ((test-sourcepath, ref-sourcepath), (test-relpath, ref-relpath), reftype) - Raises a ReftestFilepathError if any sources file do not exist or - if any relpaths point higher than the relpath root. - """ - striplist = [] - for src in self.sourcepath: - relbase = basepath(self.relpath) - srcbase = basepath(src) - with open(src) as f: - for line in f: - strip = self.baseRE.search(line) - if strip: - striplist.append(strip.group(1)) - line = self.stripRE.sub('', line) - m = self.parseRE.search(line) - if m: - record = ((join(srcbase, m.group(2)), join(srcbase, m.group(3))), \ - (join(relbase, m.group(2)), join(relbase, m.group(3))), \ - m.group(1)) - # for strip in striplist: - # strip relrecord - if not exists(record[0][0]): - raise ReftestFilepathError("Manifest Error in %s: " - "Reftest test file %s does not exist." \ - % (src, record[0][0])) - elif not exists(record[0][1]): - raise ReftestFilepathError("Manifest Error in %s: " - "Reftest reference file %s does not exist." \ - % (src, record[0][1])) - elif not isPathInsideBase(record[1][0]): - raise ReftestFilepathError("Manifest Error in %s: " - "Reftest test replath %s not within relpath root." \ - % (src, record[1][0])) - elif not isPathInsideBase(record[1][1]): - raise ReftestFilepathError("Manifest Error in %s: " - "Reftest test replath %s not within relpath root." \ - % (src, record[1][1])) - yield record - -import Utils # set up XML catalog -xhtmlns = '{http://www.w3.org/1999/xhtml}' -svgns = '{http://www.w3.org/2000/svg}' -xmlns = '{http://www.w3.org/XML/1998/namespace}' -xlinkns = '{http://www.w3.org/1999/xlink}' - -class XMLSource(FileSource): - """FileSource object with support reading XML trees.""" - - NodeTuple = collections.namedtuple('NodeTuple', ['next', 'prev', 'reference', 'notReference']) - - # Public Data - syntaxErrorDoc = \ - u""" - - - Syntax Error - -

The XML file contains a syntax error and could not be parsed. - Please correct it and try again.

-

The parser's error report was:

-
- - - """ - - # Private Data and Methods - __parser = etree.XMLParser(no_network=True, - # perf nightmare dtd_validation=True, - remove_comments=False, - strip_cdata=False, - resolve_entities=False) - - # Public Methods - - def __init__(self, sourceTree, sourcepath, relpath, data = None): - """Initialize XMLSource by loading from XML file `sourcepath`. - Parse errors are reported in `self.errors`, - and the source is replaced with an XHTML error message. - """ - FileSource.__init__(self, sourceTree, sourcepath, relpath, data = data) - self.tree = None - self.injectedTags = {} - - def cacheAsParseError(self, filename, e): - """Replace document with an error message.""" - errorDoc = self.syntaxErrorDoc % (filename, e) - from StringIO import StringIO - self.tree = etree.parse(StringIO(errorDoc), parser=self.__parser) - - def parse(self): - """Parse file and store any parse errors in self.errors""" - self.errors = None - try: - data = self.data() - if (data): - self.tree = etree.parse(StringReader(data), parser=self.__parser) - self.encoding = self.tree.docinfo.encoding or 'utf-8' - self.injectedTags = {} - else: - self.tree = None - self.errors = ['Empty source file'] - self.encoding = 'utf-8' - - FileSource.loadMetadata(self) - if ((not self.metadata) and self.tree and (not self.errors)): - self.extractMetadata(self.tree) - except etree.ParseError as e: - print("PARSE ERROR: " + self.sourcepath) - self.cacheAsParseError(self.sourcepath, e) - e.W3CTestLibErrorLocation = self.sourcepath - self.errors = [str(e)] - self.encoding = 'utf-8' - - def validate(self): - """Parse file if not parsed, and store any parse errors in self.errors""" - if self.tree is None: - self.parse() - - def getMeatdataContainer(self): - return self.tree.getroot().find(xhtmlns+'head') - - def injectMetadataLink(self, rel, href, tagCode = None): - """Inject (prepend) with data given inside metadata container. - Injected element is tagged with `tagCode`, which can be - used to clear it with clearInjectedTags later. - """ - self.validate() - container = self.getMeatdataContainer() - if (container): - node = etree.Element(xhtmlns+'link', {'rel': rel, 'href': href}) - node.tail = container.text - container.insert(0, node) - self.injectedTags[node] = tagCode or True - return node - return None - - def clearInjectedTags(self, tagCode = None): - """Clears all injected elements from the tree, or clears injected - elements tagged with `tagCode` if `tagCode` is given. - """ - if not self.injectedTags or not self.tree: return - for node in self.injectedTags: - node.getparent().remove(node) - del self.injectedTags[node] - - def serializeXML(self): - self.validate() - return etree.tounicode(self.tree) - - def data(self): - if ((not self.tree) or (self.metaSource)): - return FileSource.data(self) - return self.serializeXML().encode(self.encoding, 'xmlcharrefreplace') - - def unicode(self): - if ((not self.tree) or (self.metaSource)): - return FileSource.unicode(self) - return self.serializeXML() - - def write(self, format, output=None): - """Write Source through OutputFormat `format`. - Write contents as string `output` instead if specified. - """ - if not output: - output = self.unicode() - - # write - with open(format.dest(self.relpath), 'w') as f: - f.write(output.encode(self.encoding, 'xmlcharrefreplace')) - - def compact(self): - self.tree = None - - def getMetadataElements(self, tree): - container = self.getMeatdataContainer() - if (None != container): - return [node for node in container] - return None - - def extractMetadata(self, tree): - """Extract metadata from tree.""" - links = []; credits = []; reviewers = []; flags = []; asserts = []; title = '' - - def tokenMatch(token, string): - return bool(re.search('(^|\s+)%s($|\s+)' % token, string)) if (string) else False - - errors = [] - readFlags = False - metaElements = self.getMetadataElements(tree) - if (not metaElements): - errors.append("Missing element") - else: - # Scan and cache metadata - for node in metaElements: - if (node.tag == xhtmlns+'link'): - # help links - if tokenMatch('help', node.get('rel')): - link = node.get('href').strip() if node.get('href') else None - if (not link): - errors.append(LineString("Help link missing href value.", node.sourceline)) - elif (not (link.startswith('http://') or link.startswith('https://'))): - errors.append(LineString("Help link " + link.encode('utf-8') + " must be absolute URL.", node.sourceline)) - elif (link in links): - errors.append(LineString("Duplicate help link " + link.encode('utf-8') + ".", node.sourceline)) - else: - links.append(LineString(link, node.sourceline)) - # == references - elif tokenMatch('match', node.get('rel')) or tokenMatch('reference', node.get('rel')): - refPath = node.get('href').strip() if node.get('href') else None - if (not refPath): - errors.append(LineString("Reference link missing href value.", node.sourceline)) - else: - refName = self.sourceTree.getAssetName(join(self.sourcepath, refPath)) - if (refName in self.refs): - errors.append(LineString("Reference " + refName.encode('utf-8') + " already specified.", node.sourceline)) - else: - self.refs[refName] = ('==', refPath, node, None) - # != references - elif tokenMatch('mismatch', node.get('rel')) or tokenMatch('not-reference', node.get('rel')): - refPath = node.get('href').strip() if node.get('href') else None - if (not refPath): - errors.append(LineString("Reference link missing href value.", node.sourceline)) - else: - refName = self.sourceTree.getAssetName(join(self.sourcepath, refPath)) - if (refName in self.refs): - errors.append(LineString("Reference " + refName.encode('utf-8') + " already specified.", node.sourceline)) - else: - self.refs[refName] = ('!=', refPath, node, None) - else: # may have both author and reviewer in the same link - # credits - if tokenMatch('author', node.get('rel')): - name = node.get('title') - name = name.strip() if name else name - if (not name): - errors.append(LineString("Author link missing name (title attribute).", node.sourceline)) - else: - link = node.get('href').strip() if node.get('href') else None - if (not link): - errors.append(LineString("Author link for \"" + name.encode('utf-8') + "\" missing contact URL (http or mailto).", node.sourceline)) - else: - credits.append((name, link)) - # reviewers - if tokenMatch('reviewer', node.get('rel')): - name = node.get('title') - name = name.strip() if name else name - if (not name): - errors.append(LineString("Reviewer link missing name (title attribute).", node.sourceline)) - else: - link = node.get('href').strip() if node.get('href') else None - if (not link): - errors.append(LineString("Reviewer link for \"" + name.encode('utf-8') + "\" missing contact URL (http or mailto).", node.sourceline)) - else: - reviewers.append((name, link)) - elif (node.tag == xhtmlns+'meta'): - metatype = node.get('name') - metatype = metatype.strip() if metatype else metatype - # requirement flags - if ('flags' == metatype): - if (readFlags): - errors.append(LineString("Flags must only be specified once.", node.sourceline)) - else: - readFlags = True - if (None == node.get('content')): - errors.append(LineString("Flags meta missing content attribute.", node.sourceline)) - else: - for flag in sorted(node.get('content').split()): - flags.append(flag) - # test assertions - elif ('assert' == metatype): - if (None == node.get('content')): - errors.append(LineString("Assert meta missing content attribute.", node.sourceline)) - else: - asserts.append(node.get('content').strip().replace('\t', ' ')) - # title - elif (node.tag == xhtmlns+'title'): - title = node.text.strip() if node.text else '' - match = re.match('(?:[^:]*)[tT]est(?:[^:]*):(.*)', title, re.DOTALL) - if (match): - title = match.group(1) - title = title.strip() - # script - elif (node.tag == xhtmlns+'script'): - src = node.get('src').strip() if node.get('src') else None - if (src): - self.scripts[src] = node - - if (asserts or credits or reviewers or flags or links or title): - self.metadata = {'asserts' : asserts, - 'credits' : credits, - 'reviewers' : reviewers, - 'flags' : flags, - 'links' : links, - 'title' : title - } - - if (errors): - if (self.errors): - self.errors += errors - else: - self.errors = errors - - - def augmentMetadata(self, next=None, prev=None, reference=None, notReference=None): - """Add extra useful metadata to the head. All arguments are optional. - * Adds next/prev links to next/prev Sources given - * Adds reference link to reference Source given - """ - self.validate() - if next: - next = self.injectMetadataLink('next', self.relativeURL(next), 'next') - if prev: - prev = self.injectMetadataLink('prev', self.relativeURL(prev), 'prev') - if reference: - reference = self.injectMetadataLink('match', self.relativeURL(reference), 'ref') - if notReference: - notReference = self.injectMetadataLink('mismatch', self.relativeURL(notReference), 'not-ref') - return self.NodeTuple(next, prev, reference, notReference) - - -class XHTMLSource(XMLSource): - """FileSource object with support for XHTML->HTML conversions.""" - - # Public Methods - - def __init__(self, sourceTree, sourcepath, relpath, data = None): - """Initialize XHTMLSource by loading from XHTML file `sourcepath`. - Parse errors are stored in `self.errors`, - and the source is replaced with an XHTML error message. - """ - XMLSource.__init__(self, sourceTree, sourcepath, relpath, data = data) - - def serializeXHTML(self, doctype = None): - return self.serializeXML() - - def serializeHTML(self, doctype = None): - self.validate() - # Serialize -# print self.relpath - serializer = HTMLSerializer.HTMLSerializer() - output = serializer.serializeHTML(self.tree, doctype) - return output - - -class SVGSource(XMLSource): - """FileSource object with support for extracting metadata from SVG.""" - - def __init__(self, sourceTree, sourcepath, relpath, data = None): - """Initialize SVGSource by loading from SVG file `sourcepath`. - Parse errors are stored in `self.errors`, - and the source is replaced with an XHTML error message. - """ - XMLSource.__init__(self, sourceTree, sourcepath, relpath, data = data) - - def getMeatdataContainer(self): - groups = self.tree.getroot().findall(svgns+'g') - for group in groups: - if ('testmeta' == group.get('id')): - return group - return None - - def extractMetadata(self, tree): - """Extract metadata from tree.""" - links = []; credits = []; reviewers = []; flags = []; asserts = []; title = '' - - def tokenMatch(token, string): - return bool(re.search('(^|\s+)%s($|\s+)' % token, string)) if (string) else False - - errors = [] - readFlags = False - metaElements = self.getMetadataElements(tree) - if (not metaElements): - errors.append("Missing element") - else: - # Scan and cache metadata - for node in metaElements: - if (node.tag == xhtmlns+'link'): - # help links - if tokenMatch('help', node.get('rel')): - link = node.get('href').strip() if node.get('href') else None - if (not link): - errors.append(LineString("Help link missing href value.", node.sourceline)) - elif (not (link.startswith('http://') or link.startswith('https://'))): - errors.append(LineString("Help link " + link.encode('utf-8') + " must be absolute URL.", node.sourceline)) - elif (link in links): - errors.append(LineString("Duplicate help link " + link.encode('utf-8') + ".", node.sourceline)) - else: - links.append(LineString(link, node.sourceline)) - # == references - elif tokenMatch('match', node.get('rel')) or tokenMatch('reference', node.get('rel')): - refPath = node.get('href').strip() if node.get('href') else None - if (not refPath): - errors.append(LineString("Reference link missing href value.", node.sourceline)) - else: - refName = self.sourceTree.getAssetName(join(self.sourcepath, refPath)) - if (refName in self.refs): - errors.append(LineString("Reference " + refName.encode('utf-8') + " already specified.", node.sourceline)) - else: - self.refs[refName] = ('==', refPath, node, None) - # != references - elif tokenMatch('mismatch', node.get('rel')) or tokenMatch('not-reference', node.get('rel')): - refPath = node.get('href').strip() if node.get('href') else None - if (not refPath): - errors.append(LineString("Reference link missing href value.", node.sourceline)) - else: - refName = self.sourceTree.getAssetName(join(self.sourcepath, refPath)) - if (refName in self.refs): - errors.append(LineString("Reference " + refName.encode('utf-8') + " already specified.", node.sourceline)) - else: - self.refs[refName] = ('!=', refPath, node, None) - else: # may have both author and reviewer in the same link - # credits - if tokenMatch('author', node.get('rel')): - name = node.get('title') - name = name.strip() if name else name - if (not name): - errors.append(LineString("Author link missing name (title attribute).", node.sourceline)) - else: - link = node.get('href').strip() if node.get('href') else None - if (not link): - errors.append(LineString("Author link for \"" + name.encode('utf-8') + "\" missing contact URL (http or mailto).", node.sourceline)) - else: - credits.append((name, link)) - # reviewers - if tokenMatch('reviewer', node.get('rel')): - name = node.get('title') - name = name.strip() if name else name - if (not name): - errors.append(LineString("Reviewer link missing name (title attribute).", node.sourceline)) - else: - link = node.get('href').strip() if node.get('href') else None - if (not link): - errors.append(LineString("Reviewer link for \"" + name.encode('utf-8') + "\" missing contact URL (http or mailto).", node.sourceline)) - else: - reviewers.append((name, link)) - elif (node.tag == svgns+'metadata'): - metatype = node.get('class') - metatype = metatype.strip() if metatype else metatype - # requirement flags - if ('flags' == metatype): - if (readFlags): - errors.append(LineString("Flags must only be specified once.", node.sourceline)) - else: - readFlags = True - text = node.find(svgns+'text') - flagString = text.text if (text) else node.text - if (flagString): - for flag in sorted(flagString.split()): - flags.append(flag) - elif (node.tag == svgns+'desc'): - metatype = node.get('class') - metatype = metatype.strip() if metatype else metatype - # test assertions - if ('assert' == metatype): - asserts.append(node.text.strip().replace('\t', ' ')) - # test title - elif node.tag == svgns+'title': - title = node.text.strip() if node.text else '' - match = re.match('(?:[^:]*)[tT]est(?:[^:]*):(.*)', title, re.DOTALL) - if (match): - title = match.group(1) - title = title.strip() - # script tag (XXX restricted to metadata container?) - elif (node.tag == svgns+'script'): - src = node.get('src').strip() if node.get('src') else None - if (src): - self.scripts[src] = node - - if (asserts or credits or reviewers or flags or links or title): - self.metadata = {'asserts' : asserts, - 'credits' : credits, - 'reviewers' : reviewers, - 'flags' : flags, - 'links' : links, - 'title' : title - } - if (errors): - if (self.errors): - self.errors += errors - else: - self.errors = errors - - - -class HTMLSource(XMLSource): - """FileSource object with support for HTML metadata and HTML->XHTML conversions (untested).""" - - # Private Data and Methods - __parser = html5lib.HTMLParser(tree = treebuilders.getTreeBuilder('lxml')) - - # Public Methods - - def __init__(self, sourceTree, sourcepath, relpath, data = None): - """Initialize HTMLSource by loading from HTML file `sourcepath`. - """ - XMLSource.__init__(self, sourceTree, sourcepath, relpath, data = data) - - def parse(self): - """Parse file and store any parse errors in self.errors""" - self.errors = None - try: - data = self.data() - if data: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - self.tree = self.__parser.parse(data) - self.encoding = self.__parser.documentEncoding - self.injectedTags = {} - else: - self.tree = None - self.errors = ['Empty source file'] - self.encoding = 'utf-8' - - FileSource.loadMetadata(self) - if ((not self.metadata) and self.tree and (not self.errors)): - self.extractMetadata(self.tree) - except Exception as e: - print("PARSE ERROR: " + self.sourcepath) - e.W3CTestLibErrorLocation = self.sourcepath - self.errors = [str(e)] - self.encoding = 'utf-8' - - def _injectXLinks(self, element, nodeList): - injected = False - - xlinkAttrs = ['href', 'type', 'role', 'arcrole', 'title', 'show', 'actuate'] - if (element.get('href') or element.get(xlinkns + 'href')): - for attr in xlinkAttrs: - if (element.get(xlinkns + attr)): - injected = True - if (element.get(attr)): - injected = True - value = element.get(attr) - del element.attrib[attr] - element.set(xlinkns + attr, value) - nodeList.append((element, xlinkns + attr, attr)) - - for child in element: - if (type(child.tag) == type('')): # element node - qName = etree.QName(child.tag) - if ('foreignobject' != qName.localname.lower()): - injected |= self._injectXLinks(child, nodeList) - return injected - - - def _findElements(self, namespace, elementName): - elements = self.tree.findall('.//{' + namespace + '}' + elementName) - if (self.tree.getroot().tag == '{' + namespace + '}' + elementName): - elements.insert(0, self.tree.getroot()) - return elements - - def _injectNamespace(self, elementName, prefix, namespace, doXLinks, nodeList): - attr = xmlns + prefix if (prefix) else 'xmlns' - elements = self._findElements(namespace, elementName) - for element in elements: - if not element.get(attr): - element.set(attr, namespace) - nodeList.append((element, attr, None)) - if (doXLinks): - if (self._injectXLinks(element, nodeList)): - element.set(xmlns + 'xlink', 'http://www.w3.org/1999/xlink') - nodeList.append((element, xmlns + 'xlink', None)) - - def injectNamespaces(self): - nodeList = [] - self._injectNamespace('html', None, 'http://www.w3.org/1999/xhtml', False, nodeList) - self._injectNamespace('svg', None, 'http://www.w3.org/2000/svg', True, nodeList) - self._injectNamespace('math', None, 'http://www.w3.org/1998/Math/MathML', True, nodeList) - return nodeList - - def removeNamespaces(self, nodeList): - if nodeList: - for element, attr, oldAttr in nodeList: - if (oldAttr): - value = element.get(attr) - del element.attrib[attr] - element.set(oldAttr, value) - else: - del element.attrib[attr] - - def serializeXHTML(self, doctype = None): - self.validate() - # Serialize - nodeList = self.injectNamespaces() -# print self.relpath - serializer = HTMLSerializer.HTMLSerializer() - o = serializer.serializeXHTML(self.tree, doctype) - - self.removeNamespaces(nodeList) - return o - - def serializeHTML(self, doctype = None): - self.validate() - # Serialize -# print self.relpath - serializer = HTMLSerializer.HTMLSerializer() - o = serializer.serializeHTML(self.tree, doctype) - - return o - - def data(self): - if ((not self.tree) or (self.metaSource)): - return FileSource.data(self) - return self.serializeHTML().encode(self.encoding, 'xmlcharrefreplace') - - def unicode(self): - if ((not self.tree) or (self.metaSource)): - return FileSource.unicode(self) - return self.serializeHTML() - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Suite.py b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Suite.py deleted file mode 100644 index c5fa03a155f..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Suite.py +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/python -# CSS Test Suite Manipulation Library -# Initial code by fantasai, joint copyright 2010 W3C and Microsoft -# Licensed under BSD 3-Clause: - -import OutputFormats -import Utils -from Groups import TestGroup, excludeDirs -from Sources import SourceTree, SourceCache -from shutil import copytree, rmtree -from os.path import join -import os -from mercurial import ui as UserInterface, hg - -class TestSuite: - """Representation of a standard CSS test suite.""" - - def __init__(self, name, title, specUri, draftUri, sourceCache = None, ui = None): - self.name = name - self.title = title - self.specroot = specUri - self.draftroot = draftUri - - self.ui = ui if ui else UserInterface.ui() - self.defaultReftestRelpath='reftest.list' - self.groups = {} - self.sourcecache = sourceCache if sourceCache else SourceCache(SourceTree(hg.repository(self.ui, '.'))) - self.formats = ('html4', 'xhtml1', 'xhtml1print') # XXX FIXME, hardcoded list is lame - self.rawgroups = {} - - def addTestsByExt(self, dir, ext, groupName='', groupTitle=''): - """Add tests from directory `dir` by file extension (via `ext`, e.g. ext='.xht'). - """ - group = TestGroup(self.sourcecache, dir, selfTestExt=ext, - name=groupName, title=groupTitle, ui = self.ui) - self.addGroup(group) - - - def addTestsByList(self, dir, filenames, groupName='', groupTitle=''): - """Add tests from directory `dir`, via file name list `filenames`. - """ - group = TestGroup(self.sourcecache, dir, selfTestList=filenames, - name=groupName, title=groupTitle, ui = self.ui) - self.addGroup(group) - - def addReftests(self, dir, manifestPath, groupName='', groupTitle=''): - """Add tests by importing context of directory `dir` and importing all - tests listed in the `reftestManifestName` manifest inside `dir`. - """ - group = TestGroup(self.sourcecache, - dir, manifestPath=manifestPath, - manifestDest=self.defaultReftestRelpath, - name=groupName, title=groupTitle, ui = self.ui) - self.addGroup(group) - - def addGroup(self, group): - """ Add CSSTestGroup `group` to store. """ - master = self.groups.get(group.name) - if master: - master.merge(group) - else: - self.groups[group.name] = group - - def addRaw(self, dir, relpath): - """Add the contents of directory `dir` to the test suite by copying - (not processing). Note this means such tests will not be indexed. - `relpath` gives the directory's path within the build destination. - """ - self.rawgroups[dir] = relpath - - def setFormats(self, formats): - self.formats = formats - - def buildInto(self, dest, indexer): - """Builds test suite through all OutputFormats into directory at path `dest` - or through OutputFormat destination `dest`, using Indexer `indexer`. - """ - if isinstance(dest, OutputFormats.BasicFormat): - formats = (dest,) - dest = dest.root - else: - formats = [] - for format in self.formats: - if (format == 'html4'): - formats.append(OutputFormats.HTMLFormat(dest, self.sourcecache.sourceTree)) - elif (format == 'html5'): - formats.append(OutputFormats.HTML5Format(dest, self.sourcecache.sourceTree)) - elif (format == 'xhtml1'): - formats.append(OutputFormats.XHTMLFormat(dest, self.sourcecache.sourceTree)) - elif (format == 'xhtml1print'): - formats.append(OutputFormats.XHTMLPrintFormat(dest, self.sourcecache.sourceTree, self.title)) - elif (format == 'svg'): - formats.append(OutputFormats.SVGFormat(dest, self.sourcecache.sourceTree)) - - for format in formats: - for group in self.groups.itervalues(): - group.build(format) - - for group in self.groups.itervalues(): - indexer.indexGroup(group) - - for format in formats: - indexer.writeIndex(format) - - - rawtests = [] - for src, relpath in self.rawgroups.items(): - copytree(src, join(dest,relpath)) - for (root, dirs, files) in os.walk(join(dest,relpath)): - for xdir in excludeDirs: - if xdir in dirs: - dirs.remove(xdir) - rmtree(join(root,xdir)) - rawtests.extend( - [join(Utils.relpath(root,dest),file) - for file in files] - ) - - rawtests.sort() - indexer.writeOverview(dest, addTests=rawtests) - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Utils.py b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Utils.py deleted file mode 100644 index 065c30491c7..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/Utils.py +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/python -# CSS Test Suite Manipulation Library Utilities -# Initial code by fantasai, joint copyright 2010 W3C and Microsoft -# Licensed under BSD 3-Clause: - -###### XML Parsing ###### - -import os -import w3ctestlib -os.environ['XML_CATALOG_FILES'] = os.path.join(w3ctestlib.__path__[0], 'catalog/catalog.xml') - -###### File path manipulation ###### - -import os.path -from os.path import sep, pardir - -def assetName(path): - return intern(os.path.splitext(os.path.basename(path))[0].lower().encode('ascii')) - -def basepath(path): - """ Returns the path part of os.path.split. - """ - return os.path.dirname(path) - -def isPathInsideBase(path, base=''): - path = os.path.normpath(path) - if base: - base = os.path.normpath(base) - pathlist = path.split(os.path.sep) - baselist = base.split(os.path.sep) - while baselist: - p = pathlist.pop(0) - b = baselist.pop(0) - if p != b: - return False - return not pathlist[0].startswith(os.path.pardir) - return not path.startswith(os.path.pardir) - -def relpath(path, start): - """Return relative path from start to end. WARNING: this is not the - same as a relative URL; see relativeURL().""" - try: - return os.path.relpath(path, start) - except AttributeError: - # This function is copied directly from the Python 2.6 source - # code, and is therefore under a different license. - - if not path: - raise ValueError("no path specified") - start_list = os.path.abspath(start).split(sep) - path_list = os.path.abspath(path).split(sep) - if start_list[0].lower() != path_list[0].lower(): - unc_path, rest = os.path.splitunc(path) - unc_start, rest = os.path.splitunc(start) - if bool(unc_path) ^ bool(unc_start): - raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)" - % (path, start)) - else: - raise ValueError("path is on drive %s, start on drive %s" - % (path_list[0], start_list[0])) - # Work out how much of the filepath is shared by start and path. - for i in range(min(len(start_list), len(path_list))): - if start_list[i].lower() != path_list[i].lower(): - break - else: - i += 1 - - rel_list = [pardir] * (len(start_list)-i) + path_list[i:] - if not rel_list: - return os.path.curdir - return os.path.join(*rel_list) - -def relativeURL(start, end): - """ Returns relative URL from `start` to `end`. - """ -# if isPathInsideBase(end, start): -# return relpath(end, start) -# else: - return relpath(end, basepath(start)) - -def listfiles(path, ext = None): - """ Returns a list of all files in a directory. - Optionally lists only files with a given extension. - """ - try: - _,_,files = os.walk(path).next() - if (ext): - files = [fileName for fileName in files if fileName.endswith(ext)] - except StopIteration: - files = [] - return files - -def listdirs(path): - """ Returns a list of all subdirectories in a directory. - """ - try: - _,dirs,_ = os.walk(path).next() - except StopIteration: - dirs = [] - return dirs - -###### MIME types and file extensions ###### - -extensionMap = { None : 'application/octet-stream', # default - '.xht' : 'application/xhtml+xml', - '.xhtml' : 'application/xhtml+xml', - '.xml' : 'application/xml', - '.htm' : 'text/html', - '.html' : 'text/html', - '.txt' : 'text/plain', - '.jpg' : 'image/jpeg', - '.png' : 'image/png', - '.svg' : 'image/svg+xml', - } - -def getMimeFromExt(filepath): - """Convenience function: equal to extenionMap.get(ext, extensionMap[None]). - """ - if filepath.endswith('.htaccess'): - return 'config/htaccess' - ext = os.path.splitext(filepath)[1] - return extensionMap.get(ext, extensionMap[None]) - -###### Escaping ###### - -import types -from htmlentitydefs import entitydefs - -entityify = dict([c,e] for e,c in entitydefs.iteritems()) - -def escapeMarkup(data): - """Escape markup characters (&, >, <). Copied from xml.sax.saxutils. - """ - # must do ampersand first - data = data.replace("&", "&") - data = data.replace(">", ">") - data = data.replace("<", "<") - return data - -def escapeToNamedASCII(text): - """Escapes to named entities where possible and numeric-escapes non-ASCII - """ - return escapeToNamed(text).encode('ascii', 'xmlcharrefreplace') - -def escapeToNamed(text): - """Escape characters with named entities. - """ - escapable = set() - - for c in text: - if ord(c) > 127: - escapable.add(c) - if type(text) == types.UnicodeType: - for c in escapable: - cLatin = c.encode('Latin-1', 'ignore') - if (cLatin in entityify): - text = text.replace(c, "&%s;" % entityify[cLatin]) - else: - for c in escapable: - text = text.replace(c, "&%s;" % entityify[c]) - return text diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/__init__.py b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/__init__.py deleted file mode 100644 index 8ce9f985c30..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ - - -__all__ = ['Sources', 'Groups', 'Indexer', 'Suite', 'OutputFormats', 'HTMLSerializer'] \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/catalog.xml b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/catalog.xml deleted file mode 100644 index d9c5926235d..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/catalog.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-lat1.ent b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-lat1.ent deleted file mode 100644 index ffee223eb10..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-lat1.ent +++ /dev/null @@ -1,196 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-special.ent b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-special.ent deleted file mode 100644 index ca358b2fec7..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-special.ent +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-symbol.ent b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-symbol.ent deleted file mode 100644 index 63c2abfa6f4..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml-symbol.ent +++ /dev/null @@ -1,237 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-frameset.dtd b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-frameset.dtd deleted file mode 100644 index d128f2eb7c0..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-frameset.dtd +++ /dev/null @@ -1,1235 +0,0 @@ - - - - - -%HTMLlat1; - - -%HTMLsymbol; - - -%HTMLspecial; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-strict.dtd b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-strict.dtd deleted file mode 100644 index 2927b9ece7f..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-strict.dtd +++ /dev/null @@ -1,978 +0,0 @@ - - - - - -%HTMLlat1; - - -%HTMLsymbol; - - -%HTMLspecial; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-transitional.dtd b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-transitional.dtd deleted file mode 100644 index 628f27ac500..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml1-transitional.dtd +++ /dev/null @@ -1,1201 +0,0 @@ - - - - - -%HTMLlat1; - - -%HTMLsymbol; - - -%HTMLspecial; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml11.dtd b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml11.dtd deleted file mode 100644 index 2a999b5b37d..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/catalog/xhtml11.dtd +++ /dev/null @@ -1,294 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -]]> - - - - - - -%xhtml-inlstyle.mod;]]> - - - - - - - -%xhtml-framework.mod;]]> - - - - -]]> - - - - -%xhtml-text.mod;]]> - - - - -%xhtml-hypertext.mod;]]> - - - - -%xhtml-list.mod;]]> - - - - - - -%xhtml-edit.mod;]]> - - - - -%xhtml-bdo.mod;]]> - - - - - - -%xhtml-ruby.mod;]]> - - - - -%xhtml-pres.mod;]]> - - - - -%xhtml-link.mod;]]> - - - - -%xhtml-meta.mod;]]> - - - - -%xhtml-base.mod;]]> - - - - -%xhtml-script.mod;]]> - - - - -%xhtml-style.mod;]]> - - - - -%xhtml-image.mod;]]> - - - - -%xhtml-csismap.mod;]]> - - - - -%xhtml-ssismap.mod;]]> - - - - -%xhtml-param.mod;]]> - - - - -%xhtml-object.mod;]]> - - - - -%xhtml-table.mod;]]> - - - - -%xhtml-form.mod;]]> - - - - -%xhtml-legacy.mod;]]> - - - - -%xhtml-struct.mod;]]> - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/chapter-toc.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/chapter-toc.tmpl deleted file mode 100644 index e1e8bc275d9..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/chapter-toc.tmpl +++ /dev/null @@ -1,46 +0,0 @@ -[%# variables in this template - indexext [string, e.g. '.html'] - suitetitle [string] - specroot [uri string] - formatdir [dir name string] - chapters [list of struct] - .numstr [string, e.g. '6.1.13'] - .title [string] - .testcount [number] -%] -[% IF isXML %] - - -[% ELSE %] - - -[% END %] - - [% suitetitle %] - - - -

[% suitetitle %] By Chapter

- -

This index contains both - self-describing tests - and reftests. - A separate alphabetical reftest index - is provided for tests in reftest - format along with the reftest manifest.

- - -[% FOREACH chapter IN chapters %] - - - - -[% END %] -
- [% (chapter.numstr.match('^\d')) ? 'Chapter' : 'Appendix' +%] [%+ chapter.numstr +%] - - [%+ chapter.title +%]([% chapter.testcount +%] Tests)
- - \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/implementation-report-TEMPLATE.data.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/implementation-report-TEMPLATE.data.tmpl deleted file mode 100644 index 0231f23ba4c..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/implementation-report-TEMPLATE.data.tmpl +++ /dev/null @@ -1,21 +0,0 @@ -# UA version OS version -# UA string (if applicable) -# http://test.csswg.org/suites/[% suite %]/DATESTAMP/ -# See http://wiki.csswg.org/test/implementation-report for instructions -testname revision result comment -[% FOREACH test IN tests.sort(name) %] -[% FOREACH format IN formats %] -[% IF formatInfo.$format.report %] -[% SET skipFormat = 0 %] -[% FOREACH flag IN test.flags %] - [% SET skipFormat = 1 IF flag == formatInfo.$format.filter %] -[% END %] -[% UNLESS skipFormat +%] -[%+ formatInfo.$format.path +%]/[% test.name +%].[% formatInfo.$format.ext +%] [%+ test.revision +%] ? -[% END %] -[% END %] -[% END %] -[% END %] -[% FOREACH test IN addtests.sort() +%] -[%+ test +%] [%+ test.revision +%] ? -[% END %] diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.content.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.content.tmpl deleted file mode 100644 index e32d8fe5672..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.content.tmpl +++ /dev/null @@ -1,195 +0,0 @@ -[% PROCESS "suitedata.tmpl" %] -[% IF official %] -

[% suites.$suite.title %]

-[% ELSE %] -

Unofficial [% suites.$suite.title %]

-[% END %] -
Test Coordinator:
-
[% suites.$suite.owner %]
- -

This is a [% statusNames.${suites.$suite.status}.title or "ERROR: $suite" %] - version of the [% suites.$suite.title %].

- -[% IF suites.$suite.harness != '' %] -

You can provide test data or review the testing results for this test suite:

-
Enter Data
-
Review Results
-[% END %] - - -[% IF devel %] -

This build exists to aid in test suite development and contains unreviewed - tests. The pass/fail results of these tests are not reliable - indications of conformance. -[% ELSE %] -

Some tests in the test suite may contain errors. -[% END %] - Please check the latest version of the - [% suites.$suite.spec %] specification - and its errata - before assuming a failure is due to an implementation bug and - not a test suite bug.

- -[% UNLESS official %] -

You can find the official - build of the [% suites.$suite.title %] on W3C's web site.

-[% END %] - -

[% IF suites.$suite.status != 'fin' && suites.$suite.status != 'rc' %] - In time we hope to correct all errors and extend this test suite to - cover all of [% suites.$suite.spec %]. Your help is welcome in this effort. - [% END %] - The appropriate mailing list for submitting tests and bug reports is - public-css-testsuite@w3.org.

-

- To report bugs or feedback about a specific test file, - search for the filename (without extension) in - web-platform-tests issues, - and file a new issue if necessary with suggested label "wg-css". - More information on the contribution process and test guidelines is - available on the wiki - page.

- -

Tests are currently available in these formats:

- -
-[% FOREACH format IN formats %] - [% IF format == 'html4' %] -
HTML 4.01
-
HTML 4.01 tests sent as text/html
- [% END %] - [% IF format == 'html5' %] -
HTML 5
-
HTML 5 tests sent as text/html
- [% END %] - [% IF format == 'xhtml1' %] -
XHTML 1.1
-
XHTML 1.1 tests sent as application/xhtml+xml
- [% END %] - [% IF format == 'xhtml1print' %] -
XHTML 1.1 for Printers
-
XHTML 1.1 tests with all images converted from PNG to JPEG - and formatted with headers and footers to ease testing of - embedded printer software. This is not a canonical format, - and some tests may fail due to the format conversion that - would otherwise pass in the above XHTML 1.1 format.
-
- [% END %] -[% END %] - -[% IF suite == 'css2.1' %] -

Additional tests, that do not fit in any of those formats, - are located separately:

- -
-
Other Formats
-
Tests that do not fit in the above formats because they - test a combination of CSS and a particular document language's - features and/or error recovery.
-
-[% END %] - -

Unless the test instructions explicitly indicate otherwise, - any occurrence of red in a test indicates test failure.

- -[% IF suite == 'css2.1' %] -

Note that many of the tests require the - Ahem font to be installed. - These tests are marked with the 'ahem' flag in their metadata. - Without the Ahem font installed, these tests are of no value.

-

Some of the font-related tests also require - special fonts. - These tests are marked with the 'font' flag in their metadata.

- -[% END %] -

Implementation Reports

-

An implementation report template - is available to help with creating implementation reports. See also the - explanation - of its format.

- -

Common Assumptions

- -

Most of the test suite makes the following assumptions:

-
    -
  • The X/HTML div element is assigned display: block; - and no other property declaration.
  • -
  • The X/HTML span element is assigned display: inline; - and no other property declaration.
  • -
  • The X/HTML p element is assigned display: block;
  • -
  • The X/HTML li element is assigned display: list-item;
  • -
  • The X/HTML table elements table, tbody, - tr, and td are assigned the display - values table, table-row-group, - table-row, and table-cell, respectively.
  • -
  • The device can display the sixteen color values associated with the color - keywords black, white, gray, - silver, red, green, blue, - purple, yellow, orange, teal, - fuchsia, maroon, navy, aqua, - and lime as distinct colors.
  • -
  • The UA is set to print background colors and, if it supports graphics, - background images.
  • -
  • The UA implements reasonable page-breaking behavior; e.g., it is assumed - that UAs will not break at every opportunity, but only near the end of - a page unless a page break is forced.
  • -
  • The UA implements reasonable line-breaking behavior; e.g., it is assumed - that spaces between alphanumeric characters provide line breaking - opportunities and that UAs will not break at every opportunity, but only - near the end of a line unless a line break is forced.
  • -
- -

Uncommon Assumptions

- -

In addition, some of the tests make one or more of the following - assumptions:

- -
    -
  • The device is a full-color device.
  • -
  • The device has a viewport width of at least 640px (approx).
  • -
  • The resolution of the device is 96 CSS pixels per inch.
  • -
  • The UA imposes no minimum font size.
  • -
  • The 'medium' font-size computes to 16px.
  • -
  • The initial value of 'color' is black.
  • -
  • The canvas background is white.
  • -
  • The user stylesheet is empty (except where indicated by the tests).
  • -
  • The device is interactive and uses scroll bars.
  • -
- -

The tests that need these assumptions to be true have not yet been - marked, but it is likely that we will add a way to identify these - tests in due course. Tests should avoid relying on these assumptions - unless necessary.

- -

License

- -[% IF official %] -

This test suite is licensed under both the - W3C - Test Suite License and the W3C - 3-clause BSD License. See W3C Legal's explanation - of the licenses.

-[% ELSE %] -

These tests are licensed under the BSD 3-clause - License. You may modify and distribute them under those terms. Aside - from their titles, documentation, and location they are identical to the - official tests of the same date. However, only the - official % suites.$suite.title %] - may be used as the basis for CSS conformance - claims.

-[% END %] - -

Acknowledgements

- -

Many thanks to the following for their contributions:

-
    -[%- FOREACH person = contributors.keys.sort %] - [% IF not person.match('^CSS1') %] -
  • [% person %]
  • - [% END %] -[%- END %] -
-[% IF suite == 'css2.1' %] -

...and all the contributors - to the CSS1 test suite.

-[% END %] diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.htm.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.htm.tmpl deleted file mode 100644 index c29ed4a3c72..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.htm.tmpl +++ /dev/null @@ -1,20 +0,0 @@ -[% PROCESS "suitedata.tmpl" %] - - - -[% IF official %] - [% suites.$suite.title %] -[% ELSE %] - Unofficial [% suites.$suite.title %] -[% END %] - - - - -[% INCLUDE "index.content.tmpl" %] - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.xht.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.xht.tmpl deleted file mode 100644 index b355544cfa5..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/index.xht.tmpl +++ /dev/null @@ -1,20 +0,0 @@ -[% PROCESS "suitedata.tmpl" %] - - - -[% IF official %] - [% suites.$suite.title %] -[% ELSE %] - Unofficial [% suites.$suite.title %] -[% END %] - - - - -[% INCLUDE index.content.tmpl %] - - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/indices.css b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/indices.css deleted file mode 100644 index 7bc70eeef94..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/indices.css +++ /dev/null @@ -1,96 +0,0 @@ -/* CSS for CSS Conformance Test Indices */ -/* Written by fantasai */ - -/* Test Tables */ - - table { - border-collapse: collapse; - } - - thead { - border-bottom: 0.2em solid; - } - - tbody { - border: thin solid; - border-style: solid none; - } - - tbody.ch { - border-top: 0.2em solid; - } - tbody.ch th { - font-weight: bold; - } - - tbody th { - border-bottom: silver dotted thin; - background: #EEE; - color: black; - font-weight: normal; - font-style: italic; - } - tbody th :link { - color: gray; - background: transparent; - } - tbody th :visited { - color: #333; - background: transparent; - } - - th, td { - padding: 0.2em; - text-align: left; - vertical-align: baseline; - } - - td { - font-size: 0.9em; - } - - /* flags */ - td abbr { - border: solid thin gray; - padding: 0 0.1em; - cursor: help; - } - td abbr:hover { - background: #ffa; - color: black; - } - - - tr:hover { - background: #F9F9F9; - color: navy; - } - - th a, - td a { - text-decoration: none; - } - th a:hover, - td a:hover, - th a:focus, - td a:focus { - text-decoration: underline; - } - - td a { - display: block; - padding-left: 2em; - text-indent: -1em; - } - .refs { - font-weight: bold; - font-size: larger; - } - .assert, .assert > li { - list-style-type: none; - font-style: italic; - color: gray; - margin: 0; - padding: 0; - text-indent: 0; - } diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/reftest-toc.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/reftest-toc.tmpl deleted file mode 100644 index 91894235a49..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/reftest-toc.tmpl +++ /dev/null @@ -1,74 +0,0 @@ -[%# variables in this template - isXML [bool] - extmap [ExtensionMap object] - suitetitle [string] - specroot [URI of spec] - formatdir [string] - chaptitle [string] - chapdir [string] - testcount [number] - sections [list of struct] - .id [string - section number or id] - .uri [URI of section] - .tests [list of struct] - .asserts [list of strings] - .flags [list of token strings] - .links [list of uri strings] - .name [string] -%] -[% PROCESS suitedata.tmpl %] -[% IF isXML %] - - -[% formatMismatchFlag = 'HTMLonly' %] -[% ELSE %] - - -[% formatMismatchFlag = 'nonHTML' %] -[% END %] - - [% suitetitle %] Reftest Index - - - - - -

[% suitetitle %] Reftest Index

- - [% IF isXML %][% END %] - [% IF isXML %][% END %] - [% IF isXML %][% END %] - - - - - - - -[% FOREACH entry IN tests.sort('name') %] - [% IF entry.references and not entry.flags.contains(formatMismatchFlag) %] - - [% FOREACH refList IN entry.references %] - [% IF loop.first %] - - - - - - [% ELSE %] - - - - [% END %] - [% END %] - - [% END %] -[% END %] -
TestReferenceFlags
- [% entry.name %][% FOREACH ref IN refList %][% refCompMap.${ref.type} %] [% END %][% FOREACH flag IN entry.flags %][% IF flag != 'nonHTML' and flag != 'HTMLonly' %][% flagInfo.$flag.abbr %][% END %][% END %]
[% refCompMap.${ref.type} %]
- - - diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/reftest.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/reftest.tmpl deleted file mode 100644 index 14b9bb6595e..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/reftest.tmpl +++ /dev/null @@ -1,7 +0,0 @@ -[% FOR entry IN tests.sort('name') %] -[% IF not entry.flags.contains(formatMismatchFlag) %] -[% FOREACH refList IN entry.references %] -[%+ extmap.translate(entry.file) %] [% FOREACH ref IN refList %] [%+ ref.type %] [%+ extmap.translate(ref.relpath) %][% END %] -[% END %] -[% END %] -[% END %] diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/suitedata.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/suitedata.tmpl deleted file mode 100644 index 6aae9f2ea84..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/suitedata.tmpl +++ /dev/null @@ -1,23 +0,0 @@ -[% refCompMap = - { '==' => '=', - '!=' => '≠' - } -%] -[% statusNames = { - 'dev' => { - 'title' => 'Development', - 'link' => 'http://www.w3.org/Style/CSS/Test/#phase-pa' }, - 'alpha' => { - 'title' => 'Alpha', - 'link' => 'http://www.w3.org/Style/CSS/Test/#phase-alpha' }, - 'beta' => { - 'title' => 'Beta', - 'link' => 'http://www.w3.org/Style/CSS/Test/#phase-beta' }, - 'rc' => { - 'title' => 'Release Candidate', - 'link' => 'http://www.w3.org/Style/CSS/Test/#phase-rc' }, - 'final' => { - 'title' => 'Final', - 'link' => 'http://www.w3.org/Style/CSS/Test/#phase-fin' }, - } -%] diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/test-toc.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/test-toc.tmpl deleted file mode 100644 index ff9ffbc1b8e..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/test-toc.tmpl +++ /dev/null @@ -1,97 +0,0 @@ -[%# variables in this template - isXML [bool] - extmap [ExtensionMap object] - suitetitle [string] - specroot [URI of spec] - formatdir [string] - chaptitle [string] - chapdir [string] - testcount [number] - sections [list of struct] - .id [string - section number or id] - .uri [URI of section] - .tests [list of struct] - .asserts [list of strings] - .flags [list of token strings] - .links [list of uri strings] - .name [string] -%] -[% PROCESS suitedata.tmpl %] -[% IF isXML %] - - -[% formatMismatchFlag = 'HTMLonly' %] -[% ELSE %] - - -[% formatMismatchFlag = 'nonHTML' %] -[% END %] - - [% chaptertitle %] - [% suitetitle %] - - - - - -

[% suitetitle %]

-[% IF chaptertitle %] -

[% chaptertitle %] ([% testcount %] tests)

-[% END %] - - [% IF isXML %][% END %] - [% IF isXML %][% END %] - [% IF isXML %][% END %] - [% IF isXML %][% END %] - - - - - - - - -[% FOREACH section IN sections %] - - [% IF section.title %] - - [% END %] - - [% FOREACH entry IN section.tests.sort('name') %] - [% FOREACH flag IN entry.flags %] - [% SET skip = 1 IF flag == formatMismatchFlag %] - [% END %] - [% UNLESS skip %] - [% primary = (entry.links.0 == section.uri) or (entry.links.0 == section.uri.replace(specroot, draftroot)) %] - - - - - - - [% END %] - [% skip = 0 %] - [% END %] - -[% END %] -
TestRefsFlagsInfo
- + - [% section.numstr +%] [%+ section.title %]
[% '' IF primary %] - [% entry.name%] - [% '' IF primary %][% FOREACH refList IN entry.references %][% FOREACH ref IN refList %][% refCompMap.${ref.type} %] [%+ END %][%+ END %][% FOREACH flag IN entry.flags %][% IF flag != 'nonHTML' and flag != 'HTMLonly' %][% flagInfo.$flag.abbr %][% END %][% END %][% entry.title | collapse | html %] - [% IF entry.asserts.size > 0 %] -
    - [% FOREACH assertion IN entry.asserts %] -
  • [% assertion | collapse | html %]
  • - [% END %] -
- [% END %] -
- - - \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/testinfo.data.tmpl b/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/testinfo.data.tmpl deleted file mode 100644 index d06a2a906cb..00000000000 --- a/tests/wpt/web-platform-tests/css/tools/w3ctestlib/templates/testinfo.data.tmpl +++ /dev/null @@ -1,16 +0,0 @@ -id references title flags links revision credits assertion -[% FOREACH test IN tests.sort('name') %] -[%+ test.file.replace('\.[a-z]+$', '') +%] -[%- FOREACH refList IN test.references -%][%- FOREACH ref IN refList -%] -[%- '!' IF ref.type == '!=' %][% extmap.translate(ref.relpath) %][% ',' IF not loop.last() -%] -[%- END +%][% ';' IF not loop.last() -%] -[%- END +%] -[%- test.title FILTER collapse +%] -[%- test.flags.join(',') +%] -[%- test.links.join(',') +%] -[%- test.revision +%] -[%- FOREACH credit IN test.credits -%] -`[% credit.0 %]`<[% credit.1 %]>[% ',' IF not loop.last() -%] -[%- END +%] -[%- test.asserts.join(' ') FILTER collapse +%] -[% END %] diff --git a/tests/wpt/web-platform-tests/docs/reviewing-tests/reverting.md b/tests/wpt/web-platform-tests/docs/reviewing-tests/reverting.md index 277ccb047ab..d374f0558e3 100644 --- a/tests/wpt/web-platform-tests/docs/reviewing-tests/reverting.md +++ b/tests/wpt/web-platform-tests/docs/reviewing-tests/reverting.md @@ -12,9 +12,6 @@ break things for users of web-platform-tests. Such breakage can include: * Breakage in results collections systems for results dashboards, such as [wpt.fyi](https://wpt.fyi). - * Breakage in supplemental tooling used by working groups, such as the - [CSS build system][]. - When such breakage happens, if the maintainers of the affected systems request it, pull requests to revert the original change should normally be approved and merged as soon as possible. (When the original change itself was fixing a @@ -24,5 +21,3 @@ state acceptable to everyone.) Once a revert has happened, the maintainers of the affected systems are expected to work with the original patch author to resolve the problem so that the change can be relanded. A reasonable timeframe to do so is within one week. - -[CSS build system]: https://github.com/web-platform-tests/wpt/tree/master/css/tools diff --git a/tests/wpt/web-platform-tests/fenced-frame/fledge-container-size-mutation-observer.https.html b/tests/wpt/web-platform-tests/fenced-frame/fledge-container-size-mutation-observer.https.html new file mode 100644 index 00000000000..b6085afce37 --- /dev/null +++ b/tests/wpt/web-platform-tests/fenced-frame/fledge-container-size-mutation-observer.https.html @@ -0,0 +1,48 @@ + +Test that mutation observer doesn't break noassert container size setter. + + + + + + + + + diff --git a/tests/wpt/web-platform-tests/fenced-frame/fledge-container-size.https.html b/tests/wpt/web-platform-tests/fenced-frame/fledge-container-size.https.html new file mode 100644 index 00000000000..5347c841d58 --- /dev/null +++ b/tests/wpt/web-platform-tests/fenced-frame/fledge-container-size.https.html @@ -0,0 +1,102 @@ + +Test container size in FLEDGE fenced frames. + + + + + + + + + diff --git a/tests/wpt/web-platform-tests/fenced-frame/resources/utils.js b/tests/wpt/web-platform-tests/fenced-frame/resources/utils.js index d35855cbcfc..2263fc1db18 100644 --- a/tests/wpt/web-platform-tests/fenced-frame/resources/utils.js +++ b/tests/wpt/web-platform-tests/fenced-frame/resources/utils.js @@ -70,7 +70,8 @@ async function runSelectURL(href, keylist = [], resolve_to_config = false) { async function generateURNFromFledgeRawURL(href, nested_urls, resolve_to_config = false, - ad_with_size = false) { + ad_with_size = false, + requested_size = null) { const bidding_token = token(); const seller_token = token(); @@ -106,13 +107,16 @@ async function generateURNFromFledgeRawURL(href, // ad interest group while the test runs. navigator.joinAdInterestGroup(interestGroup, /*durationSeconds=*/3000000); - const auctionConfig = { + let auctionConfig = { seller: location.origin, interestGroupBuyers: [location.origin], decisionLogicUrl: new URL(FLEDGE_DECISION_URL, location.origin), auctionSignals: {biddingToken: bidding_token, sellerToken: seller_token}, - resolveToConfig: resolve_to_config, + resolveToConfig: resolve_to_config }; + if (requested_size) { + auctionConfig['requestedSize'] = {width: requested_size[0], height: requested_size[1]}; + } return navigator.runAdAuction(auctionConfig); } @@ -133,9 +137,9 @@ async function generateURNFromFledgeRawURL(href, // frame config. // @param {boolean} [ad_with_size = false] - Determines whether the auction is // run with ad sizes specified. -async function generateURNFromFledge(href, keylist, nested_urls=[], resolve_to_config = false, ad_with_size = false) { +async function generateURNFromFledge(href, keylist, nested_urls=[], resolve_to_config = false, ad_with_size = false, requested_size = null) { const full_url = generateURL(href, keylist); - return generateURNFromFledgeRawURL(full_url, nested_urls, resolve_to_config, ad_with_size); + return generateURNFromFledgeRawURL(full_url, nested_urls, resolve_to_config, ad_with_size, requested_size); } // Extracts a list of UUIDs from the from the current page's URL. @@ -240,23 +244,23 @@ function attachContext(object_constructor, html, headers, origin) { // function. // 1. crbug.com/1372536: resize-lock-input.https.html // 2. crbug.com/1394559: unfenced-top.https.html -async function attachOpaqueContext(generator_api, resolve_to_config, ad_with_size, object_constructor, html, headers, origin) { +async function attachOpaqueContext(generator_api, resolve_to_config, ad_with_size, requested_size, object_constructor, html, headers, origin) { const [uuid, url] = generateRemoteContextURL(headers, origin); - const id = await (generator_api == 'fledge' ? generateURNFromFledge(url, [], [], resolve_to_config, ad_with_size) : runSelectURL(url, [], resolve_to_config)); + const id = await (generator_api == 'fledge' ? generateURNFromFledge(url, [], [], resolve_to_config, ad_with_size, requested_size) : runSelectURL(url, [], resolve_to_config)); const object = object_constructor(id); return buildRemoteContextForObject(object, uuid, html); } -function attachPotentiallyOpaqueContext(generator_api, resolve_to_config, ad_with_size, frame_constructor, html, headers, origin) { +function attachPotentiallyOpaqueContext(generator_api, resolve_to_config, ad_with_size, requested_size, frame_constructor, html, headers, origin) { generator_api = generator_api.toLowerCase(); if (generator_api == 'fledge' || generator_api == 'sharedstorage') { - return attachOpaqueContext(generator_api, resolve_to_config, ad_with_size, frame_constructor, html, headers, origin); + return attachOpaqueContext(generator_api, resolve_to_config, ad_with_size, requested_size, frame_constructor, html, headers, origin); } else { return attachContext(frame_constructor, html, headers, origin); } } -function attachFrameContext(element_name, generator_api, resolve_to_config, ad_with_size, html, headers, attributes, origin) { +function attachFrameContext(element_name, generator_api, resolve_to_config, ad_with_size, requested_size, html, headers, attributes, origin) { frame_constructor = (id) => { frame = document.createElement(element_name); attributes.forEach(attribute => { @@ -273,10 +277,10 @@ function attachFrameContext(element_name, generator_api, resolve_to_config, ad_w document.body.append(frame); return frame; }; - return attachPotentiallyOpaqueContext(generator_api, resolve_to_config, ad_with_size, frame_constructor, html, headers, origin); + return attachPotentiallyOpaqueContext(generator_api, resolve_to_config, ad_with_size, requested_size, frame_constructor, html, headers, origin); } -function replaceFrameContext(frame_proxy, {generator_api="", resolve_to_config=false, html="", headers=[], origin=""}={}) { +function replaceFrameContext(frame_proxy, {generator_api="", resolve_to_config=false, ad_with_size=false, requested_size=null, html="", headers=[], origin=""}={}) { frame_constructor = (id) => { if (frame_proxy.element.nodeName == "IFRAME") { frame_proxy.element.src = id; @@ -288,7 +292,7 @@ function replaceFrameContext(frame_proxy, {generator_api="", resolve_to_config=f } return frame_proxy.element; }; - return attachPotentiallyOpaqueContext(generator_api, resolve_to_config, ad_with_size=false, frame_constructor, html, headers, origin); + return attachPotentiallyOpaqueContext(generator_api, resolve_to_config, ad_with_size, requested_size, frame_constructor, html, headers, origin); } // Attach a fenced frame that waits for scripts to execute. @@ -301,20 +305,22 @@ function replaceFrameContext(frame_proxy, {generator_api="", resolve_to_config=f // for FLEDGE and sharedStorage generator_api) // - ad_with_size: whether an ad auction is run with size specified for the ads // and ad components. (currently only works for FLEDGE) +// - requested_size: A 2-element list with the width and height for +// requestedSize in the FLEDGE auction config. // - html: extra HTML source code to inject into the loaded frame // - headers: an array of header pairs [[key, value], ...] // - attributes: an array of attribute pairs to set on the frame [[key, value], ...] // - origin: origin of the url, default to location.origin if not set // Returns a proxy that acts like the frame HTML element, but with an extra // function `execute`. See `attachFrameContext` or the README for more details. -function attachFencedFrameContext({generator_api="", resolve_to_config=false, ad_with_size=false, html = "", headers=[], attributes=[], origin=""}={}) { - return attachFrameContext('fencedframe', generator_api, resolve_to_config, ad_with_size, html, headers, attributes, origin); +function attachFencedFrameContext({generator_api="", resolve_to_config=false, ad_with_size=false, requested_size=null, html = "", headers=[], attributes=[], origin=""}={}) { + return attachFrameContext('fencedframe', generator_api, resolve_to_config, ad_with_size, requested_size, html, headers, attributes, origin); } // Attach an iframe that waits for scripts to execute. // See `attachFencedFrameContext` for more details. function attachIFrameContext({generator_api="", html="", headers=[], attributes=[], origin=""}={}) { - return attachFrameContext('iframe', generator_api, resolve_to_config=false, ad_with_size=false, html, headers, attributes, origin); + return attachFrameContext('iframe', generator_api, resolve_to_config=false, ad_with_size=false, requested_size=null, html, headers, attributes, origin); } // Open a window that waits for scripts to execute. diff --git a/tests/wpt/web-platform-tests/fenced-frame/storage-partitioning.https.html b/tests/wpt/web-platform-tests/fenced-frame/storage-partitioning.https.html index 5d6060c66fe..36b43953393 100644 --- a/tests/wpt/web-platform-tests/fenced-frame/storage-partitioning.https.html +++ b/tests/wpt/web-platform-tests/fenced-frame/storage-partitioning.https.html @@ -1,5 +1,6 @@ Test storage partitioning in fenced frames + @@ -17,8 +18,8 @@ async function runTest(getter, setter) { const inner_value = "inner"; // Set the value in the top-level frame, and check that it worked. - setter(key, outer_value); - assert_equals(getter(key), outer_value, + await setter(key, outer_value); + assert_equals(await getter(key), outer_value, "Stored the value in the top-level frame."); // Attach a fenced frame. @@ -36,7 +37,7 @@ async function runTest(getter, setter) { "Stored the value in the fenced frame."); // Check that the inner value isn't visible in the top-level frame. - assert_equals(getter(key), outer_value, + assert_equals(await getter(key), outer_value, "The inner value isn't visible outside the fenced frame."); // Perform an embedder-initiated navigation that will fail. @@ -84,5 +85,104 @@ promise_test(async () => { ); }, 'localStorage'); +promise_test(async () => { + return runTest( + (key) => { return sessionStorage.getItem(key); }, + (key, value) => { return sessionStorage.setItem(key, value); } + ); +}, 'sessionStorage'); + +promise_test(async () => { + return runTest( + async (key) => { + const newCache = await caches.open('test-cache'); + const response = await newCache.match(key); + if (!response) { + return null; + } + return response.text(); + }, + async (key, value) => { + const newCache = await caches.open('test-cache'); + return newCache.put(key, new Response(value)); + } + ); +}, 'Cache API'); + +promise_test(async () => { + return runTest( + async (key) => { + const root = await navigator.storage.getDirectory(); + const draftHandle = await root.getFileHandle(key, { create: true }); + const file = await draftHandle.getFile(); + const text = await file.text(); + return text || null; + }, + async (key, value) => { + const root = await navigator.storage.getDirectory(); + const draftHandle = await root.getFileHandle(key, { create: true }); + const writable = await draftHandle.createWritable() + await writable.truncate(0); + await writable.write(value); + await writable.close(); + } + ); +}, 'File System Access API'); + +promise_test(async () => { + return runTest( + async (key) => { + const openRequest = indexedDB.open('test-db', 2); + const db = await new Promise((resolve) => { + openRequest.onsuccess = (event) => { + resolve(event.target.result); + }; + openRequest.onupgradeneeded = (event) => { + const db = event.target.result; + const objStore = db.createObjectStore('test-tbl', {keyPath: 'key'}); + objStore.transaction.oncomplete = (event) => { + resolve(db); + }; + }; + }); + const readRequest = db.transaction(['test-tbl']) + .objectStore('test-tbl') + .get(key); + return new Promise((resolve) => { + readRequest.onsuccess = (event) => { + if (!event.target.result) { + resolve(null); + } else { + resolve(event.target.result['value']); + } + }; + }); + }, + async (key, value) => { + const openRequest = indexedDB.open('test-db', 2); + const db = await new Promise((resolve) => { + openRequest.onsuccess = (event) => { + resolve(event.target.result); + }; + openRequest.onupgradeneeded = (event) => { + const db = event.target.result; + const objStore = db.createObjectStore('test-tbl', {keyPath: 'key'}); + objStore.transaction.oncomplete = (event) => { + resolve(db); + }; + }; + }); + const writeRequest = db.transaction(['test-tbl'], 'readwrite') + .objectStore('test-tbl') + .add({'key': key, 'value': value}); + return new Promise((resolve) => { + writeRequest.onsuccess = (event) => { + resolve(event.target.result); + }; + }); + } + ); +}, 'IndexedDB'); + diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/fetch-from-treat-as-public.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/fetch-from-treat-as-public.https.window.js index 90f7feb6341..084e03282f4 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/fetch-from-treat-as-public.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/fetch-from-treat-as-public.https.window.js @@ -12,7 +12,10 @@ promise_test(t => fetchTest(t, { server: Server.HTTPS_LOCAL, treatAsPublic: true, }, - target: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + preflight: PreflightBehavior.noPnaHeader(token()), + }, expected: FetchTestResult.FAILURE, }), "treat-as-public-address to local: failed preflight."); @@ -22,15 +25,24 @@ promise_test(t => fetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { - preflight: PreflightBehavior.optionalSuccess(token()), - // Interesting: no need for CORS headers on same-origin final response. + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), }, }, expected: FetchTestResult.SUCCESS, }), "treat-as-public-address to local: success."); +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public-address to local (same-origin): no preflight required."); + promise_test(t => fetchTest(t, { source: { server: Server.HTTPS_LOCAL, diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/iframe.tentative.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/iframe.tentative.https.window.js index 48bd6420fd9..6a83b88d3ff 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/iframe.tentative.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/iframe.tentative.https.window.js @@ -154,10 +154,19 @@ makePreflightTests({ sourceServer: Server.HTTPS_LOCAL, sourceTreatAsPublic: true, sourceName: "treat-as-public-address", - targetServer: Server.HTTPS_LOCAL, + targetServer: Server.OTHER_HTTPS_LOCAL, targetName: "local", }); +promise_test_parallel(t => iframeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: IframeTestResult.SUCCESS, +}), "treat-as-public-address to local (same-origin): no preflight required."); + makePreflightTests({ sourceServer: Server.HTTPS_LOCAL, sourceTreatAsPublic: true, @@ -196,6 +205,14 @@ iframeGrandparentTest({ name: "local to local, grandparent navigates: no preflight required.", grandparentServer: Server.HTTPS_LOCAL, child: { server: Server.HTTPS_PUBLIC }, + grandchild: { server: Server.OTHER_HTTPS_LOCAL }, + expected: IframeTestResult.SUCCESS, +}); + +iframeGrandparentTest({ + name: "local to local (same-origin), grandparent navigates: no preflight required.", + grandparentServer: Server.HTTPS_LOCAL, + child: { server: Server.HTTPS_PUBLIC }, grandchild: { server: Server.HTTPS_LOCAL }, expected: IframeTestResult.SUCCESS, }); diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/redirect.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/redirect.https.window.js index edbd5a19fbc..efbd8f31f93 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/redirect.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/redirect.https.window.js @@ -244,7 +244,7 @@ promise_test(t => fetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { redirect: preflightUrl({ server: Server.HTTPS_PRIVATE, @@ -253,6 +253,7 @@ promise_test(t => fetchTest(t, { response: ResponseBehavior.allowCrossOrigin(), }, }), + response: ResponseBehavior.allowCrossOrigin(), } }, expected: FetchTestResult.FAILURE, @@ -264,7 +265,7 @@ promise_test(t => fetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { preflight: PreflightBehavior.success(token()), redirect: preflightUrl({ @@ -274,6 +275,7 @@ promise_test(t => fetchTest(t, { response: ResponseBehavior.allowCrossOrigin(), }, }), + response: ResponseBehavior.allowCrossOrigin(), } }, expected: FetchTestResult.FAILURE, @@ -285,7 +287,7 @@ promise_test(t => fetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { preflight: PreflightBehavior.success(token()), redirect: preflightUrl({ @@ -295,6 +297,7 @@ promise_test(t => fetchTest(t, { response: ResponseBehavior.allowCrossOrigin(), }, }), + response: ResponseBehavior.allowCrossOrigin(), } }, expected: FetchTestResult.SUCCESS, @@ -306,7 +309,7 @@ promise_test(t => fetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { redirect: preflightUrl({ server: Server.HTTPS_PRIVATE, @@ -324,7 +327,7 @@ promise_test(t => fetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { preflight: PreflightBehavior.success(token()), redirect: preflightUrl({ server: Server.HTTPS_PRIVATE }), @@ -340,7 +343,7 @@ promise_test(t => fetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { preflight: PreflightBehavior.success(token()), redirect: preflightUrl({ @@ -353,6 +356,88 @@ promise_test(t => fetchTest(t, { expected: FetchTestResult.OPAQUE, }), "treat-as-public to local to private: no-cors success."); +// treat-as-public -> local (same-origin) -> private + +// Request 1 (treat-as-public -> local (same-origin)): no preflight required. +// Request 2 (treat-as-public -> private): preflight required. + +// This verifies that PNA checks are applied only to the second step in a +// redirect chain if the first step is same-origin and the origin is potentially +// trustworthy. + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.noPnaHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to local (same-origin) to private: failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public to local (same-origin) to private: success."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ server: Server.HTTPS_PRIVATE }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to local (same-origin) to private: no-cors failed second preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_LOCAL, + behavior: { + redirect: preflightUrl({ + server: Server.HTTPS_PRIVATE, + behavior: { preflight: PreflightBehavior.success(token()) }, + }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "treat-as-public to local (same-origin) to private: no-cors success."); + // treat-as-public -> private -> local // Request 1 (treat-as-public -> private): preflight required. @@ -371,7 +456,7 @@ promise_test(t => fetchTest(t, { preflight: PreflightBehavior.noPnaHeader(token()), response: ResponseBehavior.allowCrossOrigin(), redirect: preflightUrl({ - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { preflight: PreflightBehavior.success(token()), response: ResponseBehavior.allowCrossOrigin(), @@ -393,7 +478,7 @@ promise_test(t => fetchTest(t, { preflight: PreflightBehavior.success(token()), response: ResponseBehavior.allowCrossOrigin(), redirect: preflightUrl({ - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { response: ResponseBehavior.allowCrossOrigin() }, }), } @@ -412,7 +497,7 @@ promise_test(t => fetchTest(t, { preflight: PreflightBehavior.success(token()), response: ResponseBehavior.allowCrossOrigin(), redirect: preflightUrl({ - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { preflight: PreflightBehavior.success(token()), response: ResponseBehavior.allowCrossOrigin(), @@ -432,7 +517,7 @@ promise_test(t => fetchTest(t, { server: Server.HTTPS_PRIVATE, behavior: { redirect: preflightUrl({ - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { preflight: PreflightBehavior.success(token()) }, }), } @@ -450,7 +535,7 @@ promise_test(t => fetchTest(t, { server: Server.HTTPS_PRIVATE, behavior: { preflight: PreflightBehavior.success(token()), - redirect: preflightUrl({ server: Server.HTTPS_LOCAL }), + redirect: preflightUrl({ server: Server.OTHER_HTTPS_LOCAL }), } }, fetchOptions: { mode: "no-cors" }, @@ -467,7 +552,7 @@ promise_test(t => fetchTest(t, { behavior: { preflight: PreflightBehavior.success(token()), redirect: preflightUrl({ - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { preflight: PreflightBehavior.success(token()) }, }), } @@ -475,3 +560,81 @@ promise_test(t => fetchTest(t, { fetchOptions: { mode: "no-cors" }, expected: FetchTestResult.OPAQUE, }), "treat-as-public to private to local: no-cors success."); + +// treat-as-public -> private -> local (same-origin) + +// Request 1 (treat-as-public -> private): preflight required. +// Request 2 (treat-as-public -> local (same-origin)): no preflight required. + +// This verifies that PNA checks are only applied to the first step in a +// redirect chain if the second step is same-origin and the origin is +// potentially trustworthy. + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.noPnaHeader(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to private to local (same-origin): failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + redirect: preflightUrl({ + server: Server.HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }), + } + }, + expected: FetchTestResult.SUCCESS, +}), "treat-as-public to private to local (same-origin): success."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + redirect: preflightUrl({ server: Server.HTTPS_LOCAL }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.FAILURE, +}), "treat-as-public to private to local (same-origin): no-cors failed first preflight."); + +promise_test(t => fetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { + server: Server.HTTPS_PRIVATE, + behavior: { + preflight: PreflightBehavior.success(token()), + redirect: preflightUrl({ server: Server.HTTPS_LOCAL }), + } + }, + fetchOptions: { mode: "no-cors" }, + expected: FetchTestResult.OPAQUE, +}), "treat-as-public to private to local (same-origin): no-cors success."); diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/resources/support.sub.js b/tests/wpt/web-platform-tests/fetch/local-network-access/resources/support.sub.js index 0cf3d2532e7..a09c46031f5 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/resources/support.sub.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/resources/support.sub.js @@ -81,6 +81,7 @@ const SERVER_PORTS = { }, "https": { "loopback": {{ports[https][0]}}, + "other-loopback": {{ports[https][1]}}, "local": {{ports[https-private][0]}}, "public": {{ports[https-public][0]}}, }, @@ -130,6 +131,7 @@ class Server { static HTTP_PRIVATE = Server.get("http", "local"); static HTTP_PUBLIC = Server.get("http", "public"); static HTTPS_LOCAL = Server.get("https", "loopback"); + static OTHER_HTTPS_LOCAL = Server.get("https", "other-loopback"); static HTTPS_PRIVATE = Server.get("https", "local"); static HTTPS_PUBLIC = Server.get("https", "public"); static WS_LOCAL = Server.get("ws", "loopback"); diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker-fetch.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker-fetch.https.window.js index 5645d784561..3d0f6d8097a 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker-fetch.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker-fetch.https.window.js @@ -161,7 +161,10 @@ promise_test(t => makeTest(t, { server: Server.HTTPS_LOCAL, treatAsPublic: true, }, - target: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, expected: TestResult.FAILURE, }), "treat-as-public to local: failed preflight."); @@ -171,12 +174,24 @@ promise_test(t => makeTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, - behavior: { preflight: PreflightBehavior.success(token()) }, + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, }, expected: TestResult.SUCCESS, }), "treat-as-public to local: success."); +promise_test(t => makeTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: TestResult.SUCCESS, +}), "treat-as-public to local (same-origin): no preflight required."); + promise_test(t => makeTest(t, { source: { server: Server.HTTPS_LOCAL, diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker-update.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker-update.https.window.js index fe2bf58f660..4882d235bb0 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker-update.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker-update.https.window.js @@ -3,9 +3,10 @@ // // Spec: https://wicg.github.io/private-network-access/#integration-fetch // -// These tests check that `ServiceWorker` script update fetches are subject to -// Private Network Access checks, just like regular `fetch()` calls. The client -// of the fetch, for PNA purposes, is taken to be the previous script. +// These tests check that `ServiceWorker` script update fetches are exempt from +// Private Network Access checks because they are always same-origin and the +// origin is potentially trustworthy. The client of the fetch, for PNA purposes, +// is taken to be the previous script. // // The tests is carried out by instantiating a service worker from a resource // that carries the `Content-Security-Policy: treat-as-public-address` header, @@ -91,27 +92,11 @@ async function makeTest(t, { target, expected }) { promise_test(t => makeTest(t, { target: { server: Server.HTTPS_LOCAL }, - expected: TestResult.FAILURE, -}), "update public to local: failed preflight."); - -promise_test(t => makeTest(t, { - target: { - server: Server.HTTPS_LOCAL, - behavior: { preflight: PreflightBehavior.serviceWorkerSuccess(token()) }, - }, expected: TestResult.SUCCESS, }), "update public to local: success."); promise_test(t => makeTest(t, { target: { server: Server.HTTPS_PRIVATE }, - expected: TestResult.FAILURE, -}), "update public to private: failed preflight."); - -promise_test(t => makeTest(t, { - target: { - server: Server.HTTPS_PRIVATE, - behavior: { preflight: PreflightBehavior.serviceWorkerSuccess(token()) }, - }, expected: TestResult.SUCCESS, }), "update public to private: success."); diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker.https.window.js index 8dc631f65a8..046f662a127 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/service-worker.https.window.js @@ -3,8 +3,9 @@ // // Spec: https://wicg.github.io/private-network-access/#integration-fetch // -// These tests check that initial `ServiceWorker` script fetches are subject to -// Private Network Access checks, just like a regular `fetch()`. +// These tests check that initial `ServiceWorker` script fetches are exempt from +// Private Network Access checks because they are always same-origin and the +// origin is potentially trustworthy. // // See also: worker.https.window.js @@ -64,18 +65,6 @@ promise_test(t => makeTest(t, { treatAsPublic: true, }, target: { server: Server.HTTPS_LOCAL }, - expected: TestResult.FAILURE, -}), "treat-as-public to local: failed preflight."); - -promise_test(t => makeTest(t, { - source: { - server: Server.HTTPS_LOCAL, - treatAsPublic: true, - }, - target: { - server: Server.HTTPS_LOCAL, - behavior: { preflight: PreflightBehavior.serviceWorkerSuccess(token()) }, - }, expected: TestResult.SUCCESS, }), "treat-as-public to local: success."); @@ -85,18 +74,6 @@ promise_test(t => makeTest(t, { treatAsPublic: true, }, target: { server: Server.HTTPS_PRIVATE }, - expected: TestResult.FAILURE, -}), "treat-as-public to private: failed preflight."); - -promise_test(t => makeTest(t, { - source: { - server: Server.HTTPS_PRIVATE, - treatAsPublic: true, - }, - target: { - server: Server.HTTPS_PRIVATE, - behavior: { preflight: PreflightBehavior.serviceWorkerSuccess(token()) }, - }, expected: TestResult.SUCCESS, }), "treat-as-public to private: success."); diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker-blob-fetch.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker-blob-fetch.https.window.js index ad9cd09c31b..269abb7edc4 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker-blob-fetch.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker-blob-fetch.https.window.js @@ -7,8 +7,8 @@ // loaded from blob URLs are subject to Private Network Access checks, just like // fetches from within documents. // -// This file covers only those tests that must execute in a non-secure context. -// Other tests are defined in: shared-worker-blob-fetch.https.window.js +// This file covers only those tests that must execute in a secure context. +// Other tests are defined in: shared-worker-blob-fetch.window.js promise_test(t => sharedWorkerBlobFetchTest(t, { source: { server: Server.HTTPS_LOCAL }, @@ -96,7 +96,10 @@ promise_test(t => sharedWorkerBlobFetchTest(t, { server: Server.HTTPS_LOCAL, treatAsPublic: true, }, - target: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, expected: WorkerFetchTestResult.FAILURE, }), "treat-as-public to local: failed preflight."); @@ -106,12 +109,24 @@ promise_test(t => sharedWorkerBlobFetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, - behavior: { preflight: PreflightBehavior.success(token()) }, + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, }, expected: WorkerFetchTestResult.SUCCESS, }), "treat-as-public to local: success."); +promise_test(t => sharedWorkerBlobFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to local (same-origin): no preflight required."); + promise_test(t => sharedWorkerBlobFetchTest(t, { source: { server: Server.HTTPS_LOCAL, diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker-fetch.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker-fetch.https.window.js index 7066b359caa..e5f2b949202 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker-fetch.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker-fetch.https.window.js @@ -95,7 +95,10 @@ promise_test(t => sharedWorkerFetchTest(t, { server: Server.HTTPS_LOCAL, treatAsPublic: true, }, - target: { server: Server.HTTPS_LOCAL }, + target: { + server: Server.OTHER_HTTPS_LOCAL, + behavior: { response: ResponseBehavior.allowCrossOrigin() }, + }, expected: WorkerFetchTestResult.FAILURE, }), "treat-as-public to local: failed preflight."); @@ -105,12 +108,24 @@ promise_test(t => sharedWorkerFetchTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, - behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, + server: Server.OTHER_HTTPS_LOCAL, + behavior: { + preflight: PreflightBehavior.success(token()), + response: ResponseBehavior.allowCrossOrigin(), + }, }, expected: WorkerFetchTestResult.SUCCESS, }), "treat-as-public to local: success."); +promise_test(t => sharedWorkerFetchTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: WorkerFetchTestResult.SUCCESS, +}), "treat-as-public to local (same-origin): no preflight required."); + promise_test(t => sharedWorkerFetchTest(t, { source: { server: Server.HTTPS_LOCAL, diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker.https.window.js index ecb70c41245..24ae1087828 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/shared-worker.https.window.js @@ -15,18 +15,6 @@ promise_test(t => sharedWorkerScriptTest(t, { treatAsPublic: true, }, target: { server: Server.HTTPS_LOCAL }, - expected: WorkerScriptTestResult.FAILURE, -}), "treat-as-public to local: failed preflight."); - -promise_test(t => sharedWorkerScriptTest(t, { - source: { - server: Server.HTTPS_LOCAL, - treatAsPublic: true, - }, - target: { - server: Server.HTTPS_LOCAL, - behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, - }, expected: WorkerScriptTestResult.SUCCESS, }), "treat-as-public to local: success."); @@ -36,18 +24,6 @@ promise_test(t => sharedWorkerScriptTest(t, { treatAsPublic: true, }, target: { server: Server.HTTPS_PRIVATE }, - expected: WorkerScriptTestResult.FAILURE, -}), "treat-as-public to private: failed preflight."); - -promise_test(t => sharedWorkerScriptTest(t, { - source: { - server: Server.HTTPS_PRIVATE, - treatAsPublic: true, - }, - target: { - server: Server.HTTPS_PRIVATE, - behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, - }, expected: WorkerScriptTestResult.SUCCESS, }), "treat-as-public to private: success."); diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/worker.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/worker.https.window.js index 2d0dddd685c..a0f19314ee3 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/worker.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/worker.https.window.js @@ -3,11 +3,11 @@ // // Spec: https://wicg.github.io/private-network-access/#integration-fetch // -// These tests check that initial `Worker` script fetches are subject to Private -// Network Access checks, just like a regular `fetch()`. The main difference is -// that workers can only be fetched same-origin, so the only way to test this -// is using the `treat-as-public` CSP directive to artificially place the parent -// document in the `public` IP address space. +// These tests check that initial `Worker` script fetches in secure contexts are +// exempt from Private Network Access checks because workers can only be fetched +// same-origin and the origin is potentially trustworthy. The only way to test +// this is using the `treat-as-public` CSP directive to artificially place the +// parent document in the `public` IP address space. // // This file covers only those tests that must execute in a secure context. // Other tests are defined in: worker.window.js @@ -18,18 +18,6 @@ promise_test(t => workerScriptTest(t, { treatAsPublic: true, }, target: { server: Server.HTTPS_LOCAL }, - expected: WorkerScriptTestResult.FAILURE, -}), "treat-as-public to local: failed preflight."); - -promise_test(t => workerScriptTest(t, { - source: { - server: Server.HTTPS_LOCAL, - treatAsPublic: true, - }, - target: { - server: Server.HTTPS_LOCAL, - behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, - }, expected: WorkerScriptTestResult.SUCCESS, }), "treat-as-public to local: success."); @@ -39,18 +27,6 @@ promise_test(t => workerScriptTest(t, { treatAsPublic: true, }, target: { server: Server.HTTPS_PRIVATE }, - expected: WorkerScriptTestResult.FAILURE, -}), "treat-as-public to private: failed preflight."); - -promise_test(t => workerScriptTest(t, { - source: { - server: Server.HTTPS_PRIVATE, - treatAsPublic: true, - }, - target: { - server: Server.HTTPS_PRIVATE, - behavior: { preflight: PreflightBehavior.optionalSuccess(token()) }, - }, expected: WorkerScriptTestResult.SUCCESS, }), "treat-as-public to private: success."); diff --git a/tests/wpt/web-platform-tests/fetch/local-network-access/xhr-from-treat-as-public.https.window.js b/tests/wpt/web-platform-tests/fetch/local-network-access/xhr-from-treat-as-public.https.window.js index 04fe5449d19..3aae3050d97 100644 --- a/tests/wpt/web-platform-tests/fetch/local-network-access/xhr-from-treat-as-public.https.window.js +++ b/tests/wpt/web-platform-tests/fetch/local-network-access/xhr-from-treat-as-public.https.window.js @@ -13,7 +13,7 @@ promise_test(t => xhrTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { response: ResponseBehavior.allowCrossOrigin() }, }, expected: XhrTestResult.FAILURE, @@ -25,15 +25,24 @@ promise_test(t => xhrTest(t, { treatAsPublic: true, }, target: { - server: Server.HTTPS_LOCAL, + server: Server.OTHER_HTTPS_LOCAL, behavior: { - preflight: PreflightBehavior.optionalSuccess(token()), + preflight: PreflightBehavior.success(token()), response: ResponseBehavior.allowCrossOrigin(), }, }, expected: XhrTestResult.SUCCESS, }), "treat-as-public to local: success."); +promise_test(t => xhrTest(t, { + source: { + server: Server.HTTPS_LOCAL, + treatAsPublic: true, + }, + target: { server: Server.HTTPS_LOCAL }, + expected: XhrTestResult.SUCCESS, +}), "treat-as-public to local (same-origin): no preflight required."); + promise_test(t => xhrTest(t, { source: { server: Server.HTTPS_LOCAL, diff --git a/tests/wpt/web-platform-tests/html/anonymous-iframe/embedding.tentative.https.window.js b/tests/wpt/web-platform-tests/html/anonymous-iframe/embedding.tentative.https.window.js index edaf49b95cc..8c5e2fa60f8 100644 --- a/tests/wpt/web-platform-tests/html/anonymous-iframe/embedding.tentative.https.window.js +++ b/tests/wpt/web-platform-tests/html/anonymous-iframe/embedding.tentative.https.window.js @@ -101,8 +101,8 @@ subsetTest(embeddingTest, // variant = 11 subsetTest(embeddingTest, - "Parents embeds a CSP:frame-ancestore credentialless iframe", { - child_headers: "|headers(Content-Security-Policy,frame-ancestors 'none')", + "Parents embeds a CSP:frame-ancestors credentialless iframe", { + child_headers: "|header(Content-Security-Policy,frame-ancestors 'none')", expectation: EXPECT_BLOCK, }); diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-cross-frame-crossorigin.sub.html b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-cross-frame-crossorigin.sub.html new file mode 100644 index 00000000000..a2ea20bf7f7 --- /dev/null +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-cross-frame-crossorigin.sub.html @@ -0,0 +1,42 @@ + + + + + + +
+ +
+ + diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-cross-frame.html b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-cross-frame.html new file mode 100644 index 00000000000..d647e6ad064 --- /dev/null +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-cross-frame.html @@ -0,0 +1,40 @@ + + + + + + +
+ +
+ + diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-popup-crossorigin.sub.html b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-popup-crossorigin.sub.html new file mode 100644 index 00000000000..d54cc81477f --- /dev/null +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-popup-crossorigin.sub.html @@ -0,0 +1,39 @@ + + + + + + +
+ +
+ + diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-popup.html b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-popup.html new file mode 100644 index 00000000000..b27d54675dc --- /dev/null +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit-popup.html @@ -0,0 +1,37 @@ + + + + + + +
+ +
+ + diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit.html b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit.html index 4012cd014f1..eace0b0a69b 100644 --- a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit.html +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/form-submit.html @@ -35,5 +35,5 @@ promise_test(async t => { await checkSentinelIframe(t, sentinelIframe); assert_equals(history.length, startingHistoryLength, "history.length must not change after checking the sentinel iframe"); -}, "Replace before load, triggered by formElement.submit()"); +}, "Replace before load, triggered by same-document formElement.submit()"); diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/history-pushstate-during-pageshow.html b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/history-pushstate-during-pageshow.html index 2a5d78de066..a4e83baf1d9 100644 --- a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/history-pushstate-during-pageshow.html +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/history-pushstate-during-pageshow.html @@ -23,7 +23,7 @@ promise_test(async t => { const iframe = insertIframe(t, startURL); assert_equals(history.length, startingHistoryLength, "Inserting the under-test iframe must not change history.length"); - await waitForMessage(t, "done"); + assert_equals(await waitForMessage(), "done"); assert_equals(history.length, startingHistoryLength + 1, "history.length must change after waiting for the replacement"); }, "history.pushState() during the pageshow event must NOT replace"); diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/location-setter-during-pageshow.html b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/location-setter-during-pageshow.html index d28de2ac891..9997783ff55 100644 --- a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/location-setter-during-pageshow.html +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/location-setter-during-pageshow.html @@ -68,7 +68,7 @@ promise_test(async t => { const iframe = insertIframe(t, startURL); assert_equals(history.length, startingHistoryLength, "Inserting the under-test iframe must not change history.length"); - await waitForMessage(t, "done"); + assert_equals(await waitForMessage(), "done"); assert_equals(history.length, startingHistoryLength, "history.length must not change after waiting for the replacement"); await checkSentinelIframe(t, sentinelIframe); diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/resources/helpers.js b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/resources/helpers.js index a6c0dc0065b..58102aa9254 100644 --- a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/resources/helpers.js +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/resources/helpers.js @@ -25,12 +25,11 @@ window.waitForLoadAllowingIntermediateLoads = (t, iframe, urlRelativeToThisDocum }); }; -window.waitForMessage = (t, expected) => { +window.waitForMessage = () => { return new Promise(resolve => { - window.addEventListener("message", t.step_func(e => { - assert_equals(e.data, expected); - resolve(); - }), { once: true }); + window.addEventListener("message", e => { + resolve(e.data); + }, { once: true }); }); }; @@ -55,9 +54,16 @@ window.checkSentinelIframe = async (t, sentinelIframe) => { await waitForLoad(t, sentinelIframe, "/common/blank.html?sentinelstart"); }; -window.insertIframe = (t, url) => { +window.insertIframe = (t, url, name) => { const iframe = document.createElement("iframe"); iframe.src = url; + + // In at least Chromium, window name targeting for form submission doesn't work if the name is set + // after the iframe is inserted into the DOM. So we can't just have callers do this themselves. + if (name) { + iframe.name = name; + } + document.body.append(iframe); // Intentionally not including the following: @@ -65,3 +71,19 @@ window.insertIframe = (t, url) => { // Doing so breaks some of the testdriver.js tests with "cannot find window" errors. return iframe; }; + +// TODO(domenic): clean up other tests in the parent directory to use this. +window.absoluteURL = relativeURL => { + return (new URL(relativeURL, location.href)).href; +}; + +// TODO(domenic): clean up other tests in the parent directory to use this. +window.codeInjectorURL = code => { + return absoluteURL("resources/code-injector.html?pipe=sub(none)&code=" + encodeURIComponent(code)); +}; + +window.changeURLHost = (url, newHost) => { + const urlObj = new URL(url); + urlObj.host = newHost; + return urlObj.href; +}; diff --git a/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/resources/slow-message-source-with-history-and-location.html b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/resources/slow-message-source-with-history-and-location.html new file mode 100644 index 00000000000..da279ebf82f --- /dev/null +++ b/tests/wpt/web-platform-tests/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/resources/slow-message-source-with-history-and-location.html @@ -0,0 +1,16 @@ + + +Subframe or popup + + + + + diff --git a/tests/wpt/web-platform-tests/html/canvas/element/fill-and-stroke-styles/2d.gradient.object.update.html b/tests/wpt/web-platform-tests/html/canvas/element/fill-and-stroke-styles/2d.gradient.object.update.html index b54b110c5f8..6f363177e3e 100644 --- a/tests/wpt/web-platform-tests/html/canvas/element/fill-and-stroke-styles/2d.gradient.object.update.html +++ b/tests/wpt/web-platform-tests/html/canvas/element/fill-and-stroke-styles/2d.gradient.object.update.html @@ -23,6 +23,7 @@ var g = ctx.createLinearGradient(-100, 0, 200, 0); g.addColorStop(0, '#f00'); g.addColorStop(1, '#f00'); ctx.fillStyle = g; +ctx.fillRect(0, 0, 100, 50); g.addColorStop(0.1, '#0f0'); g.addColorStop(0.9, '#0f0'); ctx.fillRect(0, 0, 100, 50); diff --git a/tests/wpt/web-platform-tests/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.object.update.html b/tests/wpt/web-platform-tests/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.object.update.html index 05f8e747f2f..175c3a215b7 100644 --- a/tests/wpt/web-platform-tests/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.object.update.html +++ b/tests/wpt/web-platform-tests/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.object.update.html @@ -24,6 +24,7 @@ var g = ctx.createLinearGradient(-100, 0, 200, 0); g.addColorStop(0, '#f00'); g.addColorStop(1, '#f00'); ctx.fillStyle = g; +ctx.fillRect(0, 0, 100, 50); g.addColorStop(0.1, '#0f0'); g.addColorStop(0.9, '#0f0'); ctx.fillRect(0, 0, 100, 50); diff --git a/tests/wpt/web-platform-tests/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.object.update.worker.js b/tests/wpt/web-platform-tests/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.object.update.worker.js index 5960d0afe9f..76721140392 100644 --- a/tests/wpt/web-platform-tests/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.object.update.worker.js +++ b/tests/wpt/web-platform-tests/html/canvas/offscreen/fill-and-stroke-styles/2d.gradient.object.update.worker.js @@ -20,6 +20,7 @@ var g = ctx.createLinearGradient(-100, 0, 200, 0); g.addColorStop(0, '#f00'); g.addColorStop(1, '#f00'); ctx.fillStyle = g; +ctx.fillRect(0, 0, 100, 50); g.addColorStop(0.1, '#0f0'); g.addColorStop(0.9, '#0f0'); ctx.fillRect(0, 0, 100, 50); diff --git a/tests/wpt/web-platform-tests/html/canvas/tools/yaml/element/fill-and-stroke-styles.yaml b/tests/wpt/web-platform-tests/html/canvas/tools/yaml/element/fill-and-stroke-styles.yaml index fe7b8841ae9..9d35dde661c 100644 --- a/tests/wpt/web-platform-tests/html/canvas/tools/yaml/element/fill-and-stroke-styles.yaml +++ b/tests/wpt/web-platform-tests/html/canvas/tools/yaml/element/fill-and-stroke-styles.yaml @@ -452,6 +452,7 @@ g.addColorStop(0, '#f00'); g.addColorStop(1, '#f00'); ctx.fillStyle = g; + ctx.fillRect(0, 0, 100, 50); g.addColorStop(0.1, '#0f0'); g.addColorStop(0.9, '#0f0'); ctx.fillRect(0, 0, 100, 50); diff --git a/tests/wpt/web-platform-tests/html/canvas/tools/yaml/offscreen/fill-and-stroke-styles.yaml b/tests/wpt/web-platform-tests/html/canvas/tools/yaml/offscreen/fill-and-stroke-styles.yaml index 9d34588c100..a0eca74922e 100644 --- a/tests/wpt/web-platform-tests/html/canvas/tools/yaml/offscreen/fill-and-stroke-styles.yaml +++ b/tests/wpt/web-platform-tests/html/canvas/tools/yaml/offscreen/fill-and-stroke-styles.yaml @@ -292,6 +292,7 @@ g.addColorStop(0, '#f00'); g.addColorStop(1, '#f00'); ctx.fillStyle = g; + ctx.fillRect(0, 0, 100, 50); g.addColorStop(0.1, '#0f0'); g.addColorStop(0.9, '#0f0'); ctx.fillRect(0, 0, 100, 50); diff --git a/tests/wpt/web-platform-tests/html/semantics/forms/constraints/form-validation-validity-patternMismatch.html b/tests/wpt/web-platform-tests/html/semantics/forms/constraints/form-validation-validity-patternMismatch.html index c21271c8fcc..286001b965e 100644 --- a/tests/wpt/web-platform-tests/html/semantics/forms/constraints/form-validation-validity-patternMismatch.html +++ b/tests/wpt/web-platform-tests/html/semantics/forms/constraints/form-validation-validity-patternMismatch.html @@ -17,14 +17,15 @@ {conditions: {pattern: null, value: "abc"}, expected: false, name: "[target] The pattern attribute is not set"}, {conditions: {pattern: "[A-Z]+", value: ""}, expected: false, name: "[target] The value attibute is empty string"}, {conditions: {pattern: "[A-Z]{1}", value: "A"}, expected: false, name: "[target] The value attribute matches the pattern attribute"}, - {conditions: {pattern: "[A-Z]+", value: "\u0041\u0042\u0043"}, expected: false, name: "[target] The value(ABC) in unicode attribute matches the pattern attribute"}, + {conditions: {pattern: "[A-Z]+", value: "\x41\x42\x43"}, expected: false, name: "[target] The value(ABC) in unicode attribute matches the pattern attribute"}, {conditions: {pattern: "[a-z]{3,}", value: "ABCD"}, expected: true, name: "[target] The value attribute mismatches the pattern attribute"}, {conditions: {pattern: "[A-Z]+", value: "ABC123"}, expected: true, name: "[target] The value attribute mismatches the pattern attribute even when a subset matches"}, {conditions: {pattern: "(abc", value: "de"}, expected: false, name: "[target] Invalid regular expression gets ignored"}, + {conditions: {pattern: "[(]", value: "x"}, expected: false, name: "[target] Invalid `v` regular expression gets ignored"}, {conditions: {pattern: "a)(b", value: "de"}, expected: false, name: "[target] The pattern attribute tries to escape a group"}, {conditions: {pattern: "a\\u{10FFFF}", value: "a\u{10FFFF}"}, expected: false, name: "[target] The pattern attribute uses Unicode features"}, - {conditions: {pattern: "\\u1234\\cx[5-[]{2}", value: "\u1234\x18[6"}, expected: false, name: "[target] The value attribute matches JavaScript-specific regular expression"}, - {conditions: {pattern: "\\u1234\\cx[5-[]{2}", value: "\u1234\x18[4"}, expected: true, name: "[target] The value attribute mismatches JavaScript-specific regular expression"}, + {conditions: {pattern: "\\u1234\\cx[5-\\[]{2}", value: "\u1234\x18[6"}, expected: false, name: "[target] The value attribute matches JavaScript-specific regular expression"}, + {conditions: {pattern: "\\u1234\\cx[5-\\[]{2}", value: "\u1234\x18[4"}, expected: true, name: "[target] The value attribute mismatches JavaScript-specific regular expression"}, ] }, { @@ -34,14 +35,15 @@ {conditions: {multiple: true, pattern: null, value: "abc,abc"}, expected: false, name: "[target] The pattern attribute is not set, if multiple is present"}, {conditions: {multiple: true, pattern: "[A-Z]+", value: ""}, expected: false, name: "[target] The value attibute is empty string, if multiple is present"}, {conditions: {multiple: true, pattern: "[A-Z]{1}", value: "A,A"}, expected: false, name: "[target] The value attribute matches the pattern attribute, if multiple is present"}, - {conditions: {multiple: true, pattern: "[A-Z]+", value: "\u0041\u0042\u0043,\u0041\u0042\u0043"}, expected: false, name: "[target] The value(ABC) in unicode attribute matches the pattern attribute, if multiple is present"}, + {conditions: {multiple: true, pattern: "[A-Z]+", value: "\x41\x42\x43,\x41\x42\x43"}, expected: false, name: "[target] The value(ABC) in unicode attribute matches the pattern attribute, if multiple is present"}, {conditions: {multiple: true, pattern: "[a-z]{3,}", value: "abcd,ABCD"}, expected: true, name: "[target] The value attribute mismatches the pattern attribute, if multiple is present"}, {conditions: {multiple: true, pattern: "[A-Z]+", value: "ABCD,ABC123"}, expected: true, name: "[target] The value attribute mismatches the pattern attribute even when a subset matches, if multiple is present"}, {conditions: {multiple: true, pattern: "(abc", value: "de,de"}, expected: false, name: "[target] Invalid regular expression gets ignored, if multiple is present"}, + {conditions: {multiple: true, pattern: "[(]", value: "x"}, expected: false, name: "[target] Invalid `v` regular expression gets ignored, if multiple is present"}, {conditions: {multiple: true, pattern: "a)(b", value: "de,de"}, expected: false, name: "[target] The pattern attribute tries to escape a group, if multiple is present"}, {conditions: {multiple: true, pattern: "a\\u{10FFFF}", value: "a\u{10FFFF},a\u{10FFFF}"}, expected: false, name: "[target] The pattern attribute uses Unicode features, if multiple is present"}, - {conditions: {multiple: true, pattern: "\\u1234\\cx[5-[]{2}", value: "\u1234\x18[6,\u1234\x18[Z"}, expected: false, name: "[target] The value attribute matches JavaScript-specific regular expression, if multiple is present"}, - {conditions: {multiple: true, pattern: "\\u1234\\cx[5-[]{2}", value: "\u1234\x18[4,\u1234\x18[6"}, expected: true, name: "[target] The value attribute mismatches JavaScript-specific regular expression, if multiple is present"}, + {conditions: {multiple: true, pattern: "\\u1234\\cx[5-\\[]{2}", value: "\u1234\x18[6,\u1234\x18[Z"}, expected: false, name: "[target] The value attribute matches JavaScript-specific regular expression, if multiple is present"}, + {conditions: {multiple: true, pattern: "\\u1234\\cx[5-\\[]{2}", value: "\u1234\x18[4,\u1234\x18[6"}, expected: true, name: "[target] The value attribute mismatches JavaScript-specific regular expression, if multiple is present"}, {conditions: {multiple: true, pattern: "a,", value: "a,"}, expected: true, name: "[target] Commas should be stripped from regex input, if multiple is present"}, ] } diff --git a/tests/wpt/web-platform-tests/html/semantics/forms/the-input-element/pattern_attribute.html b/tests/wpt/web-platform-tests/html/semantics/forms/the-input-element/pattern_attribute.html index ad9a4a4312c..93cbd2caeca 100644 --- a/tests/wpt/web-platform-tests/html/semantics/forms/the-input-element/pattern_attribute.html +++ b/tests/wpt/web-platform-tests/html/semantics/forms/the-input-element/pattern_attribute.html @@ -11,8 +11,45 @@

pattern attribute

+ - + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
diff --git a/tests/wpt/web-platform-tests/html/semantics/forms/the-input-element/selection-pointer.html b/tests/wpt/web-platform-tests/html/semantics/forms/the-input-element/selection-pointer.html index 8cb0ead4414..7f06ae24a2d 100644 --- a/tests/wpt/web-platform-tests/html/semantics/forms/the-input-element/selection-pointer.html +++ b/tests/wpt/web-platform-tests/html/semantics/forms/the-input-element/selection-pointer.html @@ -37,8 +37,20 @@ for (const inputType of inputVisibleTypes) { .pointerMove(0, 0, {origin: bar}) .pointerUp() .send(); - assert_equals(selection.anchorNode, foo.childNodes[0], "anchorNode"); - assert_equals(selection.focusNode, bar.childNodes[0], "focusNode"); + const nRanges = selection.rangeCount; + assert_true(nRanges > 0); + const expectedStart = foo.childNodes[0]; + const expectedEnd = bar.childNodes[0]; + if (nRanges === 1) { + assert_equals(selection.anchorNode, expectedStart, "anchorNode"); + assert_equals(selection.focusNode, expectedEnd, "focusNode"); + } else { + // In case multiple ranges are supported, make sure the set of ranges + // spans the full selection, across the input. + const ranges = [...Array(nRanges).keys()].map(n => selection.getRangeAt(n)); + assert_true(ranges.some(r => r.startContainer === expectedStart),"startContainer"); + assert_true(ranges.some(r => r.endContainer === expectedEnd),"endContainer"); + } }, `Selecting texts across should not cancel selection`); } diff --git a/tests/wpt/web-platform-tests/html/semantics/popovers/popover-change-type.html b/tests/wpt/web-platform-tests/html/semantics/popovers/popover-change-type.html new file mode 100644 index 00000000000..978d1d14956 --- /dev/null +++ b/tests/wpt/web-platform-tests/html/semantics/popovers/popover-change-type.html @@ -0,0 +1,42 @@ + + + + + + + + + + +
popover
+ + diff --git a/tests/wpt/web-platform-tests/html/semantics/popovers/popover-light-dismiss.html b/tests/wpt/web-platform-tests/html/semantics/popovers/popover-light-dismiss.html index 5800b7bc4d4..f913aaa357e 100644 --- a/tests/wpt/web-platform-tests/html/semantics/popovers/popover-light-dismiss.html +++ b/tests/wpt/web-platform-tests/html/semantics/popovers/popover-light-dismiss.html @@ -380,7 +380,7 @@ await sendTab(); assert_equals(document.activeElement,popover8Anchor,'Focus should move to the anchor element'); assert_true(popover8.matches(':popover-open'),'popover should stay open'); - popover8.hidePopover(); + popover8.hidePopover(); // Cleanup },'Moving focus back to the anchor element should not dismiss the popover'); @@ -534,6 +534,7 @@ promise_test(async () => { assert_true(p13.matches(':popover-open'),'p13 should still be open'); assert_false(p14.matches(':popover-open')); assert_false(p15.matches(':popover-open')); + p13.hidePopover(); // Cleanup },'Hide the target popover during "hide all popovers until"'); @@ -546,11 +547,16 @@ promise_test(async () => { promise_test(async () => { p16.showPopover(); p18.showPopover(); + let events = []; + const logEvents = (e) => {events.push(`${e.newState==='open' ? 'show' : 'hide'} ${e.target.id}`)}; + p16.addEventListener('beforetoggle', logEvents); + p17.addEventListener('beforetoggle', logEvents); p18.addEventListener('beforetoggle', (e) => { - if (e.newState === "closed") - p17.showPopover(); - },{once:true}); + logEvents(e); + p17.showPopover(); + }); p16.hidePopover(); + assert_array_equals(events,['hide p18','show p17','hide p16'],'There should not be a hide event for p17'); assert_false(p16.matches(':popover-open')); assert_false(p17.matches(':popover-open')); assert_false(p18.matches(':popover-open')); @@ -564,15 +570,20 @@ promise_test(async () => { diff --git a/tests/wpt/web-platform-tests/html/semantics/popovers/resources/popover-utils.js b/tests/wpt/web-platform-tests/html/semantics/popovers/resources/popover-utils.js index 04d2a2cbe75..ee69ca1e016 100644 --- a/tests/wpt/web-platform-tests/html/semantics/popovers/resources/popover-utils.js +++ b/tests/wpt/web-platform-tests/html/semantics/popovers/resources/popover-utils.js @@ -13,7 +13,7 @@ async function clickOn(element) { async function sendTab() { await waitForRender(); const kTab = '\uE004'; - await new test_driver.send_keys(document.body,kTab); + await new test_driver.send_keys(document.documentElement,kTab); await waitForRender(); } // Waiting for crbug.com/893480: @@ -31,12 +31,12 @@ async function sendTab() { // } async function sendEscape() { await waitForRender(); - await new test_driver.send_keys(document.body,'\uE00C'); // Escape + await new test_driver.send_keys(document.documentElement,'\uE00C'); // Escape await waitForRender(); } async function sendEnter() { await waitForRender(); - await new test_driver.send_keys(document.body,'\uE007'); // Enter + await new test_driver.send_keys(document.documentElement,'\uE007'); // Enter await waitForRender(); } function isElementVisible(el) { diff --git a/tests/wpt/web-platform-tests/inert/inert-pseudo-element-hittest.html b/tests/wpt/web-platform-tests/inert/inert-pseudo-element-hittest.html index bdba7696038..8268f02aa24 100644 --- a/tests/wpt/web-platform-tests/inert/inert-pseudo-element-hittest.html +++ b/tests/wpt/web-platform-tests/inert/inert-pseudo-element-hittest.html @@ -36,8 +36,9 @@ async function mouseDownAndGetEvents(test) { }, { once: true, capture: true }); } + let targetRect = target.getBoundingClientRect(); await new test_driver.Actions() - .pointerMove(0, 0, { origin: target }) + .pointerMove(targetRect.x + 1, targetRect.y + 1, { origin: "viewport" }) .pointerDown() .send(); test.add_cleanup(() => test_driver.click(document.body)); diff --git a/tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/testdriver/actions/wheelScroll.html.ini b/tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/testdriver/actions/wheelScroll.html.ini index 5632dcf1129..cfa28e9b46c 100644 --- a/tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/testdriver/actions/wheelScroll.html.ini +++ b/tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/testdriver/actions/wheelScroll.html.ini @@ -1,3 +1,3 @@ [wheelScroll.html] expected: - if product == "epiphany": ERROR + if product == "epiphany" or product == "safari": ERROR diff --git a/tests/wpt/web-platform-tests/lint.ignore b/tests/wpt/web-platform-tests/lint.ignore index cda77f4df8c..6f8ec10470b 100644 --- a/tests/wpt/web-platform-tests/lint.ignore +++ b/tests/wpt/web-platform-tests/lint.ignore @@ -367,8 +367,6 @@ SET TIMEOUT: common/rendering-utils.js SET TIMEOUT: acid/acid3/test.html # Third party code -*: css/tools/apiclient/* -*: css/tools/w3ctestlib/* *: resources/webidl2/* *: tools/* *: */third_party/* @@ -380,9 +378,6 @@ SET TIMEOUT: acid/acid3/test.html *: resources/.gitignore *: webaudio/.gitignore -# Build system virtualenv -*: css/tools/_virtualenv/* - ## Third party data files TRAILING WHITESPACE: resources/chromium/* @@ -395,36 +390,6 @@ PRINT STATEMENT: css/* CONTENT-VISUAL: css/* CONTENT-MANUAL: css/* -## Support files not in /support/ or similar -SUPPORT-WRONG-DIR: css/README.md -SUPPORT-WRONG-DIR: css/*/reftest.list -SUPPORT-WRONG-DIR: css/*/README -SUPPORT-WRONG-DIR: css/*/README.md -SUPPORT-WRONG-DIR: css/*-README -SUPPORT-WRONG-DIR: css/*/LICENSE -SUPPORT-WRONG-DIR: css/*/LICENSE-* -SUPPORT-WRONG-DIR: css/*/Makefile - -# The selectors-3 testsuite has a weird build system -SUPPORT-WRONG-DIR: css/selectors/* - -# Things we should fix -SUPPORT-WRONG-DIR: css/css-animations/animationevent-interface.js -SUPPORT-WRONG-DIR: css/css-backgrounds/justfortest.html -SUPPORT-WRONG-DIR: css/css-backgrounds/background-attachment-local/aqua-yellow-32x32.png -SUPPORT-WRONG-DIR: css/css-backgrounds/background-clip/list.txt -SUPPORT-WRONG-DIR: css/css-backgrounds/background-origin/list.txt -SUPPORT-WRONG-DIR: css/css-color/htaccess -SUPPORT-WRONG-DIR: css/css-fonts/font-variant-debug.html -SUPPORT-WRONG-DIR: css/css-masking/clip-path/svg-clipPath.svg -SUPPORT-WRONG-DIR: css/css-multicol/multicol-red.png -SUPPORT-WRONG-DIR: css/CSS2/section-index.xht -SUPPORT-WRONG-DIR: css/CSS2/other-formats/xml/background-18.css -SUPPORT-WRONG-DIR: css/CSS2/other-formats/xml/background-19-alt.xml -SUPPORT-WRONG-DIR: css/CSS2/other-formats/xml/background-19.css -SUPPORT-WRONG-DIR: css/WOFF2/testcaseindex.xht - - ## Whitespace rules that we can't enforce yet INDENT TABS: css/compositing/* INDENT TABS: css/CSS2/* @@ -462,6 +427,9 @@ TRAILING WHITESPACE: css/css-fonts/support/fonts/gsubtest-lookup3.ufo/features.f SET TIMEOUT: css/compositing/mix-blend-mode/mix-blend-mode-parent-with-3D-transform-and-transition.html SET TIMEOUT: css/compositing/mix-blend-mode/mix-blend-mode-sibling-with-3D-transform-and-transition.html +SET TIMEOUT: css/css-backgrounds/color-mix-currentcolor-border-repaint-parent.html +SET TIMEOUT: css/css-backgrounds/color-mix-currentcolor-border-repaint.html +SET TIMEOUT: css/css-backgrounds/currentcolor-border-repaint-parent.html SET TIMEOUT: css/css-transitions/events-007.html SET TIMEOUT: css/css-transitions/support/generalParallelTest.js SET TIMEOUT: css/css-transitions/support/runParallelAsyncHarness.js @@ -512,166 +480,13 @@ SET TIMEOUT: css/CSS2/selectors/dom-hover-002.xht SET TIMEOUT: css/CSS2/tables/tables-102.xht SET TIMEOUT: css/mediaqueries/min-width-tables-001.html SET TIMEOUT: css/css-text/crashtests/rendering-rtl-bidi-override-crash.html +SET TIMEOUT: css/css-backgrounds/color-mix-currentcolor-border-repaint-parent.html +SET TIMEOUT: svg/painting/color-mix-currentcolor-fill-stroke-repaint.html +SET TIMEOUT: svg/painting/currentcolor-fill-stroke-repaint.html SET TIMEOUT: resource-timing/resources/run-async-tasks-promise.js -## Build system stuff -CSS-COLLIDING-SUPPORT-NAME: css/*/README -CSS-COLLIDING-SUPPORT-NAME: css/*/LOCK - -# These are all the current "merge mismatch" errors the build system produces -CSS-COLLIDING-SUPPORT-NAME: css/css-flexbox/support/200x200-green.png -CSS-COLLIDING-SUPPORT-NAME: css/css-grid/grid-items/support/200x200-green.png -CSS-COLLIDING-SUPPORT-NAME: css/css-sizing/aspect-ratio/support/200x200-green.png -CSS-COLLIDING-SUPPORT-NAME: css/css-backgrounds/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-multicol/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-transitions/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/backgrounds/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-backgrounds/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-fonts/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-multicol/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-page/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-transitions/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/backgrounds/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-flexbox/support/solidblue.png -CSS-COLLIDING-SUPPORT-NAME: css/css-writing-modes/support/swatch-fuchsia.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/support/swatch-fuchsia.png - -# More duplicated copies of the above -CSS-COLLIDING-SUPPORT-NAME: css/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/floats-clear/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/media/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/cssom-view/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/syntax/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/fonts/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/cascade/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-transforms/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/cssom/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-style-attr/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/borders/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/zindex/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/text/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-values/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/margin-padding-clear/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-text/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/box-display/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/colors/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/lists/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/filter-effects/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/selectors/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/values/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-shapes/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/tables/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/bidi-text/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/css1/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/ui/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/normal-flow/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-images/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/generated-content/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/css-flexbox/support/pattern-rgr-grg-rgr.png -CSS-COLLIDING-SUPPORT-NAME: css/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-fonts/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-transforms/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/cssom-view/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/fonts/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/selectors/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-shapes/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/ui/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/normal-flow/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/margin-padding-clear/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/syntax/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/zindex/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/colors/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/cascade/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/bidi-text/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-style-attr/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/lists/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-flexbox/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/filter-effects/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/borders/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-text/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/text/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/box-display/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/media/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-values/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-page/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/cssom/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/css1/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/floats-clear/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/generated-content/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/css-images/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/tables/support/pattern-grg-rgr-grg.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/values/support/pattern-grg-rgr-grg.png - -# Duplicate filename not picked up by the build system -# https:css///github.com/w3c/csswg-test/issues/1236 -CSS-COLLIDING-REF-NAME: css/css-masking/clip-path-svg-content/reference/clip-path-square-001-ref.svg -CSS-COLLIDING-REF-NAME: css/css-masking/clip-path/reference/clip-path-square-001-ref.html -CSS-COLLIDING-REF-NAME: css/css-masking/clip-path-svg-content/reference/clip-path-square-002-ref.svg -CSS-COLLIDING-REF-NAME: css/css-masking/clip-path/reference/clip-path-square-002-ref.html - -# Duplicate filename where there's no actual merging -# (i.e., we're being more aggressive than the build system at forbidding it) -CSS-COLLIDING-REF-NAME: css/CSS2/text/text-transform-lowercase-001-ref.xht -CSS-COLLIDING-REF-NAME: css/css-text/text-transform/reference/text-transform-lowercase-001-ref.xht -CSS-COLLIDING-REF-NAME: css/CSS2/text/text-transform-capitalize-003-ref.xht -CSS-COLLIDING-REF-NAME: css/css-text/text-transform/reference/text-transform-capitalize-003-ref.html -CSS-COLLIDING-REF-NAME: css/CSS2/text/text-transform-capitalize-001-ref.xht -CSS-COLLIDING-REF-NAME: css/css-text/text-transform/reference/text-transform-capitalize-001-ref.html -CSS-COLLIDING-REF-NAME: css/css-pseudo/first-letter-001-ref.html -CSS-COLLIDING-REF-NAME: css/CSS2/selectors/first-letter-001-ref.xht -CSS-COLLIDING-REF-NAME: css/CSS2/text/text-transform-uppercase-001-ref.xht -CSS-COLLIDING-REF-NAME: css/css-text/text-transform/reference/text-transform-uppercase-001-ref.xht -CSS-COLLIDING-REF-NAME: css/CSS2/visufx/overflow-applies-to-001-ref.xht -CSS-COLLIDING-REF-NAME: css/CSS2/ui/overflow-applies-to-001-ref.xht -CSS-COLLIDING-REF-NAME: css/CSS2/visuren/inline-formatting-context-001-ref.xht -CSS-COLLIDING-REF-NAME: css/CSS2/linebox/inline-formatting-context-001-ref.xht -CSS-COLLIDING-REF-NAME: css/css-flexbox/reference/percentage-size-subitems-001-ref.html -CSS-COLLIDING-REF-NAME: css/css-grid/grid-items/percentage-size-subitems-001-ref.html -CSS-COLLIDING-SUPPORT-NAME: css/css-backgrounds/support/red.png -CSS-COLLIDING-SUPPORT-NAME: css/compositing/mix-blend-mode/support/red.png -CSS-COLLIDING-SUPPORT-NAME: css/compositing/background-blending/support/red.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/normal-flow/support/replaced-min-max-3.png -CSS-COLLIDING-SUPPORT-NAME: css/css-sizing/support/replaced-min-max-3.png -CSS-COLLIDING-SUPPORT-NAME: css/css-backgrounds/background-size/support/50x50-green.png -CSS-COLLIDING-SUPPORT-NAME: css/css-backgrounds/support/50x50-green.png -CSS-COLLIDING-SUPPORT-NAME: css/css-grid/grid-items/support/50x50-green.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/support/50x50-green.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/ui/support/animated.gif -CSS-COLLIDING-SUPPORT-NAME: css/css-grid/alignment/support/50x50-green.png -CSS-COLLIDING-SUPPORT-NAME: css/css-grid/alignment/support/25x50-green.png -CSS-COLLIDING-SUPPORT-NAME: css/css-grid/grid-items/support/25x50-green.png -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/backgrounds/support/animated.gif -CSS-COLLIDING-SUPPORT-NAME: css/css-shapes/shape-outside/shape-image/support/animated.gif -CSS-COLLIDING-SUPPORT-NAME: css/css-display/support/util.js -CSS-COLLIDING-SUPPORT-NAME: css/CSS2/normal-flow/support/replaced-min-max-1.png -CSS-COLLIDING-SUPPORT-NAME: css/css-sizing/support/replaced-min-max-1.png -CSS-COLLIDING-REF-NAME: css/css-multicol/baseline-001-ref.html -CSS-COLLIDING-REF-NAME: css/css-grid/subgrid/baseline-001-ref.html -CSS-COLLIDING-REF-NAME: css/css-backgrounds/simple-bg-color-ref.html -CSS-COLLIDING-REF-NAME: css/css-backgrounds/hidpi/simple-bg-color-ref.html - -CSS-COLLIDING-TEST-NAME: css/css-contain/content-visibility/inheritance.html -CSS-COLLIDING-TEST-NAME: css/css-contain/inheritance.html -CSS-COLLIDING-TEST-NAME: css/css-grid/grid-items/replaced-element-001.html -CSS-COLLIDING-TEST-NAME: css/css-grid/grid-items/replaced-element-002.html -CSS-COLLIDING-TEST-NAME: css/css-grid/grid-items/replaced-element-007.html -CSS-COLLIDING-TEST-NAME: css/css-grid/grid-items/replaced-element-010.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/aspect-ratio/parsing/contain-intrinsic-size-computed.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/aspect-ratio/parsing/contain-intrinsic-size-invalid.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/aspect-ratio/parsing/contain-intrinsic-size-valid.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/aspect-ratio/replaced-element-001.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/aspect-ratio/replaced-element-002.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/aspect-ratio/replaced-element-007.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/aspect-ratio/replaced-element-010.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/contain-intrinsic-size/parsing/contain-intrinsic-size-computed.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/contain-intrinsic-size/parsing/contain-intrinsic-size-invalid.html -CSS-COLLIDING-TEST-NAME: css/css-sizing/contain-intrinsic-size/parsing/contain-intrinsic-size-valid.html - # CSS tests that used to be at the top level and weren't subject to lints MISSING-LINK: css/css-fonts/matching/fixed-stretch-style-over-weight.html -SUPPORT-WRONG-DIR: css/css-fonts/matching/font-matching.css MISSING-LINK: css/css-fonts/matching/stretch-distance-over-weight-distance.html MISSING-LINK: css/css-fonts/matching/style-ranges-over-weight-direction.html MISSING-LINK: css/css-fonts/variations/font-parse-numeric-stretch-style-weight.html @@ -697,10 +512,8 @@ MISSING-LINK: css/css-scroll-anchoring/position-change-heuristic.html MISSING-LINK: css/css-scroll-anchoring/start-edge-in-block-layout-direction.html MISSING-LINK: css/css-scroll-anchoring/subtree-exclusion.html MISSING-LINK: css/css-scroll-anchoring/wrapped-text.html -SUPPORT-WRONG-DIR: css/css-easing/testcommon.js MISSING-LINK: css/css-typed-om/CSSMatrixComponent-DOMMatrix-mutable.html MISSING-LINK: css/css-typed-om/declared-styleMap-accepts-inherit.html -SUPPORT-WRONG-DIR: css/cssom/stylesheet-same-origin.css MISSING-LINK: css/cssom-view/DOMRectList.html MISSING-LINK: css/cssom-view/elementFromPoint-002.html MISSING-LINK: css/cssom-view/elementFromPoint-003.html @@ -715,7 +528,6 @@ MISSING-LINK: css/cssom-view/elementsFromPoint-table.html MISSING-LINK: css/cssom-view/elementsFromPoint.html MISSING-LINK: css/cssom-view/historical.html MISSING-LINK: css/cssom-view/HTMLBody-ScrollArea_quirksmode.html -SUPPORT-WRONG-DIR: css/cssom-view/iframe.html MISSING-LINK: css/cssom-view/mouseEvent.html MISSING-LINK: css/cssom-view/negativeMargins.html MISSING-LINK: css/cssom-view/offsetTopLeftInScrollableParent.html @@ -857,9 +669,6 @@ DUPLICATE-BASENAME-PATH: svg/struct/reftests/reference/green-100x100.svg SET TIMEOUT: mediacapture-insertable-streams/MediaStreamTrackProcessor-video.https.html -CSS-COLLIDING-REF-NAME: css/css-backgrounds/reference/background-image-001-ref.html -CSS-COLLIDING-REF-NAME: css/css-break/background-image-001-ref.html - # Ported crashtests from Mozilla SET TIMEOUT: editing/crashtests/backcolor-in-nested-editing-host-td-from-DOMAttrModified.html SET TIMEOUT: editing/crashtests/contenteditable-will-be-blurred-by-focus-event-listener.html diff --git a/tests/wpt/web-platform-tests/long-animation-frame/tentative/loaf-blocking-duration.html b/tests/wpt/web-platform-tests/long-animation-frame/tentative/loaf-blocking-duration.html index 3514d413e9e..1671a386acb 100644 --- a/tests/wpt/web-platform-tests/long-animation-frame/tentative/loaf-blocking-duration.html +++ b/tests/wpt/web-platform-tests/long-animation-frame/tentative/loaf-blocking-duration.html @@ -14,37 +14,44 @@ function loaf_blocking_duration_test(run, label) { const OVERHEAD_EPSILON = 5; const BLOCKING_THRESHOLD = 50; promise_test(async t => { - const longtask_promise = new Promise(resolve => new PerformanceObserver( + let found = false; + for (let i = 0; i < 10 && !found; ++i) { + const longtask_promise = new Promise(resolve => new PerformanceObserver( (entries, observer) => { resolve(entries.getEntries()); observer.disconnect(); - }).observe({entryTypes: ["longtask"]})); - const [longtask_entries, loaf_entry] = await Promise.all( - [longtask_promise, expect_long_frame(run, t)]); - const overlapping = longtask_entries.filter(longtask => - (longtask.startTime >= loaf_entry.startTime && - longtask.startTime < (loaf_entry.startTime + loaf_entry.duration) && - (!loaf_entry.renderStart || - (longtask.startTime < loaf_entry.renderStart - OVERHEAD_EPSILON)))); + }).observe({entryTypes: ["longtask"]})); + const [longtask_entries, loaf_entry] = await Promise.all( + [longtask_promise, expect_long_frame(run, t)]); + const overlapping = longtask_entries.filter(longtask => + (longtask.startTime >= loaf_entry.startTime && + longtask.startTime < (loaf_entry.startTime + loaf_entry.duration) && + (!loaf_entry.renderStart || + (longtask.startTime < loaf_entry.renderStart - OVERHEAD_EPSILON)))); - const longest_index = overlapping.reduce( - (max, cur, i) => cur > overlapping[max] ? i : max, 0); - let expected_blocking_duration = 0; - overlapping.forEach(({duration}, i) => { - if (i === longest_index && loaf_entry.renderStart) - duration += loaf_entry.startTime + loaf_entry.duration - - loaf_entry.renderStart; - expected_blocking_duration += Math.max(0, duration - BLOCKING_THRESHOLD); - }); + const longest_index = overlapping.reduce( + (max, cur, i) => cur > overlapping[max] ? i : max, 0); + let expected_blocking_duration = 0; + overlapping.forEach(({duration}, i) => { + if (i === longest_index && loaf_entry.renderStart) + duration += loaf_entry.startTime + loaf_entry.duration - + loaf_entry.renderStart; + expected_blocking_duration += Math.max(0, duration - BLOCKING_THRESHOLD); + }); - if (!overlapping.length && loaf_entry.renderStart) - expected_blocking_duration = - Math.max(0, - loaf_entry.startTime + loaf_entry.duration - loaf_entry.renderStart - - BLOCKING_THRESHOLD); - assert_approx_equals(loaf_entry.blockingDuration, - expected_blocking_duration, - OVERHEAD_EPSILON); + if (!overlapping.length && loaf_entry.renderStart) { + expected_blocking_duration = + Math.max(0, + loaf_entry.startTime + loaf_entry.duration - loaf_entry.renderStart - + BLOCKING_THRESHOLD); + } + + if (Math.abs(loaf_entry.blockingDuration - expected_blocking_duration) < + OVERHEAD_EPSILON) { + found = true; + } + } + assert_true(found); }, `LoAF blockingDuration should be equivalent to long tasks: ${label}`); } diff --git a/tests/wpt/web-platform-tests/long-animation-frame/tentative/loaf-script-window-attribution.html b/tests/wpt/web-platform-tests/long-animation-frame/tentative/loaf-script-window-attribution.html index 001bb537f79..f54a1f23cb8 100644 --- a/tests/wpt/web-platform-tests/long-animation-frame/tentative/loaf-script-window-attribution.html +++ b/tests/wpt/web-platform-tests/long-animation-frame/tentative/loaf-script-window-attribution.html @@ -25,6 +25,8 @@ promise_test (async t => { }, 'Scripts in this window should be self-attributed'); promise_test (async t => { + let found = false; + for (let i = 0; i < 10 && !found; ++i) { const [executor, iframe] = await prepare_exec_iframe(t, ORIGIN); const [entry, script] = await expect_long_frame_with_script(() => executor.execute_script(async (duration) => { @@ -32,11 +34,18 @@ promise_test (async t => { const deadline = performance.now() + duration; while (performance.now() < deadline) {} }, [very_long_frame_duration]), () => true, t); - assert_equals(script.windowAttribution, "descendant"); - assert_equals(script.window, iframe.contentWindow); + + if (script.windowAttribution === "descendant" && script.window === iframe.contentWindow) { + found = true; + } + } + + assert_true(found); }, 'Scripts in subframes should be descendant-attributed'); promise_test (async t => { + let found = false; + for (let i = 0; i < 10 && !found; ++i) { const [executor1, iframe1] = await prepare_exec_iframe(t, ORIGIN); const [executor2, iframe2] = await prepare_exec_iframe(t, ORIGIN); const [entry, script] = await expect_long_frame_with_script(() => @@ -52,10 +61,15 @@ promise_test (async t => { const iframe1_entry = find_entry(iframe1.contentWindow); const iframe2_entry = find_entry(iframe2.contentWindow); - assert_equals(iframe1_entry.windowAttribution, "self"); - assert_equals(iframe2_entry.windowAttribution, "same-page"); - assert_equals(iframe1_entry.window, iframe1.contentWindow); - assert_equals(iframe2_entry.window, iframe1.contentWindow); + if (iframe1_entry.windowAttribution === "self" && + iframe2_entry.windowAttribution === "same-page" && + iframe1_entry.window === iframe1.contentWindow && + iframe2_entry.window === iframe1.contentWindow) { + found = true; + } + } + + assert_true(found); }, 'Scripts in subframes should be same-page-attributed to other subframes'); diff --git a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-camera.https.html b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-camera.https.html index 1bb086daddd..9e8b7a6f36e 100644 --- a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-camera.https.html +++ b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-camera.https.html @@ -1,14 +1,14 @@ -enumerateDevices: test enumerateDevices should not expose camera devices if they are not allowed to use +enumerateDevices: test enumerateDevices should not expose camera devices if they are not allowed by Permissions-Policy header - +

Description

-

This test checks for the presence of camera in -navigator.mediaDevices.enumerateDevices() method.

+

This test checks for the absence of camera in +navigator.mediaDevices.enumerateDevices() method when blocked by the Permissions-Policy header.

@@ -24,7 +24,7 @@ promise_test(async () => { assert_not_equals(mediaInfo.groupId, undefined, "mediaInfo's groupId should exist."); assert_in_array(mediaInfo.kind, ["audioinput", "audiooutput"]); } -}, "Camera is not exposed in mediaDevices.enumerateDevices()"); +}, "Camera is not exposed in mediaDevices.enumerateDevices() when blocked by Permissions-Policy header"); diff --git a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-camera.https.html.headers b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-camera.https.html.headers index 2adc5e237fc..6fcbae14191 100644 --- a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-camera.https.html.headers +++ b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-camera.https.html.headers @@ -1 +1 @@ -Feature-Policy: camera 'none' +Permissions-Policy: camera=() diff --git a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-mic.https.html b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-mic.https.html index 8d535ce551d..d45fd740e80 100644 --- a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-mic.https.html +++ b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-mic.https.html @@ -1,14 +1,14 @@ -enumerateDevices: test enumerateDevices should not expose microphone devices if they are not allowed to use +enumerateDevices: test enumerateDevices should not expose microphone devices if they are not allowed by Permissions-Policy header - +

Description

-

This test checks for the presence of microphone in -navigator.mediaDevices.enumerateDevices() method.

+

This test checks for the absence of microphone in +navigator.mediaDevices.enumerateDevices() method when blocked by Permissions-Policy header.

@@ -24,7 +24,7 @@ promise_test(async () => { assert_not_equals(mediaInfo.groupId, undefined, "mediaInfo's groupId should exist."); assert_in_array(mediaInfo.kind, ["videoinput", "audiooutput"]); } -}, "Microphone is not exposed in mediaDevices.enumerateDevices()"); +}, "Microphone is not exposed in mediaDevices.enumerateDevices() when blocked by Permissions-Policy"); diff --git a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-mic.https.html.headers b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-mic.https.html.headers index a86e0a07785..ae65ea5c735 100644 --- a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-mic.https.html.headers +++ b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-not-allowed-mic.https.html.headers @@ -1 +1 @@ -Feature-Policy: microphone 'none' +Permissions-Policy: microphone=() diff --git a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-persistent-permission.https.html b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-persistent-permission.https.html index 58aacf9856c..ec127625228 100644 --- a/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-persistent-permission.https.html +++ b/tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-enumerateDevices-persistent-permission.https.html @@ -18,8 +18,8 @@ // the page loaded below hasn't had capture enabled // so enumerateDevices should not list detailed info yet const iframe = document.createElement("iframe"); - iframe.setAttribute("allow", "camera 'src';microphone 'src'"); - iframe.src = "/mediacapture-streams/iframe-enumerate.html"; + iframe.setAttribute("allow", "microphone;camera"); + iframe.src = "/mediacapture-streams/iframe-enumerate-nogum.html"; document.body.appendChild(iframe); const loadWatcher = new EventWatcher(t, iframe, ['load']); await loadWatcher.wait_for('load'); diff --git a/tests/wpt/web-platform-tests/mediacapture-streams/iframe-enumerate-nogum.html b/tests/wpt/web-platform-tests/mediacapture-streams/iframe-enumerate-nogum.html new file mode 100644 index 00000000000..394575ed48f --- /dev/null +++ b/tests/wpt/web-platform-tests/mediacapture-streams/iframe-enumerate-nogum.html @@ -0,0 +1,2 @@ + + diff --git a/tests/wpt/web-platform-tests/mediacapture-streams/message-enumerateddevices-nogum.js b/tests/wpt/web-platform-tests/mediacapture-streams/message-enumerateddevices-nogum.js new file mode 100644 index 00000000000..3a503e0ce5f --- /dev/null +++ b/tests/wpt/web-platform-tests/mediacapture-streams/message-enumerateddevices-nogum.js @@ -0,0 +1,6 @@ +onmessage = async e => { + const devices = await navigator.mediaDevices.enumerateDevices(); + e.source.postMessage({ + devices: devices.map(d => d.toJSON()) + }, '*'); +} diff --git a/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-allowed-by-permissions-policy-attribute.tentative.https.sub.html b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-allowed-by-permissions-policy-attribute.tentative.https.sub.html new file mode 100644 index 00000000000..699b11cfef3 --- /dev/null +++ b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-allowed-by-permissions-policy-attribute.tentative.https.sub.html @@ -0,0 +1,29 @@ + +Private State Tokens API Issuance operation container policy test + + + + + + diff --git a/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-disabled-by-permissions-policy.tentative.https.sub.html b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-disabled-by-permissions-policy.tentative.https.sub.html new file mode 100644 index 00000000000..0c72b3da889 --- /dev/null +++ b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-disabled-by-permissions-policy.tentative.https.sub.html @@ -0,0 +1,67 @@ + + + + + + + diff --git a/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-disabled-by-permissions-policy.tentative.https.sub.html.headers b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-disabled-by-permissions-policy.tentative.https.sub.html.headers new file mode 100644 index 00000000000..18cbd50fca1 --- /dev/null +++ b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-disabled-by-permissions-policy.tentative.https.sub.html.headers @@ -0,0 +1 @@ +Permissions-Policy: private-state-token-issuance=() diff --git a/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-enabled-by-permissions-policy.tentative.https.sub.html b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-enabled-by-permissions-policy.tentative.https.sub.html new file mode 100644 index 00000000000..4b446f98d7c --- /dev/null +++ b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-enabled-by-permissions-policy.tentative.https.sub.html @@ -0,0 +1,58 @@ + + + + + + + diff --git a/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-enabled-by-permissions-policy.tentative.https.sub.html.headers b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-enabled-by-permissions-policy.tentative.https.sub.html.headers new file mode 100644 index 00000000000..cef93ce872f --- /dev/null +++ b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-enabled-by-permissions-policy.tentative.https.sub.html.headers @@ -0,0 +1 @@ +Permissions-Policy: private-state-token-issuance=* diff --git a/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-supported-by-permissions-policy.tentative.html b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-supported-by-permissions-policy.tentative.html new file mode 100644 index 00000000000..52a392de577 --- /dev/null +++ b/tests/wpt/web-platform-tests/permissions-policy/private-state-token-issue-supported-by-permissions-policy.tentative.html @@ -0,0 +1,8 @@ + + + + diff --git a/tests/wpt/web-platform-tests/permissions-policy/resources/permissions-policy-private-state-token-issuance.html b/tests/wpt/web-platform-tests/permissions-policy/resources/permissions-policy-private-state-token-issuance.html new file mode 100644 index 00000000000..f2bf31918e1 --- /dev/null +++ b/tests/wpt/web-platform-tests/permissions-policy/resources/permissions-policy-private-state-token-issuance.html @@ -0,0 +1,35 @@ + + diff --git a/tests/wpt/web-platform-tests/pointerevents/pointerevent_support.js b/tests/wpt/web-platform-tests/pointerevents/pointerevent_support.js index e8e9dd6642e..d65194db566 100644 --- a/tests/wpt/web-platform-tests/pointerevents/pointerevent_support.js +++ b/tests/wpt/web-platform-tests/pointerevents/pointerevent_support.js @@ -71,44 +71,15 @@ function check_PointerEvent(event, testNamePrefix) { "boolean": function (v) { return typeof v === "boolean" }, "object": function (v) { return typeof v === "object" } }; - [ - ["long", "pointerId"], - ["float", "width"], - ["float", "height"], - ["float", "pressure"], - ["long", "tiltX"], - ["long", "tiltY"], - ["string", "pointerType"], - ["boolean", "isPrimary"], - ["long", "detail", 0], - ["object", "fromElement"], - ["object", "toElement"], - ["boolean", "isTrusted"], - ["boolean", "composed"], - ["boolean", "bubbles"] - ].forEach(function (attr) { - var type = attr[0]; - var name = attr[1]; - - test(function () { - // Existence check. - assert_true(name in event, "attribute exists"); - - // Readonly check. - assert_readonly(event.type, name, "attribute is readonly"); - - // Type check. - assert_true(idl_type_check[type](event[name]), - "attribute type " + type + " (JS type was " + typeof event[name] + ")"); - }, pointerTestName + "." + name + " conforms to WebIDL"); - }); // Check values for inherited attributes. // https://w3c.github.io/pointerevents/#attributes-and-default-actions test(function () { + assert_implements_optional("fromElement" in event); assert_equals(event.fromElement, null); }, pointerTestName + ".fromElement value is null"); test(function () { + assert_implements_optional("toElement" in event); assert_equals(event.toElement, null); }, pointerTestName + ".toElement value is null"); test(function () { diff --git a/tests/wpt/web-platform-tests/preload/onerror-event.html b/tests/wpt/web-platform-tests/preload/onerror-event.html index 1d2ebefc656..443513e9fee 100644 --- a/tests/wpt/web-platform-tests/preload/onerror-event.html +++ b/tests/wpt/web-platform-tests/preload/onerror-event.html @@ -16,18 +16,18 @@ var gibberishFailed = false; var fetchFailed = false; - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/preload/preload-error.sub.html b/tests/wpt/web-platform-tests/preload/preload-error.sub.html index 3c9d35b0b35..7a170471fc8 100644 --- a/tests/wpt/web-platform-tests/preload/preload-error.sub.html +++ b/tests/wpt/web-platform-tests/preload/preload-error.sub.html @@ -69,29 +69,29 @@ function runTest(api, as, description, shouldPreloadSucceed, shouldMainLoadSucce if (api === 'image') { mainPromise = new Promise(t.step_func((resolve, reject) => { const img = document.createElement('img'); - img.src = url; img.setAttribute('crossorigin', 'anonymous'); img.onload = resolve; img.onerror = () => reject(new TypeError('img onerror')); + img.src = url; document.head.appendChild(img); })); } else if (api === 'style') { mainPromise = new Promise(t.step_func((resolve, reject) => { const link = document.createElement('link'); - link.href = url; link.setAttribute('rel', 'stylesheet'); link.setAttribute('crossorigin', 'anonymous'); link.onload = resolve; link.onerror = () => reject(new TypeError('link rel=stylesheet onerror')); + link.href = url; document.head.appendChild(link); })); } else if (api === 'script') { mainPromise = new Promise(t.step_func((resolve, reject) => { const script = document.createElement('script'); - script.src = url; script.setAttribute('crossorigin', 'anonymous'); script.onload = resolve; script.onerror = () => reject(new TypeError('script onerror')); + script.src = url; document.head.appendChild(script); })); } else if (api === 'xhr') { diff --git a/tests/wpt/web-platform-tests/resource-timing/resources/fake_responses.py b/tests/wpt/web-platform-tests/resource-timing/resources/fake_responses.py index 66b17be154b..cc6aba6efaa 100644 --- a/tests/wpt/web-platform-tests/resource-timing/resources/fake_responses.py +++ b/tests/wpt/web-platform-tests/resource-timing/resources/fake_responses.py @@ -13,8 +13,8 @@ def main(request, response): date = request.GET.first(b"date", b"") modified = request.headers.get(b"If-Modified-Since", None) url = request.GET.first(b"url", None) - response.headers.set(b"Access-Control-Allow-Origin", b"*"); - response.headers.set(b"Timing-Allow-Origin", b"*"); + response.headers.set(b"Access-Control-Allow-Origin", b"*") + response.headers.set(b"Timing-Allow-Origin", b"*") if tag: response.headers.set(b"ETag", b'"%s"' % tag) elif date: @@ -30,6 +30,7 @@ def main(request, response): response.headers.set(b"Content-Type", b"text/javascript") with open(filepath, 'rb') as f: filedata = f.read() + return filedata if ((match is not None and match == tag) or diff --git a/tests/wpt/web-platform-tests/scroll-animations/css/animation-timeline-ignored.tentative.html b/tests/wpt/web-platform-tests/scroll-animations/css/animation-timeline-ignored.tentative.html index 54a6257f343..0ac7a9d63e8 100644 --- a/tests/wpt/web-platform-tests/scroll-animations/css/animation-timeline-ignored.tentative.html +++ b/tests/wpt/web-platform-tests/scroll-animations/css/animation-timeline-ignored.tentative.html @@ -7,13 +7,16 @@ main { overflow: hidden; height: 0px; + scroll-timeline-attachment: defer; + scroll-timeline-name: timeline1, timeline2, timeline3; } - main > div { + .scroller { overflow: hidden; width: 100px; height: 100px; + scroll-timeline-attachment: ancestor; } - main > div > div { + .scroller > div { height: 200px; } @keyframes expand { @@ -21,13 +24,13 @@ to { width: 200px; } } #scroller1 { - scroll-timeline: timeline1; + scroll-timeline-name: timeline1; } #scroller2 { - scroll-timeline: timeline2; + scroll-timeline-name: timeline2; } #scroller3 { - scroll-timeline: timeline3; + scroll-timeline-name: timeline3; } #element { width: 0px; @@ -43,10 +46,10 @@ }
-
-
-
-
+
+
+
+
diff --git a/tests/wpt/web-platform-tests/scroll-animations/css/animation-timeline-multiple.html b/tests/wpt/web-platform-tests/scroll-animations/css/animation-timeline-multiple.html index 7eccdf89b6c..50a829c5b6b 100644 --- a/tests/wpt/web-platform-tests/scroll-animations/css/animation-timeline-multiple.html +++ b/tests/wpt/web-platform-tests/scroll-animations/css/animation-timeline-multiple.html @@ -5,12 +5,18 @@
-
-
-
-
+
+
+
+
diff --git a/tests/wpt/web-platform-tests/scroll-animations/css/scroll-timeline-in-container-query.html b/tests/wpt/web-platform-tests/scroll-animations/css/scroll-timeline-in-container-query.html index d6a8ba8e605..38b8ffdc15a 100644 --- a/tests/wpt/web-platform-tests/scroll-animations/css/scroll-timeline-in-container-query.html +++ b/tests/wpt/web-platform-tests/scroll-animations/css/scroll-timeline-in-container-query.html @@ -21,6 +21,7 @@ width: auto; height: 100px; } + #scroller > div { height: 200px; } @@ -32,14 +33,15 @@ } } - @keyframes expand { + @keyframes recolor { from { background-color: rgb(100, 100, 100); } to { background-color: rgb(200, 200, 200); } } + #element { height: 10px; width: 10px; - animation: expand 10s linear; + animation: recolor 10s linear; animation-timeline: timeline; background-color: rgb(0, 0, 0); } @@ -48,8 +50,7 @@
-
-
+
@@ -58,7 +59,7 @@ promise_test(async (t) => { element.offsetTop; - scroller.scrollTop = 50; + scroller.scrollTop = (scroller.scrollHeight - scroller.clientHeight) / 2; await waitForNextFrame(); // Unknown timeline, time held at zero. assert_equals(getComputedStyle(element).backgroundColor, 'rgb(100, 100, 100)'); diff --git a/tests/wpt/web-platform-tests/scroll-animations/css/scroll-timeline-sampling.html b/tests/wpt/web-platform-tests/scroll-animations/css/scroll-timeline-sampling.html index 1fe354edfd6..51b60e73ce6 100644 --- a/tests/wpt/web-platform-tests/scroll-animations/css/scroll-timeline-sampling.html +++ b/tests/wpt/web-platform-tests/scroll-animations/css/scroll-timeline-sampling.html @@ -29,8 +29,8 @@
+
-
+ + + + + + + + +
+
+
+
+
+
+
+ + diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/aztec-correction.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/aztec-correction.jpg new file mode 100644 index 00000000000..55bc0d23d6a Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/aztec-correction.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/aztec-full.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/aztec-full.jpg new file mode 100644 index 00000000000..36390f08217 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/aztec-full.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/aztec-layers.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/aztec-layers.jpg new file mode 100644 index 00000000000..75449a70443 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/aztec-layers.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/aztec.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/aztec.jpg new file mode 100644 index 00000000000..f71e11f0646 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/aztec.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/barcodes.mov b/tests/wpt/web-platform-tests/shape-detection/resources/barcodes.mov new file mode 100644 index 00000000000..473a7ae2392 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/barcodes.mov differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/code128-height.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/code128-height.jpg new file mode 100644 index 00000000000..69883e56835 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/code128-height.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/code128.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/code128.jpg new file mode 100644 index 00000000000..9bb66fe8caf Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/code128.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/face-bottom-left.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/face-bottom-left.jpg new file mode 100644 index 00000000000..1fb4e660e40 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/face-bottom-left.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/face-bottom-right.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/face-bottom-right.jpg new file mode 100644 index 00000000000..ce8837851b8 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/face-bottom-right.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/face-center.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/face-center.jpg new file mode 100644 index 00000000000..30364040ed5 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/face-center.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/face-top-left.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/face-top-left.jpg new file mode 100644 index 00000000000..300866b2eb8 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/face-top-left.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/face-top-right.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/face-top-right.jpg new file mode 100644 index 00000000000..528a2a778df Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/face-top-right.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/faces.mov b/tests/wpt/web-platform-tests/shape-detection/resources/faces.mov new file mode 100644 index 00000000000..b2c7b8c5774 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/faces.mov differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-columns.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-columns.jpg new file mode 100644 index 00000000000..54a08cf0eea Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-columns.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-compact.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-compact.jpg new file mode 100644 index 00000000000..1185c56dfe4 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-compact.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-compaction.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-compaction.jpg new file mode 100644 index 00000000000..20e4a1c64cf Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-compaction.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-correction.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-correction.jpg new file mode 100644 index 00000000000..0c64ea9605d Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-correction.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-rows.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-rows.jpg new file mode 100644 index 00000000000..9f5f67b10c8 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-rows.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-square.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-square.jpg new file mode 100644 index 00000000000..8a379ae6cc6 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-square.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-taller.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-taller.jpg new file mode 100644 index 00000000000..a520f22fde8 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-taller.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-wider.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-wider.jpg new file mode 100644 index 00000000000..9f5f67b10c8 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417-wider.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/pdf417.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417.jpg new file mode 100644 index 00000000000..ebbe36b5104 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/pdf417.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-bottom-left.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-bottom-left.jpg new file mode 100644 index 00000000000..754bdedaf1a Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-bottom-left.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-bottom-right.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-bottom-right.jpg new file mode 100644 index 00000000000..483297100d6 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-bottom-right.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-center.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-center.jpg new file mode 100644 index 00000000000..ca8e770bf48 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-center.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-h.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-h.jpg new file mode 100644 index 00000000000..a1beb021018 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-h.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-l.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-l.jpg new file mode 100644 index 00000000000..a29c358393c Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-l.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-m.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-m.jpg new file mode 100644 index 00000000000..ca8e770bf48 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-m.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-q.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-q.jpg new file mode 100644 index 00000000000..45313c71b08 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-q.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-top-left.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-top-left.jpg new file mode 100644 index 00000000000..f3092933e42 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-top-left.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/qr-top-right.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/qr-top-right.jpg new file mode 100644 index 00000000000..875ee8035c8 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/qr-top-right.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/single-detection-helpers.js b/tests/wpt/web-platform-tests/shape-detection/resources/single-detection-helpers.js new file mode 100644 index 00000000000..bbd2bda96b2 --- /dev/null +++ b/tests/wpt/web-platform-tests/shape-detection/resources/single-detection-helpers.js @@ -0,0 +1,66 @@ +function imageLoadedPromise(image) { + return new Promise(function(resolve, reject) { + if (image.complete) + resolve(); + image.addEventListener("load", resolve, { once: true }); + }); +} + +function videoLoadedPromise(video) { + return new Promise(function(resolve, reject) { + if (video.readyState == 4) + resolve(); + else { + video.addEventListener("loadeddata", resolve, { once: true }); + video.addEventListener("error", reject, { once: true }); + } + }); +} + +function waitForNFrames(count) { + if (count <= 0) + return Promise.reject(new TypeError("count should be greater than 0!")); + + return new Promise(resolve => { + function tick() { + (--count) ? requestAnimationFrame(tick) : resolve(); + } + requestAnimationFrame(tick); + }); +} + +function seekTo(video, time) { + return new Promise(function(resolve, reject) { + video.addEventListener("seeked", async function() { + /* Work around flakiness in video players... */ + await waitForNFrames(3); + resolve(); + }, { once: true }); + video.currentTime = time; + }); +} + +function checkBoundingBox(actual, expected, fuzziness) { + assert_equals(actual.constructor.name, "DOMRectReadOnly"); + assert_approx_equals(actual.left, expected.left, fuzziness); + assert_approx_equals(actual.right, expected.right, fuzziness); + assert_approx_equals(actual.top, expected.top, fuzziness); + assert_approx_equals(actual.bottom, expected.bottom, fuzziness); +} + +function checkPointsLieWithinBoundingBox(points, boundingBox) { + for (point of points) { + assert_between_inclusive(point.x, boundingBox.left, boundingBox.right); + assert_between_inclusive(point.y, boundingBox.top, boundingBox.bottom); + } +} + +function checkPointIsNear(actual, expected, fuzzinessX, fuzzinessY) { + assert_approx_equals(actual.x, expected.x, fuzzinessX); + assert_approx_equals(actual.y, expected.y, fuzzinessY); +} + +function checkPointsAreNear(actual, expected, fuzzinessX, fuzzinessY) { + for (point of actual) + checkPointIsNear(point, expected, fuzzinessX, fuzzinessY); +} diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/text-bottom-left.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/text-bottom-left.jpg new file mode 100644 index 00000000000..12a0641fd3e Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/text-bottom-left.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/text-bottom-right.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/text-bottom-right.jpg new file mode 100644 index 00000000000..7ad8b71b6c5 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/text-bottom-right.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/text-center.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/text-center.jpg new file mode 100644 index 00000000000..69e8ce446cd Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/text-center.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/text-top-left.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/text-top-left.jpg new file mode 100644 index 00000000000..53ca0e0aaff Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/text-top-left.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/text-top-right.jpg b/tests/wpt/web-platform-tests/shape-detection/resources/text-top-right.jpg new file mode 100644 index 00000000000..76a22a677c1 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/text-top-right.jpg differ diff --git a/tests/wpt/web-platform-tests/shape-detection/resources/text.mov b/tests/wpt/web-platform-tests/shape-detection/resources/text.mov new file mode 100644 index 00000000000..d50197b3263 Binary files /dev/null and b/tests/wpt/web-platform-tests/shape-detection/resources/text.mov differ diff --git a/tests/wpt/web-platform-tests/shape-detection/single-barcode-detection.https.html b/tests/wpt/web-platform-tests/shape-detection/single-barcode-detection.https.html new file mode 100644 index 00000000000..1f14e35153a --- /dev/null +++ b/tests/wpt/web-platform-tests/shape-detection/single-barcode-detection.https.html @@ -0,0 +1,396 @@ + + + + + + + diff --git a/tests/wpt/web-platform-tests/shape-detection/single-face-detection.https.html b/tests/wpt/web-platform-tests/shape-detection/single-face-detection.https.html new file mode 100644 index 00000000000..28afdef1364 --- /dev/null +++ b/tests/wpt/web-platform-tests/shape-detection/single-face-detection.https.html @@ -0,0 +1,223 @@ + + + + + + + diff --git a/tests/wpt/web-platform-tests/shape-detection/single-text-detection.https.html b/tests/wpt/web-platform-tests/shape-detection/single-text-detection.https.html new file mode 100644 index 00000000000..829e8ce6d61 --- /dev/null +++ b/tests/wpt/web-platform-tests/shape-detection/single-text-detection.https.html @@ -0,0 +1,197 @@ + + + + + + + diff --git a/tests/wpt/web-platform-tests/svg/painting/color-mix-currentcolor-fill-stroke-repaint.html b/tests/wpt/web-platform-tests/svg/painting/color-mix-currentcolor-fill-stroke-repaint.html new file mode 100644 index 00000000000..216948038ca --- /dev/null +++ b/tests/wpt/web-platform-tests/svg/painting/color-mix-currentcolor-fill-stroke-repaint.html @@ -0,0 +1,30 @@ + + +currentColor in color-mix() used in fill/stroke repaints properly when parent color changes + + + +

Test passes if there is a filled green square and no red.

+
+ + + +
+ + diff --git a/tests/wpt/web-platform-tests/svg/painting/currentcolor-fill-stroke-repaint.html b/tests/wpt/web-platform-tests/svg/painting/currentcolor-fill-stroke-repaint.html new file mode 100644 index 00000000000..4e4fa20450c --- /dev/null +++ b/tests/wpt/web-platform-tests/svg/painting/currentcolor-fill-stroke-repaint.html @@ -0,0 +1,30 @@ + + +currentColor used in fill/stroke repaints properly when parent color changes + + + +

Test passes if there is a filled green square and no red.

+
+ + + +
+ + diff --git a/tests/wpt/web-platform-tests/svg/pservers/reftests/pattern-viewbox-01.svg b/tests/wpt/web-platform-tests/svg/pservers/reftests/pattern-viewbox-01.svg new file mode 100644 index 00000000000..618b8fc29e6 --- /dev/null +++ b/tests/wpt/web-platform-tests/svg/pservers/reftests/pattern-viewbox-01.svg @@ -0,0 +1,17 @@ + + + Pattern: viewBox with x offset + + + + + + + + + + + + diff --git a/tests/wpt/web-platform-tests/svg/pservers/reftests/reference/pattern-viewbox-01-ref.svg b/tests/wpt/web-platform-tests/svg/pservers/reftests/reference/pattern-viewbox-01-ref.svg new file mode 100644 index 00000000000..c9f6931dead --- /dev/null +++ b/tests/wpt/web-platform-tests/svg/pservers/reftests/reference/pattern-viewbox-01-ref.svg @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/tests/wpt/web-platform-tests/tools/ci/requirements_tc.txt b/tests/wpt/web-platform-tests/tools/ci/requirements_tc.txt index 58a7ef6058e..67e46ed204c 100644 --- a/tests/wpt/web-platform-tests/tools/ci/requirements_tc.txt +++ b/tests/wpt/web-platform-tests/tools/ci/requirements_tc.txt @@ -1,4 +1,4 @@ pygithub==1.58.1 pyyaml==6.0 -requests==2.28.2 -taskcluster==49.1.1 +requests==2.29.0 +taskcluster==49.1.2 diff --git a/tests/wpt/web-platform-tests/tools/docker/requirements.txt b/tests/wpt/web-platform-tests/tools/docker/requirements.txt index 75dd52bde00..7c45f769eea 100644 --- a/tests/wpt/web-platform-tests/tools/docker/requirements.txt +++ b/tests/wpt/web-platform-tests/tools/docker/requirements.txt @@ -1,2 +1,2 @@ pyyaml==6.0 -requests==2.28.2 +requests==2.29.0 diff --git a/tests/wpt/web-platform-tests/tools/lint/lint.py b/tests/wpt/web-platform-tests/tools/lint/lint.py index f255c024952..fbc663417fa 100644 --- a/tests/wpt/web-platform-tests/tools/lint/lint.py +++ b/tests/wpt/web-platform-tests/tools/lint/lint.py @@ -193,8 +193,7 @@ def check_gitignore_file(repo_root, path): return [] if (path_parts[0] in ["tools", "docs"] or - path_parts[:2] == ["resources", "webidl2"] or - path_parts[:3] == ["css", "tools", "apiclient"]): + path_parts[:2] == ["resources", "webidl2"]): return [] return [rules.GitIgnoreFile.error(path)] @@ -254,99 +253,6 @@ w3c_tr_re = re.compile(r"https?\:\/\/www\.w3c?\.org\/TR\/([^/?#]+)") w3c_dev_re = re.compile(r"https?\:\/\/dev\.w3c?\.org\/[^/?#]+\/([^/?#]+)") -def check_css_globally_unique(repo_root, paths): - # type: (Text, List[Text]) -> List[rules.Error] - """ - Checks that CSS filenames are sufficiently unique - - This groups files by path classifying them as "test", "reference", or - "support". - - "test" files must have a unique name across files that share links to the - same spec. - - "reference" and "support" files, on the other hand, must have globally - unique names. - - :param repo_root: the repository root - :param paths: list of all paths - :returns: a list of errors found in ``paths`` - - """ - test_files = defaultdict(set) # type: Dict[Text, Set[Text]] - ref_files = defaultdict(set) # type: Dict[Text, Set[Text]] - support_files = defaultdict(set) # type: Dict[Text, Set[Text]] - - for path in paths: - if os.name == "nt": - path = path.replace("\\", "/") - - if not path.startswith("css/"): - continue - - source_file = SourceFile(repo_root, path, "/") - if source_file.name_is_non_test: - # If we're name_is_non_test for a reason apart from support, ignore it. - # We care about support because of the requirement all support files in css/ to be in - # a support directory; see the start of check_parsed. - offset = path.find("/support/") - if offset == -1: - continue - - parts = source_file.dir_path.split(os.path.sep) - if (parts[0] in source_file.root_dir_non_test or - any(item in source_file.dir_non_test - {"support"} for item in parts) or - any(parts[:len(non_test_path)] == list(non_test_path) for non_test_path in source_file.dir_path_non_test)): - continue - - support_name = path[offset+1:] - support_files[support_name].add(path) - elif source_file.name_is_reference: - ref_files[source_file.name].add(path) - else: - test_name = source_file.name # type: Text - test_name = test_name.replace('-manual', '') - test_files[test_name].add(path) - - errors = [] - - for name, colliding in test_files.items(): - if len(colliding) > 1: - if not _all_files_equal([os.path.join(repo_root, x) for x in colliding]): - # Only compute by_spec if there are prima-facie collisions because of cost - by_spec = defaultdict(set) # type: Dict[Text, Set[Text]] - for path in colliding: - source_file = SourceFile(repo_root, path, "/") - for link in source_file.spec_links: - for r in (drafts_csswg_re, w3c_tr_re, w3c_dev_re): - m = r.match(link) - if m: - spec = m.group(1) - break - else: - continue - by_spec[spec].add(path) - - for spec, spec_paths in by_spec.items(): - if not _all_files_equal([os.path.join(repo_root, x) for x in spec_paths]): - for x in spec_paths: - context1 = (name, spec, ", ".join(sorted(spec_paths))) - errors.append(rules.CSSCollidingTestName.error(x, - context1)) - - for rule_class, d in [(rules.CSSCollidingRefName, ref_files), - (rules.CSSCollidingSupportName, support_files)]: - for name, colliding in d.items(): - if len(colliding) > 1: - if not _all_files_equal([os.path.join(repo_root, x) for x in colliding]): - context2 = (name, ", ".join(sorted(colliding))) - - for x in colliding: - errors.append(rule_class.error(x, context2)) - - return errors - - def check_unique_testharness_basenames(repo_root, paths): # type: (Text, List[Text]) -> List[rules.Error] """ @@ -498,11 +404,6 @@ def check_parsed(repo_root, path, f): errors = [] # type: List[rules.Error] if path.startswith("css/"): - if (source_file.type == "support" and - not source_file.name_is_non_test and - not source_file.name_is_reference): - return [rules.SupportWrongDir.error(path)] - if (source_file.type != "support" and not source_file.name_is_reference and not source_file.name_is_tentative and @@ -1125,7 +1026,7 @@ def lint(repo_root, paths, output_format, ignore_glob=None, github_checks_output path_lints = [check_file_type, check_path_length, check_worker_collision, check_ahem_copy, check_mojom_js, check_tentative_directories, check_gitignore_file] -all_paths_lints = [check_css_globally_unique, check_unique_testharness_basenames, +all_paths_lints = [check_unique_testharness_basenames, check_unique_case_insensitive_paths] file_lints = [check_regexp_line, check_parsed, check_python_ast, check_script_metadata, check_ahem_system_font] diff --git a/tests/wpt/web-platform-tests/tools/lint/rules.py b/tests/wpt/web-platform-tests/tools/lint/rules.py index 7b9a54b9db0..d5876cdc269 100644 --- a/tests/wpt/web-platform-tests/tools/lint/rules.py +++ b/tests/wpt/web-platform-tests/tools/lint/rules.py @@ -108,26 +108,6 @@ class IgnoredPath(Rule): """) -class CSSCollidingTestName(Rule): - name = "CSS-COLLIDING-TEST-NAME" - description = "The filename %s in the %s testsuite is shared by: %s" - - -class CSSCollidingRefName(Rule): - name = "CSS-COLLIDING-REF-NAME" - description = "The filename %s is shared by: %s" - - -class CSSCollidingSupportName(Rule): - name = "CSS-COLLIDING-SUPPORT-NAME" - description = "The filename %s is shared by: %s" - - -class SupportWrongDir(Rule): - name = "SUPPORT-WRONG-DIR" - description = "Support file not in support directory" - - class ParseFailed(Rule): name = "PARSE-FAILED" description = "Unable to parse file" diff --git a/tests/wpt/web-platform-tests/tools/lint/tests/test_file_lints.py b/tests/wpt/web-platform-tests/tools/lint/tests/test_file_lints.py index b438e45e628..9a49d6e7a24 100644 --- a/tests/wpt/web-platform-tests/tools/lint/tests/test_file_lints.py +++ b/tests/wpt/web-platform-tests/tools/lint/tests/test_file_lints.py @@ -750,27 +750,6 @@ def test_open_mode(): ] -@pytest.mark.parametrize( - "filename,expect_error", - [ - ("foo/bar.html", False), - ("css/bar.html", True), - ]) -def test_css_support_file(filename, expect_error): - errors = check_file_contents("", filename, io.BytesIO(b"")) - check_errors(errors) - - if expect_error: - assert errors == [ - ('SUPPORT-WRONG-DIR', - 'Support file not in support directory', - filename, - None), - ] - else: - assert errors == [] - - def test_css_missing_file_in_css(): code = b"""\ diff --git a/tests/wpt/web-platform-tests/tools/lint/tests/test_lint.py b/tests/wpt/web-platform-tests/tools/lint/tests/test_lint.py index 11ce20353fe..8a304bd3694 100644 --- a/tests/wpt/web-platform-tests/tools/lint/tests/test_lint.py +++ b/tests/wpt/web-platform-tests/tools/lint/tests/test_lint.py @@ -277,126 +277,6 @@ def test_lint_passing_and_failing(caplog): assert "okay.html" not in caplog.text -def test_check_css_globally_unique_identical_test(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/match/a.html", "css/css-unique/a.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert caplog.text == "" - - -def test_check_css_globally_unique_different_test(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/not-match/a.html", "css/css-unique/a.html"], "normal") - assert rv == 2 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert "CSS-COLLIDING-TEST-NAME" in caplog.text - - -def test_check_css_globally_unique_different_spec_test(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/selectors/a.html", "css/css-unique/a.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert caplog.text == "" - - -def test_check_css_globally_unique_support_ignored(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/support/a.html", "css/css-unique/support/tools/a.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert caplog.text == "" - - -def test_check_css_globally_unique_support_identical(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/support/a.html", "css/css-unique/match/support/a.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert caplog.text == "" - - -def test_check_css_globally_unique_support_different(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/not-match/support/a.html", "css/css-unique/support/a.html"], "normal") - assert rv == 2 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert "CSS-COLLIDING-SUPPORT-NAME" in caplog.text - - -def test_check_css_globally_unique_test_support(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/support/a.html", "css/css-unique/a.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert caplog.text == "" - - -def test_check_css_globally_unique_ref_identical(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/a-ref.html", "css/css-unique/match/a-ref.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert caplog.text == "" - - -def test_check_css_globally_unique_ref_different(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/not-match/a-ref.html", "css/css-unique/a-ref.html"], "normal") - assert rv == 2 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert "CSS-COLLIDING-REF-NAME" in caplog.text - - -def test_check_css_globally_unique_test_ref(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/a-ref.html", "css/css-unique/a.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert caplog.text == "" - - -def test_check_css_globally_unique_ignored(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/tools/a.html", "css/css-unique/not-match/tools/a.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 2 - assert mocked_check_file_contents.call_count == 2 - assert caplog.text == "" - - -def test_check_css_globally_unique_ignored_dir(caplog): - with _mock_lint("check_path") as mocked_check_path: - with _mock_lint("check_file_contents") as mocked_check_file_contents: - rv = lint(_dummy_repo, ["css/css-unique/support/a.html"], "normal") - assert rv == 0 - assert mocked_check_path.call_count == 1 - assert mocked_check_file_contents.call_count == 1 - assert caplog.text == "" - - def test_check_unique_testharness_basename_same_basename(caplog): # Precondition: There are testharness files with conflicting basename paths. assert os.path.exists(os.path.join(_dummy_repo, 'tests', 'dir1', 'a.html')) diff --git a/tests/wpt/web-platform-tests/tools/lint/tests/test_path_lints.py b/tests/wpt/web-platform-tests/tools/lint/tests/test_path_lints.py index f2cc2409f2c..99c8f7dce6b 100644 --- a/tests/wpt/web-platform-tests/tools/lint/tests/test_path_lints.py +++ b/tests/wpt/web-platform-tests/tools/lint/tests/test_path_lints.py @@ -121,8 +121,7 @@ def test_tentative_directories_negative(path): "else/where/.gitignore" "elsewhere/tools/.gitignore", "elsewhere/docs/.gitignore", - "elsewhere/resources/webidl2/.gitignore", - "elsewhere/css/tools/apiclient/.gitignore"]) + "elsewhere/resources/webidl2/.gitignore"]) def test_gitignore_file(path): path = os.path.join(*path.split("/")) @@ -144,9 +143,7 @@ def test_gitignore_file(path): "docs/.gitignore" "docs/elsewhere/.gitignore", "resources/webidl2/.gitignore", - "resources/webidl2/elsewhere/.gitignore", - "css/tools/apiclient/.gitignore", - "css/tools/apiclient/elsewhere/.gitignore"]) + "resources/webidl2/elsewhere/.gitignore"]) def test_gitignore_negative(path): path = os.path.join(*path.split("/")) diff --git a/tests/wpt/web-platform-tests/tools/requirements_mypy.txt b/tests/wpt/web-platform-tests/tools/requirements_mypy.txt index e56d65b3a6d..af7de298c9f 100644 --- a/tests/wpt/web-platform-tests/tools/requirements_mypy.txt +++ b/tests/wpt/web-platform-tests/tools/requirements_mypy.txt @@ -9,6 +9,6 @@ types-PyYAML==6.0.12.9 types-requests==2.28.11.17 types-setuptools==67.6.0.8 types-six==1.16.21.8 -types-ujson==5.7.0.3 -types-urllib3==1.26.25.10 +types-ujson==5.7.0.4 +types-urllib3==1.26.25.11 typing_extensions==4.5.0 diff --git a/tests/wpt/web-platform-tests/tools/requirements_pytest.txt b/tests/wpt/web-platform-tests/tools/requirements_pytest.txt index 22188887e42..5039de986ec 100644 --- a/tests/wpt/web-platform-tests/tools/requirements_pytest.txt +++ b/tests/wpt/web-platform-tests/tools/requirements_pytest.txt @@ -1,3 +1,3 @@ pytest==7.3.1 pytest-cov==4.0.0 -hypothesis==6.72.2 +hypothesis==6.74.0 diff --git a/tests/wpt/web-platform-tests/tools/requirements_tests.txt b/tests/wpt/web-platform-tests/tools/requirements_tests.txt index b404460243e..63f0b39b546 100644 --- a/tests/wpt/web-platform-tests/tools/requirements_tests.txt +++ b/tests/wpt/web-platform-tests/tools/requirements_tests.txt @@ -2,4 +2,4 @@ httpx[http2]==0.24.0 json-e==4.5.2 jsonschema==4.17.3 pyyaml==6.0 -taskcluster==49.1.1 +taskcluster==49.1.2 diff --git a/tests/wpt/web-platform-tests/tools/serve/serve.py b/tests/wpt/web-platform-tests/tools/serve/serve.py index 6eba2153a14..52a0eae428d 100644 --- a/tests/wpt/web-platform-tests/tools/serve/serve.py +++ b/tests/wpt/web-platform-tests/tools/serve/serve.py @@ -633,7 +633,7 @@ class ServerProc: # in the logging module unlocked importlib.reload(logging) - logger = get_logger(config.log_level, log_handlers) + logger = get_logger(config.logging["level"], log_handlers) if sys.platform == "darwin": # on Darwin, NOFILE starts with a very low limit (256), so bump it up a little @@ -1003,7 +1003,6 @@ class ConfigBuilder(config.ConfigBuilder): "webtransport-h3": ["auto"], }, "check_subdomains": True, - "log_level": "info", "bind_address": True, "ssl": { "type": "pregenerated", @@ -1022,7 +1021,11 @@ class ConfigBuilder(config.ConfigBuilder): }, "none": {} }, - "aliases": [] + "aliases": [], + "logging": { + "level": "info", + "suppress_handler_traceback": False + } } computed_properties = ["ws_doc_root"] + config.ConfigBuilder.computed_properties @@ -1082,7 +1085,7 @@ def build_config(logger, override_path=None, config_cls=ConfigBuilder, **kwargs) raise ValueError("Config path %s does not exist" % other_path) if kwargs.get("verbose"): - rv.log_level = "debug" + rv.logging["level"] = "DEBUG" setattr(rv, "inject_script", kwargs.get("inject_script")) @@ -1174,7 +1177,7 @@ def run(config_cls=ConfigBuilder, route_builder=None, mp_context=None, log_handl config_cls=config_cls, **kwargs) as config: # This sets the right log level - logger = get_logger(config.log_level, log_handlers) + logger = get_logger(config.logging["level"], log_handlers) bind_address = config["bind_address"] diff --git a/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/error.py b/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/error.py index d9ea28c78fd..5a169aa9847 100644 --- a/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/error.py +++ b/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/error.py @@ -35,9 +35,14 @@ class InvalidArgumentException(BidiException): error_code = "invalid argument" +class MoveTargetOutOfBoundsException(BidiException): + error_code = "move target out of bounds" + + class NoSuchFrameException(BidiException): error_code = "no such frame" + class NoSuchHandleException(BidiException): error_code = "no such handle" diff --git a/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/modules/input.py b/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/modules/input.py index be0d745a0ca..6b2221d7dc4 100644 --- a/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/modules/input.py +++ b/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/modules/input.py @@ -30,6 +30,12 @@ class PauseAction(Action): def __init__(self, duration: Optional[int] = None): self.duration = duration + def to_json(self) -> MutableMapping[str, Any]: + rv = super().to_json() + if self.duration is not None: + rv["duration"] = self.duration + return rv + class KeyAction(Action): def __init__(self, key: str): @@ -252,6 +258,12 @@ class KeyInputSource(InputSource): self.actions.append(KeyUpAction(key)) return self + def send_keys(self, keys: str) -> "KeyInputSource": + for c in keys: + self.key_down(c) + self.key_up(c) + return self + class PointerInputSource(InputSource): input_type = "pointer" diff --git a/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/modules/script.py b/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/modules/script.py index a33a9a7b670..d994c6388d8 100644 --- a/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/modules/script.py +++ b/tests/wpt/web-platform-tests/tools/webdriver/webdriver/bidi/modules/script.py @@ -43,6 +43,21 @@ class ContextTarget(Dict[str, Any]): Target = Union[RealmTarget, ContextTarget] +class SerializationOptions(Dict[str, Any]): + def __init__( + self, + max_dom_depth: Optional[int] = None, + max_object_depth: Optional[int] = None, + include_shadow_tree: Optional[str] = None + ): + if max_dom_depth is not None: + self["maxDomDepth"] = max_dom_depth + if max_object_depth is not None: + self["maxObjectDepth"] = max_object_depth + if include_shadow_tree is not None: + self["includeShadowTree"] = include_shadow_tree + + class Script(BidiModule): @command def add_preload_script( @@ -77,6 +92,7 @@ class Script(BidiModule): arguments: Optional[List[Mapping[str, Any]]] = None, this: Optional[Mapping[str, Any]] = None, result_ownership: Optional[OwnershipModel] = None, + serialization_options: Optional[SerializationOptions] = None ) -> Mapping[str, Any]: params: MutableMapping[str, Any] = { "functionDeclaration": function_declaration, @@ -90,6 +106,8 @@ class Script(BidiModule): params["this"] = this if result_ownership is not None: params["resultOwnership"] = result_ownership + if serialization_options is not None: + params["serializationOptions"] = serialization_options return params @call_function.result @@ -115,6 +133,7 @@ class Script(BidiModule): target: Target, await_promise: bool, result_ownership: Optional[OwnershipModel] = None, + serialization_options: Optional[SerializationOptions] = None ) -> Mapping[str, Any]: params: MutableMapping[str, Any] = { "expression": expression, @@ -124,6 +143,8 @@ class Script(BidiModule): if result_ownership is not None: params["resultOwnership"] = result_ownership + if serialization_options is not None: + params["serializationOptions"] = serialization_options return params @evaluate.result diff --git a/tests/wpt/web-platform-tests/tools/wpt/requirements.txt b/tests/wpt/web-platform-tests/tools/wpt/requirements.txt index ba07d192a2d..496696730aa 100644 --- a/tests/wpt/web-platform-tests/tools/wpt/requirements.txt +++ b/tests/wpt/web-platform-tests/tools/wpt/requirements.txt @@ -1 +1 @@ -requests==2.28.2 +requests==2.29.0 diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/requirements.txt b/tests/wpt/web-platform-tests/tools/wptrunner/requirements.txt index b7d3524f611..c55bc634101 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/requirements.txt +++ b/tests/wpt/web-platform-tests/tools/wptrunner/requirements.txt @@ -4,6 +4,6 @@ mozinfo==1.2.2 # https://bugzilla.mozilla.org/show_bug.cgi?id=1621226 mozlog==7.1.1 mozprocess==1.3.0 pillow==9.5.0 -requests==2.28.2 +requests==2.29.0 six==1.16.0 urllib3[secure]==1.26.15 diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/requirements_sauce.txt b/tests/wpt/web-platform-tests/tools/wptrunner/requirements_sauce.txt index 0f55bd5f87e..0650e6655e9 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/requirements_sauce.txt +++ b/tests/wpt/web-platform-tests/tools/wptrunner/requirements_sauce.txt @@ -1,2 +1,2 @@ selenium==4.9.0 -requests==2.28.2 +requests==2.29.0 diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/content_shell.py b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/content_shell.py index a4b9c9b0d4f..d729ebb6b36 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/content_shell.py +++ b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/content_shell.py @@ -1,13 +1,16 @@ # mypy: allow-untyped-defs import os +import subprocess from multiprocessing import Queue, Event -from subprocess import PIPE from threading import Thread -from mozprocess import ProcessHandlerMixin from . import chrome_spki_certs -from .base import Browser, ExecutorBrowser +from .base import ( + Browser, + ExecutorBrowser, + OutputHandler, +) from .base import get_timeout_multiplier # noqa: F401 from ..executors import executor_kwargs as base_executor_kwargs from ..executors.executorcontentshell import ( # noqa: F401 @@ -85,45 +88,65 @@ class ContentShellBrowser(Browser): process are connected to multiprocessing Queues so that the runner process can interact with content_shell through its protocol mode. """ + # Seconds to wait for the process to stop after it was sent `SIGTERM` or + # `TerminateProcess()`. The value is inherited from: + # https://chromium.googlesource.com/chromium/src/+/b175d48d3ea4ea66eea35c88c11aa80d233f3bee/third_party/blink/tools/blinkpy/web_tests/port/base.py#476 + termination_timeout: float = 3 def __init__(self, logger, binary="content_shell", binary_args=[], **kwargs): super().__init__(logger) - self._args = [binary] + binary_args + self._output_handler = None self._proc = None def start(self, group_metadata, **kwargs): self.logger.debug("Starting content shell: %s..." % self._args[0]) - - # Unfortunately we need to use the Process class directly because we do not - # want mozprocess to do any output handling at all. - self._proc = ProcessHandlerMixin.Process(self._args, stdin=PIPE, stdout=PIPE, stderr=PIPE) + self._output_handler = OutputHandler(self.logger, self._args) if os.name == "posix": - self._proc.pgid = ProcessHandlerMixin._getpgid(self._proc.pid) - self._proc.detached_pid = None + close_fds, preexec_fn = True, lambda: os.setpgid(0, 0) + else: + close_fds, preexec_fn = False, None + self._proc = subprocess.Popen(self._args, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + close_fds=close_fds, + preexec_fn=preexec_fn) + self._output_handler.after_process_start(self._proc.pid) self._stdout_queue = Queue() self._stderr_queue = Queue() self._stdin_queue = Queue() self._io_stopped = Event() - self._stdout_reader = self._create_reader_thread(self._proc.stdout, self._stdout_queue) - self._stderr_reader = self._create_reader_thread(self._proc.stderr, self._stderr_queue) + self._stdout_reader = self._create_reader_thread(self._proc.stdout, + self._stdout_queue, + prefix=b"OUT: ") + self._stderr_reader = self._create_reader_thread(self._proc.stderr, + self._stderr_queue, + prefix=b"ERR: ") self._stdin_writer = self._create_writer_thread(self._proc.stdin, self._stdin_queue) # Content shell is likely still in the process of initializing. The actual waiting # for the startup to finish is done in the ContentShellProtocol. self.logger.debug("Content shell has been started.") + self._output_handler.start(group_metadata=group_metadata, **kwargs) def stop(self, force=False): self.logger.debug("Stopping content shell...") + clean_shutdown = True if self.is_alive(): - kill_result = self._proc.kill(timeout=5) - # This makes sure any left-over child processes get killed. - # See http://bugzilla.mozilla.org/show_bug.cgi?id=1760080 - if force and kill_result != 0: - self._proc.kill(9, timeout=5) + self._proc.terminate() + try: + self._proc.wait(timeout=self.termination_timeout) + except subprocess.TimeoutExpired: + clean_shutdown = False + self.logger.warning( + "Content shell failed to stop gracefully (PID: " + f"{self._proc.pid}, timeout: {self.termination_timeout}s)") + if force: + self._proc.kill() # We need to shut down these queues cleanly to avoid broken pipe error spam in the logs. self._stdout_reader.join(2) @@ -142,7 +165,9 @@ class ContentShellBrowser(Browser): self.logger.debug("Content shell has been stopped.") else: self.logger.warning("Content shell failed to stop.") - + if stopped and self._output_handler is not None: + self._output_handler.after_process_stop(clean_shutdown) + self._output_handler = None return stopped def is_alive(self): @@ -165,7 +190,7 @@ class ContentShellBrowser(Browser): def check_crash(self, process, test): return not self.is_alive() - def _create_reader_thread(self, stream, queue): + def _create_reader_thread(self, stream, queue, prefix=b""): """This creates (and starts) a background thread which reads lines from `stream` and puts them into `queue` until `stream` reports EOF. """ @@ -174,7 +199,7 @@ class ContentShellBrowser(Browser): line = stream.readline() if not line: break - + self._output_handler(prefix + line.rstrip()) queue.put(line) stop_event.set() diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/firefox.py b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/firefox.py index 3e005ef0949..d2e386484f9 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/firefox.py +++ b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/firefox.py @@ -198,7 +198,7 @@ def run_info_extras(**kwargs): "headless": kwargs.get("headless", False) or "MOZ_HEADLESS" in os.environ, "fission": enable_fission, "sessionHistoryInParent": (enable_fission or - get_bool_pref("fission.sessionHistoryInParent")), + not get_bool_pref("fission.disableSessionHistoryInParent")), "swgl": get_bool_pref("gfx.webrender.software")} rv.update(run_info_browser_version(**kwargs)) diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/environment.py b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/environment.py index 2bf72448e79..bea6808221a 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/environment.py +++ b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/environment.py @@ -93,7 +93,8 @@ class TestEnvironment: websockets servers""" def __init__(self, test_paths, testharness_timeout_multipler, pause_after_test, debug_test, debug_info, options, ssl_config, env_extras, - enable_webtransport=False, mojojs_path=None, inject_script=None): + enable_webtransport=False, mojojs_path=None, inject_script=None, + suppress_handler_traceback=None): self.test_paths = test_paths self.server = None @@ -117,6 +118,7 @@ class TestEnvironment: self.enable_webtransport = enable_webtransport self.mojojs_path = mojojs_path self.inject_script = inject_script + self.suppress_handler_traceback = suppress_handler_traceback def __enter__(self): server_log_handler = self.server_logging_ctx.__enter__() @@ -213,6 +215,9 @@ class TestEnvironment: config.doc_root = serve_path(self.test_paths) config.inject_script = self.inject_script + if self.suppress_handler_traceback is not None: + config.logging["suppress_handler_traceback"] = self.suppress_handler_traceback + return config def get_routes(self): diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/executors/executormarionette.py b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/executors/executormarionette.py index aa6d50bc87b..a18063c9801 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/executors/executormarionette.py +++ b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/executors/executormarionette.py @@ -24,7 +24,8 @@ from .base import (CallbackHandler, WdspecExecutor, get_pages, strip_server) -from .protocol import (ActionSequenceProtocolPart, +from .protocol import (AccessibilityProtocolPart, + ActionSequenceProtocolPart, AssertsProtocolPart, BaseProtocolPart, TestharnessProtocolPart, @@ -701,6 +702,17 @@ loadDevTools().catch((e) => console.error("Devtools failed to load", e)) """, asynchronous=True) +class MarionetteAccessibilityProtocolPart(AccessibilityProtocolPart): + def setup(self): + self.marionette = self.parent.marionette + + def get_computed_label(self, element): + return element.computed_label + + def get_computed_role(self, element): + return element.computed_role + + class MarionetteProtocol(Protocol): implements = [MarionetteBaseProtocolPart, MarionetteTestharnessProtocolPart, @@ -719,7 +731,8 @@ class MarionetteProtocol(Protocol): MarionetteVirtualAuthenticatorProtocolPart, MarionetteSetPermissionProtocolPart, MarionettePrintProtocolPart, - MarionetteDebugProtocolPart] + MarionetteDebugProtocolPart, + MarionetteAccessibilityProtocolPart] def __init__(self, executor, browser, capabilities=None, timeout_multiplier=1, e10s=True, ccov=False): do_delayed_imports() diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/testloader.py b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/testloader.py index 78e05264d4d..c35e509776a 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/testloader.py +++ b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/testloader.py @@ -404,6 +404,13 @@ class TestSource: for _ in range(num_of_workers): test_queue.put(TestGroup(None, None, None)) + @classmethod + def process_count(cls, requested_processes, num_test_groups): + """Get the number of processes to use. + + This must always be at least one, but otherwise not more than the number of test groups""" + return max(1, min(requested_processes, num_test_groups)) + class GroupedSource(TestSource): @classmethod @@ -430,8 +437,10 @@ class GroupedSource(TestSource): for item in groups: test_queue.put(item) - cls.add_sentinal(test_queue, kwargs["processes"]) - return test_queue + + processes = cls.process_count(kwargs["processes"], len(groups)) + cls.add_sentinal(test_queue, processes) + return test_queue, processes @classmethod def tests_by_group(cls, tests_by_type, **kwargs): @@ -451,6 +460,7 @@ class SingleTestSource(TestSource): def make_queue(cls, tests_by_type, **kwargs): mp = mpcontext.get_context() test_queue = mp.Queue() + num_test_groups = 0 for test_type, tests in tests_by_type.items(): processes = kwargs["processes"] queues = [deque([]) for _ in range(processes)] @@ -465,9 +475,11 @@ class SingleTestSource(TestSource): for item in zip(queues, itertools.repeat(test_type), metadatas): if len(item[0]) > 0: test_queue.put(TestGroup(*item)) - cls.add_sentinal(test_queue, kwargs["processes"]) + num_test_groups += 1 - return test_queue + processes = cls.process_count(kwargs["processes"], num_test_groups) + cls.add_sentinal(test_queue, processes) + return test_queue, processes @classmethod def tests_by_group(cls, tests_by_type, **kwargs): @@ -498,6 +510,7 @@ class GroupFileTestSource(TestSource): def make_queue(cls, tests_by_type, **kwargs): mp = mpcontext.get_context() test_queue = mp.Queue() + num_test_groups = 0 for test_type, tests in tests_by_type.items(): tests_by_group = cls.tests_by_group({test_type: tests}, @@ -515,10 +528,11 @@ class GroupFileTestSource(TestSource): test.update_metadata(group_metadata) test_queue.put(TestGroup(group, test_type, group_metadata)) + num_test_groups += 1 - cls.add_sentinal(test_queue, kwargs["processes"]) - - return test_queue + processes = cls.process_count(kwargs["processes"], num_test_groups) + cls.add_sentinal(test_queue, processes) + return test_queue, processes @classmethod def tests_by_group(cls, tests_by_type, **kwargs): diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/testrunner.py b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/testrunner.py index 82ffc9b84c0..30b51366c26 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/testrunner.py +++ b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/testrunner.py @@ -889,19 +889,19 @@ class TestRunnerManager(threading.Thread): def make_test_queue(tests, test_source_cls, **test_source_kwargs): - queue = test_source_cls.make_queue(tests, **test_source_kwargs) + queue, num_of_workers = test_source_cls.make_queue(tests, **test_source_kwargs) # There is a race condition that means sometimes we continue # before the tests have been written to the underlying pipe. # Polling the pipe for data here avoids that queue._reader.poll(10) assert not queue.empty() - return queue + return queue, num_of_workers class ManagerGroup: """Main thread object that owns all the TestRunnerManager threads.""" - def __init__(self, suite_name, size, test_source_cls, test_source_kwargs, + def __init__(self, suite_name, test_source_cls, test_source_kwargs, test_implementation_by_type, rerun=1, pause_after_test=False, @@ -912,7 +912,6 @@ class ManagerGroup: restart_on_new_group=True, recording=None): self.suite_name = suite_name - self.size = size self.test_source_cls = test_source_cls self.test_source_kwargs = test_source_kwargs self.test_implementation_by_type = test_implementation_by_type @@ -940,11 +939,11 @@ class ManagerGroup: def run(self, tests): """Start all managers in the group""" - self.logger.debug("Using %i processes" % self.size) - test_queue = make_test_queue(tests, self.test_source_cls, **self.test_source_kwargs) + test_queue, size = make_test_queue(tests, self.test_source_cls, **self.test_source_kwargs) + self.logger.info("Using %i child processes" % size) - for idx in range(self.size): + for idx in range(size): manager = TestRunnerManager(self.suite_name, idx, test_queue, diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptcommandline.py b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptcommandline.py index 2fe65865be5..f64d17483d1 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptcommandline.py +++ b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptcommandline.py @@ -261,6 +261,11 @@ scheme host and port.""") help="Don't run browser in headless mode") config_group.add_argument("--instrument-to-file", action="store", help="Path to write instrumentation logs to") + config_group.add_argument("--suppress-handler-traceback", action="store_true", default=None, + help="Don't write the stacktrace for exceptions in server handlers") + config_group.add_argument("--no-suppress-handler-traceback", action="store_false", + dest="supress_handler_traceback", + help="Write the stacktrace for exceptions in server handlers") build_type = parser.add_mutually_exclusive_group() build_type.add_argument("--debug-build", dest="debug", action="store_true", diff --git a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptrunner.py b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptrunner.py index 740bb7e9f42..987cf058cca 100644 --- a/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptrunner.py +++ b/tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/wptrunner.py @@ -252,7 +252,6 @@ def run_test_iteration(test_status, test_loader, test_source_kwargs, test_source extra={"run_by_dir": run_test_kwargs["run_by_dir"]}) with ManagerGroup("web-platform-tests", - run_test_kwargs["processes"], test_source_cls, test_source_kwargs, test_implementation_by_type, @@ -375,8 +374,6 @@ def run_tests(config, test_paths, product, **kwargs): test_groups=test_groups, **kwargs) - logger.info("Using %i client processes" % kwargs["processes"]) - test_status = TestStatus() repeat = kwargs["repeat"] test_status.expected_repeated_runs = repeat @@ -413,7 +410,8 @@ def run_tests(config, test_paths, product, **kwargs): env_extras, kwargs["enable_webtransport_h3"], mojojs_path, - inject_script) as test_environment: + inject_script, + kwargs["suppress_handler_traceback"]) as test_environment: recording.set(["startup", "ensure_environment"]) try: test_environment.ensure_started() diff --git a/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_handlers.py b/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_handlers.py index 26a9f797ecf..623a0e5b6a8 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_handlers.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_handlers.py @@ -19,7 +19,9 @@ class TestFileHandler(TestUsingServer): resp = self.request("/document.txt") self.assertEqual(200, resp.getcode()) self.assertEqual("text/plain", resp.info()["Content-Type"]) - self.assertEqual(open(os.path.join(doc_root, "document.txt"), 'rb').read(), resp.read()) + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() + self.assertEqual(expected, resp.read()) def test_headers(self): resp = self.request("/with_headers.txt") @@ -36,7 +38,8 @@ class TestFileHandler(TestUsingServer): resp = self.request("/document.txt", headers={"Range":"bytes=10-19"}) self.assertEqual(206, resp.getcode()) data = resp.read() - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() self.assertEqual(10, len(data)) self.assertEqual("bytes 10-19/%i" % len(expected), resp.info()['Content-Range']) self.assertEqual("10", resp.info()['Content-Length']) @@ -46,7 +49,8 @@ class TestFileHandler(TestUsingServer): resp = self.request("/document.txt", headers={"Range":"bytes=10-"}) self.assertEqual(206, resp.getcode()) data = resp.read() - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() self.assertEqual(len(expected) - 10, len(data)) self.assertEqual("bytes 10-%i/%i" % (len(expected) - 1, len(expected)), resp.info()['Content-Range']) self.assertEqual(expected[10:], data) @@ -55,7 +59,8 @@ class TestFileHandler(TestUsingServer): resp = self.request("/document.txt", headers={"Range":"bytes=-10"}) self.assertEqual(206, resp.getcode()) data = resp.read() - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() self.assertEqual(10, len(data)) self.assertEqual("bytes %i-%i/%i" % (len(expected) - 10, len(expected) - 1, len(expected)), resp.info()['Content-Range']) @@ -65,7 +70,8 @@ class TestFileHandler(TestUsingServer): resp = self.request("/document.txt", headers={"Range":"bytes=1-2,5-7,6-10"}) self.assertEqual(206, resp.getcode()) data = resp.read() - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() self.assertTrue(resp.info()["Content-Type"].startswith("multipart/byteranges; boundary=")) boundary = resp.info()["Content-Type"].split("boundary=")[1] parts = data.split(b"--" + boundary.encode("ascii")) @@ -84,7 +90,8 @@ class TestFileHandler(TestUsingServer): self.request("/document.txt", headers={"Range":"bytes=11-10"}) self.assertEqual(cm.exception.code, 416) - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() with self.assertRaises(HTTPError) as cm: self.request("/document.txt", headers={"Range":"bytes=%i-%i" % (len(expected), len(expected) + 10)}) self.assertEqual(cm.exception.code, 416) @@ -130,6 +137,7 @@ class TestFunctionHandler(TestUsingServer): self.request(route[1]) assert cm.value.code == 500 + del cm def test_tuple_2_rv(self): @wptserve.handlers.handler @@ -181,6 +189,7 @@ class TestFunctionHandler(TestUsingServer): self.request(route[1]) assert cm.value.code == 500 + del cm def test_none_rv(self): @wptserve.handlers.handler @@ -271,18 +280,21 @@ class TestPythonHandler(TestUsingServer): self.request("/no_main.py") assert cm.value.code == 500 + del cm def test_invalid(self): with pytest.raises(HTTPError) as cm: self.request("/invalid.py") assert cm.value.code == 500 + del cm def test_missing(self): with pytest.raises(HTTPError) as cm: self.request("/missing.py") assert cm.value.code == 404 + del cm class TestDirectoryHandler(TestUsingServer): diff --git a/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_input_file.py b/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_input_file.py index 93db62c8422..c2be5b780b5 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_input_file.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_input_file.py @@ -4,25 +4,35 @@ import pytest from wptserve.request import InputFile -bstr = b'This is a test document\nWith new lines\nSeveral in fact...' -rfile = '' -test_file = '' # This will be used to test the InputFile functions against -input_file = InputFile(None, 0) +def files_with_buffer(max_buffer_size=None): + bstr = b"This is a test document\nWith new lines\nSeveral in fact..." + + with BytesIO(bstr) as rfile, BytesIO(bstr) as test_file: + if max_buffer_size is not None: + old_max_buf = InputFile.max_buffer_size + InputFile.max_buffer_size = max_buffer_size + + try: + with InputFile(rfile, len(bstr)) as input_file: + yield (input_file, test_file) + finally: + if max_buffer_size is not None: + InputFile.max_buffer_size = old_max_buf -def setup_function(function): - global rfile, input_file, test_file - rfile = BytesIO(bstr) - test_file = BytesIO(bstr) - input_file = InputFile(rfile, len(bstr)) +@pytest.fixture +def files(): + yield from files_with_buffer() -def teardown_function(function): - rfile.close() - test_file.close() +@pytest.fixture +def files_small_buffer(): + yield from files_with_buffer(10) -def test_seek(): +def test_seek(files): + input_file, test_file = files + input_file.seek(2) test_file.seek(2) assert input_file.read(1) == test_file.read(1) @@ -32,7 +42,9 @@ def test_seek(): assert input_file.read(1) == test_file.read(1) -def test_seek_backwards(): +def test_seek_backwards(files): + input_file, test_file = files + input_file.seek(2) test_file.seek(2) assert input_file.tell() == test_file.tell() @@ -44,45 +56,40 @@ def test_seek_backwards(): assert input_file.read(1) == test_file.read(1) -def test_seek_negative_offset(): +def test_seek_negative_offset(files): + input_file, test_file = files + with pytest.raises(ValueError): input_file.seek(-1) -def test_seek_file_bigger_than_buffer(): - old_max_buf = InputFile.max_buffer_size - InputFile.max_buffer_size = 10 +def test_seek_file_bigger_than_buffer(files_small_buffer): + input_file, test_file = files_small_buffer - try: - input_file = InputFile(rfile, len(bstr)) + input_file.seek(2) + test_file.seek(2) + assert input_file.read(1) == test_file.read(1) - input_file.seek(2) - test_file.seek(2) - assert input_file.read(1) == test_file.read(1) - - input_file.seek(4) - test_file.seek(4) - assert input_file.read(1) == test_file.read(1) - finally: - InputFile.max_buffer_size = old_max_buf + input_file.seek(4) + test_file.seek(4) + assert input_file.read(1) == test_file.read(1) -def test_read(): +def test_read(files): + input_file, test_file = files + assert input_file.read() == test_file.read() -def test_read_file_bigger_than_buffer(): - old_max_buf = InputFile.max_buffer_size - InputFile.max_buffer_size = 10 +def test_read_file_bigger_than_buffer(files_small_buffer): + input_file, test_file = files_small_buffer - try: - input_file = InputFile(rfile, len(bstr)) - assert input_file.read() == test_file.read() - finally: - InputFile.max_buffer_size = old_max_buf + assert input_file.read() == test_file.read() -def test_readline(): +def test_readline(files): + input_file, test_file = files + assert input_file.readline() == test_file.readline() assert input_file.readline() == test_file.readline() @@ -91,59 +98,49 @@ def test_readline(): assert input_file.readline() == test_file.readline() -def test_readline_max_byte(): +def test_readline_max_byte(files): + input_file, test_file = files + line = test_file.readline() assert input_file.readline(max_bytes=len(line)//2) == line[:len(line)//2] assert input_file.readline(max_bytes=len(line)) == line[len(line)//2:] -def test_readline_max_byte_longer_than_file(): +def test_readline_max_byte_longer_than_file(files): + input_file, test_file = files + assert input_file.readline(max_bytes=1000) == test_file.readline() assert input_file.readline(max_bytes=1000) == test_file.readline() -def test_readline_file_bigger_than_buffer(): - old_max_buf = InputFile.max_buffer_size - InputFile.max_buffer_size = 10 +def test_readline_file_bigger_than_buffer(files_small_buffer): + input_file, test_file = files_small_buffer - try: - input_file = InputFile(rfile, len(bstr)) - - assert input_file.readline() == test_file.readline() - assert input_file.readline() == test_file.readline() - finally: - InputFile.max_buffer_size = old_max_buf + assert input_file.readline() == test_file.readline() + assert input_file.readline() == test_file.readline() -def test_readlines(): +def test_readlines(files): + input_file, test_file = files + assert input_file.readlines() == test_file.readlines() -def test_readlines_file_bigger_than_buffer(): - old_max_buf = InputFile.max_buffer_size - InputFile.max_buffer_size = 10 +def test_readlines_file_bigger_than_buffer(files_small_buffer): + input_file, test_file = files_small_buffer - try: - input_file = InputFile(rfile, len(bstr)) - - assert input_file.readlines() == test_file.readlines() - finally: - InputFile.max_buffer_size = old_max_buf + assert input_file.readlines() == test_file.readlines() -def test_iter(): +def test_iter(files): + input_file, test_file = files + for a, b in zip(input_file, test_file): assert a == b -def test_iter_file_bigger_than_buffer(): - old_max_buf = InputFile.max_buffer_size - InputFile.max_buffer_size = 10 +def test_iter_file_bigger_than_buffer(files_small_buffer): + input_file, test_file = files_small_buffer - try: - input_file = InputFile(rfile, len(bstr)) - - for a, b in zip(input_file, test_file): - assert a == b - finally: - InputFile.max_buffer_size = old_max_buf + for a, b in zip(input_file, test_file): + assert a == b diff --git a/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_pipes.py b/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_pipes.py index 904bfb4ee4c..beb124d1dbe 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_pipes.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_pipes.py @@ -52,17 +52,20 @@ class TestHeader(TestUsingServer): class TestSlice(TestUsingServer): def test_both_bounds(self): resp = self.request("/document.txt", query="pipe=slice(1,10)") - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() self.assertEqual(resp.read(), expected[1:10]) def test_no_upper(self): resp = self.request("/document.txt", query="pipe=slice(1)") - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() self.assertEqual(resp.read(), expected[1:]) def test_no_lower(self): resp = self.request("/document.txt", query="pipe=slice(null,10)") - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() self.assertEqual(resp.read(), expected[:10]) class TestSub(TestUsingServer): @@ -147,7 +150,8 @@ class TestTrickle(TestUsingServer): t0 = time.time() resp = self.request("/document.txt", query="pipe=trickle(1:d2:5:d1:r2)") t1 = time.time() - expected = open(os.path.join(doc_root, "document.txt"), 'rb').read() + with open(os.path.join(doc_root, "document.txt"), 'rb') as f: + expected = f.read() self.assertEqual(resp.read(), expected) self.assertGreater(6, t1-t0) diff --git a/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_response.py b/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_response.py index 4a4611f60a1..2e7249ec952 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_response.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_response.py @@ -207,14 +207,16 @@ class TestH2Response(TestUsingH2Server): def test_set_error(self): @wptserve.handlers.handler def handler(request, response): - response.set_error(503, message="Test error") + response.set_error(503, "Test error") route = ("GET", "/h2test/test_set_error", handler) self.server.router.register(*route) resp = self.client.get(route[1]) assert resp.status_code == 503 - assert json.loads(resp.content) == json.loads("{\"error\": {\"message\": \"Test error\", \"code\": 503}}") + error = json.loads(resp.content)["error"] + assert error["code"] == 503 + assert "Test error" in error["message"] def test_file_like_response(self): @wptserve.handlers.handler diff --git a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/config.py b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/config.py index b87795430fc..50e20f05f0b 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/config.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/config.py @@ -133,7 +133,6 @@ class ConfigBuilder: "server_host": None, "ports": {"http": [8000]}, "check_subdomains": True, - "log_level": "debug", "bind_address": True, "ssl": { "type": "none", @@ -152,14 +151,18 @@ class ConfigBuilder: "host_cert_path": None, }, }, - "aliases": [] + "aliases": [], + "logging": { + "level": "debug", + "suppress_handler_traceback": False, + } } default_config_cls = Config # Configuration properties that are computed. Each corresponds to a method # _get_foo, which is called with the current data dictionary. The properties # are computed in the order specified in the list. - computed_properties = ["log_level", + computed_properties = ["logging", "paths", "server_host", "ports", @@ -209,6 +212,12 @@ class ConfigBuilder: else: self.__dict__[key] = value + def __getattr__(self, key): + try: + return self._data[key] + except KeyError as e: + raise AttributeError from e + def update(self, override): """Load an overrides dict to override config values""" override = override.copy() @@ -251,8 +260,10 @@ class ConfigBuilder: self._ssl_env.__exit__(*args) self._ssl_env = None - def _get_log_level(self, data): - return data["log_level"].upper() + def _get_logging(self, data): + logging = data["logging"] + logging["level"] = logging["level"].upper() + return logging def _get_paths(self, data): return {"doc_root": data["doc_root"]} diff --git a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/handlers.py b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/handlers.py index bae6a8f1375..00ba06789c8 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/handlers.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/handlers.py @@ -2,7 +2,6 @@ import json import os -import traceback from collections import defaultdict from urllib.parse import quote, unquote, urljoin @@ -361,9 +360,8 @@ class FunctionHandler: rv = self.func(request, response) except HTTPException: raise - except Exception: - msg = traceback.format_exc() - raise HTTPException(500, message=msg) + except Exception as e: + raise HTTPException(500) from e if rv is not None: if isinstance(rv, tuple): if len(rv) == 3: diff --git a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/request.py b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/request.py index bfbbae3c28c..9207b4dbf4b 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/request.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/request.py @@ -60,6 +60,16 @@ class InputFile: else: self._buf = BytesIO() + def close(self): + self._buf.close() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + return False + @property def _buf_position(self): rv = self._buf.tell() @@ -299,6 +309,16 @@ class Request: self.server = Server(self) + def close(self): + return self.raw_input.close() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + return False + def __repr__(self): return "" % (self.method, self.url) diff --git a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/response.py b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/response.py index 5c0ea7dd8d5..a6ece62dab1 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/response.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/response.py @@ -1,10 +1,11 @@ # mypy: allow-untyped-defs +import json +import uuid +import traceback from collections import OrderedDict from datetime import datetime, timedelta from io import BytesIO -import json -import uuid from hpack.struct import HeaderTuple from http.cookies import BaseCookie, Morsel @@ -203,10 +204,14 @@ class Response: elif isinstance(self.content, str): yield self.content.encode(self.encoding) elif hasattr(self.content, "read"): - if read_file: - yield self.content.read() - else: - yield self.content + # Read the file in chunks rather than reading the whole file into + # memory at once. (See also ResponseWriter.file_chunk_size) + while True: + read = self.content.read(32 * 1024) + if len(read) == 0: + break + yield read + self.content.close() else: for item in self.content: if hasattr(item, "__call__"): @@ -234,27 +239,46 @@ class Response: self.write_status_headers() self.write_content() - def set_error(self, code, message=""): + def set_error(self, code, err=None): """Set the response status headers and return a JSON error object: {"error": {"code": code, "message": message}} code is an int (HTTP status code), and message is a text string. """ - err = {"code": code, - "message": message} - data = json.dumps({"error": err}) + if 500 <= code < 600: + message = self._format_server_error(err) + self.logger.warning(message) + else: + if err is None: + message = "" + else: + message = str(err) + + data = json.dumps({"error": { + "code": code, + "message": message} + }) self.status = code self.headers = [("Content-Type", "application/json"), ("Content-Length", len(data))] self.content = data - if code == 500: - if isinstance(message, str) and message: - first_line = message.splitlines()[0] - else: - first_line = "" - self.logger.error("Exception loading %s: %s" % (self.request.url, - first_line)) - self.logger.info(message) + + def _format_server_error(self, err): + if err is None: + suffix = "" + elif isinstance(err, str): + suffix = err + elif self.request.server.config.logging["suppress_handler_traceback"]: + frame = traceback.extract_tb(err.__traceback__)[-1] + suffix = (f"""File "{frame.filename}", line {frame.lineno} """ + f"""in {frame.name} (traceback suppressed)""") + else: + tb = "\n".join(f" {line}" + for line in traceback.format_tb(err.__traceback__)) + suffix = f"""Traceback (most recent call last): +{tb} {type(err).__name__}: {err} +""" + return f"Internal server error loading {self.request.url}:\n {suffix}" class MultipartContent: diff --git a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/server.py b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/server.py index 94b70ad93f5..c9a252e8d3d 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/server.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/server.py @@ -4,7 +4,6 @@ import errno import http.server import os import socket -from socketserver import ThreadingMixIn import ssl import sys import threading @@ -33,7 +32,7 @@ from .logger import get_logger from .request import Server, Request, H2Request from .response import Response, H2Response from .router import Router -from .utils import HTTPException, isomorphic_decode, isomorphic_encode +from .utils import HTTPException, get_error_cause, isomorphic_decode, isomorphic_encode from .constants import h2_headers from .ws_h2_handshake import WsH2Handshaker @@ -129,7 +128,7 @@ class RequestRewriter: request_handler.path = new_url -class WebTestServer(ThreadingMixIn, http.server.HTTPServer): +class WebTestServer(http.server.ThreadingHTTPServer): allow_reuse_address = True acceptable_errors = (errno.EPIPE, errno.ECONNABORTED) request_queue_size = 2000 @@ -190,7 +189,7 @@ class WebTestServer(ThreadingMixIn, http.server.HTTPServer): else: hostname_port = ("",server_address[1]) - http.server.HTTPServer.__init__(self, hostname_port, request_handler_cls, **kwargs) + super().__init__(hostname_port, request_handler_cls) if config is not None: Server.config = config @@ -243,27 +242,27 @@ class BaseWebTestRequestHandler(http.server.BaseHTTPRequestHandler): def __init__(self, *args, **kwargs): self.logger = get_logger() - http.server.BaseHTTPRequestHandler.__init__(self, *args, **kwargs) + super().__init__(*args, **kwargs) def finish_handling_h1(self, request_line_is_valid): self.server.rewriter.rewrite(self) - request = Request(self) - response = Response(self, request) + with Request(self) as request: + response = Response(self, request) - if request.method == "CONNECT": - self.handle_connect(response) - return + if request.method == "CONNECT": + self.handle_connect(response) + return - if not request_line_is_valid: - response.set_error(414) - response.write() - return + if not request_line_is_valid: + response.set_error(414) + response.write() + return - self.logger.debug(f"{request.method} {request.request_path}") - handler = self.server.router.get_handler(request) - self.finish_handling(request, response, handler) + self.logger.debug(f"{request.method} {request.request_path}") + handler = self.server.router.get_handler(request) + self.finish_handling(request, response, handler) def finish_handling(self, request, response, handler): # If the handler we used for the request had a non-default base path @@ -288,12 +287,10 @@ class BaseWebTestRequestHandler(http.server.BaseHTTPRequestHandler): try: handler(request, response) except HTTPException as e: - if 500 <= e.code < 600: - self.logger.warning("HTTPException in handler: %s" % e) - self.logger.warning(traceback.format_exc()) - response.set_error(e.code, str(e)) + exc = get_error_cause(e) if 500 <= e.code < 600 else e + response.set_error(e.code, exc) except Exception as e: - self.respond_with_error(response, e) + response.set_error(500, e) self.logger.debug("%i %s %s (%s) %i" % (response.status[0], request.method, request.request_path, @@ -332,15 +329,6 @@ class BaseWebTestRequestHandler(http.server.BaseHTTPRequestHandler): self.setup() return - def respond_with_error(self, response, e): - message = str(e) - if message: - err = [message] - else: - err = [] - err.append(traceback.format_exc()) - response.set_error(500, "\n".join(err)) - class Http2WebTestRequestHandler(BaseWebTestRequestHandler): protocol_version = "HTTP/2.0" @@ -380,7 +368,11 @@ class Http2WebTestRequestHandler(BaseWebTestRequestHandler): data = connection.data_to_send() window_size = connection.remote_settings.initial_window_size - self.request.sendall(data) + try: + self.request.sendall(data) + except ConnectionResetError: + self.logger.warning("Connection reset during h2 setup") + return # Dict of { stream_id: (thread, queue) } stream_queues = {} @@ -490,8 +482,8 @@ class Http2WebTestRequestHandler(BaseWebTestRequestHandler): try: handshaker.do_handshake() except HandshakeException as e: - self.logger.info('Handshake failed for error: %s' % e) - h2response.set_error(e.status) + self.logger.info("Handshake failed") + h2response.set_error(e.status, e) h2response.write() return except AbortedByUserException: @@ -643,10 +635,11 @@ class Http2WebTestRequestHandler(BaseWebTestRequestHandler): try: return handler.frame_handler(request) except HTTPException as e: - response.set_error(e.code, str(e)) + exc = get_error_cause(e) if 500 <= e.code < 600 else e + response.set_error(exc.code, exc) response.write() except Exception as e: - self.respond_with_error(response, e) + response.set_error(500, e) response.write() @@ -726,10 +719,9 @@ class Http1WebTestRequestHandler(BaseWebTestRequestHandler): self.close_connection = True return - except Exception: - err = traceback.format_exc() + except Exception as e: if response: - response.set_error(500, err) + response.set_error(500, e) response.write() def get_request_line(self): diff --git a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/stash.py b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/stash.py index 90c3078ff82..ed185c1756f 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/stash.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/stash.py @@ -194,7 +194,11 @@ class Stash: if isinstance(key, bytes): # UUIDs are within the ASCII charset. key = key.decode('ascii') - return (isomorphic_encode(path), uuid.UUID(key).bytes) + try: + my_uuid = uuid.UUID(key).bytes + except ValueError as e: + raise ValueError(f"""Invalid UUID "{key}" used as stash key""") from e + return (isomorphic_encode(path), my_uuid) def put(self, key, value, path=None): """Place a value in the shared stash. diff --git a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/utils.py b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/utils.py index a592e416376..e711e40725b 100644 --- a/tests/wpt/web-platform-tests/tools/wptserve/wptserve/utils.py +++ b/tests/wpt/web-platform-tests/tools/wptserve/wptserve/utils.py @@ -193,3 +193,12 @@ def http2_compatible() -> bool: (ssl_v[0] == 1 and (ssl_v[1] == 1 or (ssl_v[1] == 0 and ssl_v[2] >= 2)))) + + +def get_error_cause(exc: BaseException) -> BaseException: + """Get the parent cause/context from an exception""" + if exc.__cause__ is not None: + return exc.__cause__ + if exc.__context__ is not None: + return exc.__context__ + return exc diff --git a/tests/wpt/web-platform-tests/wai-aria/META.yml b/tests/wpt/web-platform-tests/wai-aria/META.yml index 25ab1c28495..502b9c30251 100644 --- a/tests/wpt/web-platform-tests/wai-aria/META.yml +++ b/tests/wpt/web-platform-tests/wai-aria/META.yml @@ -1,6 +1,8 @@ spec: https://w3c.github.io/aria/ suggested_reviewers: - cookiecrook + - spectranaut + - jnurthen - halindrome - joanmarie - michael-n-cooper diff --git a/tests/wpt/web-platform-tests/wai-aria/scripts/aria-utils.js b/tests/wpt/web-platform-tests/wai-aria/scripts/aria-utils.js index 41d8535f91b..e6411a9a0ed 100644 --- a/tests/wpt/web-platform-tests/wai-aria/scripts/aria-utils.js +++ b/tests/wpt/web-platform-tests/wai-aria/scripts/aria-utils.js @@ -5,8 +5,14 @@ const AriaUtils = { /* Tests simple role assignment:
x
Not intended for nested, context-dependent, or other complex role tests. + + Ex: AriaUtils.assignAndVerifyRolesByRoleNames(["group", "main", "button"]) + */ assignAndVerifyRolesByRoleNames: function(roleNames) { + if (!Array.isArray(roleNames) || !roleNames.length) { + throw `Param roleNames of assignAndVerifyRolesByRoleNames("${roleNames}") should be an array containing at least one role string.`; + } for (const role of roleNames) { promise_test(async t => { let el = document.createElement("div"); @@ -20,9 +26,10 @@ const AriaUtils = { } }, + /* - Tests computed role of all elements matching selector - against the string value of their data-role attribute. + Tests computed ROLE of all elements matching selector + against the string value of their data-expectedrole attribute. Ex:
{ const expectedRole = el.getAttribute("data-expectedrole"); @@ -57,5 +67,51 @@ const AriaUtils = { } }, + + /* + Tests computed LABEL of all elements matching selector + against the string value of their data-expectedlabel attribute. + + Ex:
+ + AriaUtils.verifyLabelsBySelector(".ex") + + */ + verifyLabelsBySelector: function(selector) { + const els = document.querySelectorAll(selector); + if (!els.length) { + throw `Selector passed in verifyLabelsBySelector("${selector}") should match at least one element.`; + } + for (const el of els) { + let label = el.getAttribute("data-expectedlabel"); + let testName = el.getAttribute("data-testname") || label; // data-testname optional if label is unique per test file + promise_test(async t => { + const expectedLabel = el.getAttribute("data-expectedlabel"); + + // ensure ID existence and uniqueness for the webdriver callback + if (!el.id) { + let labelCount = 1; + let elID = `labelTest${labelCount}`; + while(document.getElementById(elID)) { + labelCount++; + elID = `labelTest${labelCount}`; + } + el.id = elID; + } + + let computedLabel = await test_driver.get_computed_label(el); + + // Todo: Remove whitespace normalization after https://github.com/w3c/accname/issues/192 is addressed. Change prior line back to `const`, too. + computedLabel = computedLabel.trim() + + assert_equals(computedLabel, expectedLabel, el.outerHTML); + }, `${testName}`); + } + }, + + }; diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/__init__.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/__init__.py index 3aa0c3a19d1..7aa3355929e 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/__init__.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/__init__.py @@ -3,7 +3,7 @@ import json from webdriver.bidi.modules.script import ContextTarget -async def get_events(context, bidi_session): +async def get_events(bidi_session, context): """Return list of key events recorded on the test_actions.html page.""" events_str = await bidi_session.script.evaluate( expression="JSON.stringify(allEvents.events)", @@ -26,3 +26,13 @@ async def get_events(context, bidi_session): if "code" in e and e["code"] == "Unidentified": e["code"] = "" return events + + +async def get_keys_value(bidi_session, context): + keys_value = await bidi_session.script.evaluate( + expression="""document.getElementById("keys").value""", + target=ContextTarget(context), + await_promise=False, + ) + + return keys_value["value"] diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/conftest.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/conftest.py index 0ec3174163f..71a1152729a 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/conftest.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/conftest.py @@ -1,7 +1,9 @@ import pytest +import pytest_asyncio from webdriver.bidi.modules.script import ContextTarget +from tests.support.keys import Keys @pytest.fixture def get_focused_key_input(bidi_session, top_context): @@ -19,3 +21,26 @@ def get_focused_key_input(bidi_session, top_context): ) return get_focused_key_input + + +@pytest_asyncio.fixture(autouse=True) +async def release_actions(bidi_session, top_context): + # release all actions after each test + yield + await bidi_session.input.release_actions(context=top_context["context"]) + + +@pytest_asyncio.fixture +async def setup_key_test(load_static_test_page, get_focused_key_input): + await load_static_test_page(page="test_actions.html") + await get_focused_key_input() + + +@pytest_asyncio.fixture +async def setup_wheel_test(bidi_session, top_context, load_static_test_page): + await load_static_test_page(page="test_actions_scroll.html") + await bidi_session.script.evaluate( + expression="document.scrollingElement.scrollTop = 0", + target=ContextTarget(top_context["context"]), + await_promise=False, + ) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/__init__.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/__init__.py index e69de29bb2d..27bf9543b8e 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/__init__.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/__init__.py @@ -0,0 +1,64 @@ +from webdriver.bidi.modules.script import ContextTarget + + +def remote_mapping_to_dict(js_object): + obj = {} + for key, value in js_object: + obj[key] = value["value"] + + return obj + + +async def get_inview_center_bidi(bidi_session, context, element): + elem_rect = await get_element_rect(bidi_session, context=context, element=element) + viewport_rect = await get_viewport_rect(bidi_session, context=context) + + x = { + "left": max(0, min(elem_rect["x"], elem_rect["x"] + elem_rect["width"])), + "right": min( + viewport_rect["width"], + max(elem_rect["x"], elem_rect["x"] + elem_rect["width"]), + ), + } + + y = { + "top": max(0, min(elem_rect["y"], elem_rect["y"] + elem_rect["height"])), + "bottom": min( + viewport_rect["height"], + max(elem_rect["y"], elem_rect["y"] + elem_rect["height"]), + ), + } + + return { + "x": (x["left"] + x["right"]) / 2, + "y": (y["top"] + y["bottom"]) / 2, + } + + +async def get_element_rect(bidi_session, context, element): + result = await bidi_session.script.call_function( + function_declaration=""" +el => el.getBoundingClientRect().toJSON() +""", + arguments=[element], + target=ContextTarget(context["context"]), + await_promise=False, + ) + + return remote_mapping_to_dict(result["value"]) + + +async def get_viewport_rect(bidi_session, context): + expression = """ + ({ + height: window.innerHeight || document.documentElement.clientHeight, + width: window.innerWidth || document.documentElement.clientWidth, + }); + """ + result = await bidi_session.script.evaluate( + expression=expression, + target=ContextTarget(context["context"]), + await_promise=False, + ) + + return remote_mapping_to_dict(result["value"]) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/invalid.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/invalid.py index 4dee9e33654..53b7f3a323e 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/invalid.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/invalid.py @@ -1,7 +1,11 @@ import pytest from webdriver.bidi.modules.input import Actions -from webdriver.bidi.error import InvalidArgumentException, NoSuchFrameException +from webdriver.bidi.error import ( + InvalidArgumentException, + MoveTargetOutOfBoundsException, + NoSuchFrameException, +) pytestmark = pytest.mark.asyncio @@ -20,3 +24,85 @@ async def test_params_contexts_value_invalid_value(bidi_session): actions.add_key() with pytest.raises(NoSuchFrameException): await bidi_session.input.perform_actions(actions=actions, context="foo") + + +@pytest.mark.parametrize( + "value", + [("fa"), ("\u0BA8\u0BBFb"), ("\u0BA8\u0BBF\u0BA8"), ("\u1100\u1161\u11A8c")], +) +async def test_params_actions_invalid_value_multiple_codepoints( + bidi_session, top_context, setup_key_test, value +): + actions = Actions() + actions.add_key().key_down(value).key_up(value) + with pytest.raises(InvalidArgumentException): + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + +@pytest.mark.parametrize("missing", ["x", "y"]) +async def test_params_actions_missing_coordinates(bidi_session, top_context, missing): + actions = Actions() + pointer_input_source = actions.add_pointer().pointer_move(x=0, y=0) + + json_actions = actions.to_json() + pointer_input_source_json = json_actions[-1]["actions"] + del pointer_input_source_json[-1][missing] + + with pytest.raises(InvalidArgumentException): + await bidi_session.input.perform_actions( + actions=json_actions, context=top_context["context"] + ) + + +@pytest.mark.parametrize("missing", ["x", "y", "deltaX", "deltaY"]) +async def test_params_actions_missing_wheel_property( + bidi_session, top_context, missing +): + actions = Actions() + wheel_input_source = actions.add_wheel().scroll(x=0, y=0, delta_x=5, delta_y=10) + + json_actions = actions.to_json() + wheel_input_actions_json = json_actions[-1]["actions"] + del wheel_input_actions_json[-1][missing] + + with pytest.raises(InvalidArgumentException): + await bidi_session.input.perform_actions( + actions=json_actions, context=top_context["context"] + ) + + +async def test_params_actions_origin_element_outside_viewport( + bidi_session, top_context, get_actions_origin_page, get_element +): + url = get_actions_origin_page( + """width: 100px; height: 50px; background: green; + position: relative; left: -200px; top: -100px;""" + ) + await bidi_session.browsing_context.navigate( + context=top_context["context"], + url=url, + wait="complete", + ) + + elem = await get_element("#inner") + + actions = Actions() + actions.add_pointer().pointer_move(x=0, y=0, origin=elem) + with pytest.raises(MoveTargetOutOfBoundsException): + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + +@pytest.mark.parametrize("origin", ["viewport", "pointer"]) +async def test_params_actions_origin_outside_viewport( + bidi_session, top_context, origin +): + actions = Actions() + actions.add_pointer().pointer_move(x=-50, y=-50, origin=origin) + with pytest.raises(MoveTargetOutOfBoundsException): + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key.py index bed2182f34c..0521e9ccd42 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key.py @@ -1,14 +1,316 @@ +import copy import pytest +from collections import defaultdict + from webdriver.bidi.modules.input import Actions +from webdriver.bidi.modules.script import ContextTarget + +from tests.support.helpers import filter_dict, filter_supported_key_events +from tests.support.keys import ALL_EVENTS, Keys, ALTERNATIVE_KEY_NAMES +from .. import get_events, get_keys_value pytestmark = pytest.mark.asyncio +async def test_key_backspace(bidi_session, top_context, setup_key_test): + actions = Actions() + actions.add_key().send_keys("efcd").send_keys([Keys.BACKSPACE, Keys.BACKSPACE]) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert keys_value == "ef" + + +@pytest.mark.parametrize( + "value", + [ + ("\U0001F604"), + ("\U0001F60D"), + ("\u0BA8\u0BBF"), + ("\u1100\u1161\u11A8"), + ], +) +async def test_key_codepoint( + bidi_session, top_context, setup_key_test, value +): + # Not using send_keys() because we always want to treat value as + # one character here. `len(value)` varies by platform for non-BMP characters, + # so we don't want to iterate over value. + + actions = Actions() + (actions.add_key().key_down(value).key_up(value)) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + # events sent by major browsers are inconsistent so only check key value + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert keys_value == value + + +@pytest.mark.parametrize( + "key,event", + [ + (Keys.ESCAPE, "ESCAPE"), + (Keys.RIGHT, "RIGHT"), + ], +) +async def test_key_non_printable_key( + bidi_session, top_context, setup_key_test, key, event +): + code = ALL_EVENTS[event]["code"] + value = ALL_EVENTS[event]["key"] + + actions = Actions() + (actions.add_key().key_down(key).key_up(key)) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + all_events = await get_events(bidi_session, top_context["context"]) + + expected = [ + {"code": code, "key": value, "type": "keydown"}, + {"code": code, "key": value, "type": "keypress"}, + {"code": code, "key": value, "type": "keyup"}, + ] + + # Make a copy for alternate key property values + # Note: only keydown and keyup are affected by alternate key names + alt_expected = copy.deepcopy(expected) + if event in ALTERNATIVE_KEY_NAMES: + alt_expected[0]["key"] = ALTERNATIVE_KEY_NAMES[event] + alt_expected[2]["key"] = ALTERNATIVE_KEY_NAMES[event] + + (_, expected) = filter_supported_key_events(all_events, expected) + (events, alt_expected) = filter_supported_key_events(all_events, alt_expected) + if len(events) == 2: + # most browsers don't send a keypress for non-printable keys + assert events == [expected[0], expected[2]] or events == [ + alt_expected[0], + alt_expected[2], + ] + else: + assert events == expected or events == alt_expected + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert len(keys_value) == 0 + + +@pytest.mark.parametrize( + "key, event", + [ + (Keys.ALT, "ALT"), + (Keys.CONTROL, "CONTROL"), + (Keys.META, "META"), + (Keys.SHIFT, "SHIFT"), + (Keys.R_ALT, "R_ALT"), + (Keys.R_CONTROL, "R_CONTROL"), + (Keys.R_META, "R_META"), + (Keys.R_SHIFT, "R_SHIFT"), + ], +) +async def test_key_modifier_key( + bidi_session, top_context, setup_key_test, key, event +): + code = ALL_EVENTS[event]["code"] + value = ALL_EVENTS[event]["key"] + + actions = Actions() + (actions.add_key().key_down(key).key_up(key)) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + all_events = await get_events(bidi_session, top_context["context"]) + + expected = [ + {"code": code, "key": value, "type": "keydown"}, + {"code": code, "key": value, "type": "keyup"}, + ] + + (events, expected) = filter_supported_key_events(all_events, expected) + assert events == expected + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert len(keys_value) == 0 + + +@pytest.mark.parametrize( + "value,code", + [ + ("a", "KeyA"), + ("a", "KeyA"), + ('"', "Quote"), + (",", "Comma"), + ("\u00E0", ""), + ("\u0416", ""), + ("@", "Digit2"), + ("\u2603", ""), + ("\uF6C2", ""), # PUA + ], +) +async def test_key_printable_key( + bidi_session, + top_context, + setup_key_test, + value, + code, +): + actions = Actions() + (actions.add_key().key_down(value).key_up(value)) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + all_events = await get_events(bidi_session, top_context["context"]) + + expected = [ + {"code": code, "key": value, "type": "keydown"}, + {"code": code, "key": value, "type": "keypress"}, + {"code": code, "key": value, "type": "keyup"}, + ] + + (events, expected) = filter_supported_key_events(all_events, expected) + assert events == expected + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert keys_value == value + + +@pytest.mark.parametrize("use_keyup", [True, False]) +async def test_key_printable_sequence( + bidi_session, top_context, setup_key_test, use_keyup +): + actions = Actions() + key_source = actions.add_key() + if use_keyup: + actions.add_key().send_keys("ab") + else: + actions.add_key().key_down("a").key_down("b") + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + all_events = await get_events(bidi_session, top_context["context"]) + + expected = [ + {"code": "KeyA", "key": "a", "type": "keydown"}, + {"code": "KeyA", "key": "a", "type": "keypress"}, + {"code": "KeyA", "key": "a", "type": "keyup"}, + {"code": "KeyB", "key": "b", "type": "keydown"}, + {"code": "KeyB", "key": "b", "type": "keypress"}, + {"code": "KeyB", "key": "b", "type": "keyup"}, + ] + expected = [e for e in expected if use_keyup or e["type"] is not "keyup"] + + (events, expected) = filter_supported_key_events(all_events, expected) + assert events == expected + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert keys_value == "ab" + + +@pytest.mark.parametrize("name,expected", ALL_EVENTS.items()) +async def test_key_special_key_sends_keydown( + bidi_session, + top_context, + setup_key_test, + name, + expected, +): + if name.startswith("F"): + # Prevent default behavior for F1, etc., but only after keydown + # bubbles up to body. (Otherwise activated browser menus/functions + # may interfere with subsequent tests.) + await bidi_session.script.evaluate( + expression=""" + document.body.addEventListener("keydown", + function(e) { e.preventDefault() }); + """, + target=ContextTarget(top_context["context"]), + await_promise=False, + ) + + actions = Actions() + (actions.add_key().key_down(getattr(Keys, name))) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + # only interested in keydown + all_events = await get_events(bidi_session, top_context["context"]) + first_event = all_events[0] + # make a copy so we can throw out irrelevant keys and compare to events + expected = dict(expected) + + del expected["value"] + + # make another copy for alternative key names + alt_expected = copy.deepcopy(expected) + if name in ALTERNATIVE_KEY_NAMES: + alt_expected["key"] = ALTERNATIVE_KEY_NAMES[name] + + # check and remove keys that aren't in expected + assert first_event["type"] == "keydown" + assert first_event["repeat"] is False + first_event = filter_dict(first_event, expected) + if first_event["code"] is None: + del first_event["code"] + del expected["code"] + del alt_expected["code"] + assert first_event == expected or first_event == alt_expected + # only printable characters should be recorded in input field + keys_value = await get_keys_value(bidi_session, top_context["context"]) + if len(expected["key"]) == 1: + assert keys_value == expected["key"] + else: + assert len(keys_value) == 0 + + +async def test_key_space(bidi_session, top_context, setup_key_test): + actions = Actions() + ( + actions.add_key() + .key_down(Keys.SPACE) + .key_up(Keys.SPACE) + .key_down(" ") + .key_up(" ") + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + all_events = await get_events(bidi_session, top_context["context"]) + + by_type = defaultdict(list) + for event in all_events: + by_type[event["type"]].append(event) + + for event_type in by_type: + events = by_type[event_type] + assert len(events) == 2 + assert events[0] == events[1] + + +async def test_keyup_only_sends_no_events(bidi_session, top_context, setup_key_test): + actions = Actions() + actions.add_key().key_up("a") + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + events = await get_events(bidi_session, top_context["context"]) + assert len(events) == 0 + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert len(keys_value) == 0 + + async def test_null_response_value(bidi_session, top_context): actions = Actions() actions.add_key().key_down("a").key_up("a") - value = await bidi_session.input.perform_actions(actions=actions, - context=top_context["context"]) + value = await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) assert value == {} - diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key_events.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key_events.py deleted file mode 100644 index e222776d1f9..00000000000 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key_events.py +++ /dev/null @@ -1,55 +0,0 @@ -import pytest - -from webdriver.bidi.modules.input import Actions -from webdriver.bidi.modules.script import ContextTarget - -from tests.support.helpers import filter_supported_key_events -from .. import get_events - -pytestmark = pytest.mark.asyncio - - -@pytest.mark.parametrize("value,code", [ - (u"a", "KeyA",), - ("a", "KeyA",), - (u"\"", "Quote"), - (u",", "Comma"), - (u"\u00E0", ""), - (u"\u0416", ""), - (u"@", "Digit2"), - (u"\u2603", ""), - (u"\uF6C2", ""), # PUA -]) -async def test_printable_key_sends_correct_events( - bidi_session, top_context, test_actions_page_bidi, get_focused_key_input, value, code -): - await test_actions_page_bidi() - elem = await get_focused_key_input() - - actions = Actions() - (actions.add_key() - .key_down(value) - .key_up(value)) - await bidi_session.input.perform_actions(actions=actions, - context=top_context["context"]) - - all_events = await get_events(top_context["context"], bidi_session) - - expected = [ - {"code": code, "key": value, "type": "keydown"}, - {"code": code, "key": value, "type": "keypress"}, - {"code": code, "key": value, "type": "keyup"}, - ] - - (events, expected) = filter_supported_key_events(all_events, expected) - assert events == expected - - keys_value = await bidi_session.script.call_function(function_declaration=""" -(elem) => { - return elem.value -}""", - target=ContextTarget(top_context["context"]), - arguments=[elem], - await_promise=False) - - assert keys_value["value"] == value diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key_modifier.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key_modifier.py new file mode 100644 index 00000000000..e319bb70aa8 --- /dev/null +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/key_modifier.py @@ -0,0 +1,163 @@ +import pytest + +from webdriver.bidi.modules.input import Actions + +from tests.support.keys import Keys +from .. import get_keys_value + +pytestmark = pytest.mark.asyncio + + +async def test_meta_or_ctrl_with_printable_and_backspace_deletes_all_text( + bidi_session, top_context, setup_key_test, modifier_key +): + actions = Actions() + ( + actions.add_key() + .send_keys("abc d") + .key_down(modifier_key) + .key_down("a") + .key_up(modifier_key) + .key_up("a") + .key_down(Keys.BACKSPACE) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert keys_value == "" + + +async def test_meta_or_ctrl_with_printable_cut_and_paste_text( + bidi_session, top_context, setup_key_test, modifier_key +): + initial = "abc d" + actions = Actions() + ( + actions.add_key() + .send_keys(initial) + .key_down(modifier_key) + .key_down("a") + .key_up(modifier_key) + .key_up("a") + .key_down(modifier_key) + .key_down("x") + .key_up(modifier_key) + .key_up("x") + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert keys_value == "" + + actions = Actions() + ( + actions.add_key() + .key_down(modifier_key) + .key_down("v") + .key_up(modifier_key) + .key_up("v") + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert keys_value == initial + + +async def test_meta_or_ctrl_with_printable_copy_and_paste_text( + bidi_session, top_context, setup_key_test, modifier_key +): + initial = "abc d" + actions = Actions() + ( + actions.add_key() + .send_keys(initial) + .key_down(modifier_key) + .key_down("a") + .key_up(modifier_key) + .key_up("a") + .key_down(modifier_key) + .key_down("c") + .key_up(modifier_key) + .key_up("c") + .send_keys([Keys.RIGHT]) + .key_down(modifier_key) + .key_down("v") + .key_up(modifier_key) + .key_up("v") + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + assert keys_value == initial * 2 + + +@pytest.mark.parametrize("modifier", [Keys.SHIFT, Keys.R_SHIFT]) +async def test_key_modifier_shift_non_printable_keys( + bidi_session, top_context, setup_key_test, modifier +): + actions = Actions() + ( + actions.add_key() + .key_down("f") + .key_up("f") + .key_down("o") + .key_up("o") + .key_down("o") + .key_up("o") + .key_down(modifier) + .key_down(Keys.BACKSPACE) + .key_up(modifier) + .key_up(Keys.BACKSPACE) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + + assert keys_value == "fo" + + +@pytest.mark.parametrize("modifier", [Keys.SHIFT, Keys.R_SHIFT]) +async def test_key_modifier_shift_printable_keys( + bidi_session, top_context, setup_key_test, modifier +): + actions = Actions() + ( + actions.add_key() + .key_down("b") + .key_up("b") + .key_down(modifier) + .key_down("c") + .key_up(modifier) + .key_up("c") + .key_down("d") + .key_up("d") + .key_down(modifier) + .key_down("e") + .key_up("e") + .key_down("f") + .key_up(modifier) + .key_up("f") + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + keys_value = await get_keys_value(bidi_session, top_context["context"]) + + assert keys_value == "bCdEF" diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse.py new file mode 100644 index 00000000000..b73d3d859dd --- /dev/null +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse.py @@ -0,0 +1,252 @@ +import pytest + +from webdriver.bidi.modules.input import Actions + +from tests.support.asserts import assert_move_to_coordinates +from tests.support.helpers import filter_dict + +from .. import get_events +from . import get_element_rect, get_inview_center_bidi + +pytestmark = pytest.mark.asyncio + + +async def test_click_at_coordinates(bidi_session, top_context, load_static_test_page): + await load_static_test_page(page="test_actions.html") + + div_point = { + "x": 82, + "y": 187, + } + actions = Actions() + ( + actions.add_pointer() + .pointer_move(x=div_point["x"], y=div_point["y"], duration=1000) + .pointer_down(button=0) + .pointer_up(button=0) + ) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + events = await get_events(bidi_session, top_context["context"]) + + assert len(events) == 4 + assert_move_to_coordinates(div_point, "outer", events) + + for e in events: + if e["type"] != "mousedown": + assert e["buttons"] == 0 + assert e["button"] == 0 + + expected = [ + {"type": "mousedown", "buttons": 1}, + {"type": "mouseup", "buttons": 0}, + {"type": "click", "buttons": 0}, + ] + filtered_events = [filter_dict(e, expected[0]) for e in events] + assert expected == filtered_events[1:] + + +async def test_context_menu_at_coordinates( + bidi_session, top_context, load_static_test_page +): + await load_static_test_page(page="test_actions.html") + + div_point = { + "x": 82, + "y": 187, + } + + actions = Actions() + ( + actions.add_pointer() + .pointer_move(x=div_point["x"], y=div_point["y"]) + .pointer_down(button=2) + .pointer_up(button=2) + ) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + events = await get_events(bidi_session, top_context["context"]) + assert len(events) == 4 + + expected = [ + {"type": "mousedown", "button": 2}, + {"type": "contextmenu", "button": 2}, + ] + filtered_events = [filter_dict(e, expected[0]) for e in events] + mousedown_contextmenu_events = [ + x for x in filtered_events if x["type"] in ["mousedown", "contextmenu"] + ] + assert expected == mousedown_contextmenu_events + + +async def test_click_element_center( + bidi_session, top_context, get_element, load_static_test_page +): + await load_static_test_page(page="test_actions.html") + + outer = await get_element("#outer") + center = await get_inview_center_bidi( + bidi_session, context=top_context, element=outer + ) + + actions = Actions() + ( + actions.add_pointer() + .pointer_move(x=0, y=0, origin=outer) + .pointer_down(button=0) + .pointer_up(button=0) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + events = await get_events(bidi_session, top_context["context"]) + assert len(events) == 4 + + event_types = [e["type"] for e in events] + assert ["mousemove", "mousedown", "mouseup", "click"] == event_types + for e in events: + if e["type"] != "mousemove": + assert e["pageX"] == pytest.approx(center["x"], abs=1.0) + assert e["pageY"] == pytest.approx(center["y"], abs=1.0) + assert e["target"] == "outer" + + +async def test_click_navigation( + bidi_session, + top_context, + url, + inline, + subscribe_events, + wait_for_event, + get_element, +): + await subscribe_events(events=["browsingContext.load"]) + + destination = url("/webdriver/tests/support/html/test_actions.html") + start = inline(f'destination') + + async def click_link(): + link = await get_element("#link") + + actions = Actions() + ( + actions.add_pointer() + .pointer_move(x=0, y=0, origin=link) + .pointer_down(button=0) + .pointer_up(button=0) + ) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + # repeat steps to check behaviour after document unload + for _ in range(2): + await bidi_session.browsing_context.navigate( + context=top_context["context"], url=start, wait="complete" + ) + + on_entry = wait_for_event("browsingContext.load") + await click_link() + event = await on_entry + assert event["url"] == destination + + +@pytest.mark.parametrize("drag_duration", [0, 300, 800]) +@pytest.mark.parametrize( + "dx, dy", [(20, 0), (0, 15), (10, 15), (-20, 0), (10, -15), (-10, -15)] +) +async def test_drag_and_drop( + bidi_session, + top_context, + get_element, + load_static_test_page, + dx, + dy, + drag_duration, +): + await load_static_test_page(page="test_actions.html") + + drag_target = await get_element("#dragTarget") + initial_rect = await get_element_rect( + bidi_session, context=top_context, element=drag_target + ) + initial_center = await get_inview_center_bidi( + bidi_session, context=top_context, element=drag_target + ) + + # Conclude chain with extra move to allow time for last queued + # coordinate-update of drag_target and to test that drag_target is "dropped". + actions = Actions() + ( + actions.add_pointer() + .pointer_move(x=0, y=0, origin=drag_target) + .pointer_down(button=0) + .pointer_move(dx, dy, duration=drag_duration, origin="pointer") + .pointer_up(button=0) + .pointer_move(80, 50, duration=100, origin="pointer") + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + # mouseup that ends the drag is at the expected destination + events = await get_events(bidi_session, top_context["context"]) + e = events[1] + assert e["type"] == "mouseup" + assert e["pageX"] == pytest.approx(initial_center["x"] + dx, abs=1.0) + assert e["pageY"] == pytest.approx(initial_center["y"] + dy, abs=1.0) + # check resulting location of the dragged element + final_rect = await get_element_rect( + bidi_session, context=top_context, element=drag_target + ) + assert initial_rect["x"] + dx == final_rect["x"] + assert initial_rect["y"] + dy == final_rect["y"] + + +@pytest.mark.parametrize("drag_duration", [0, 300, 800]) +async def test_drag_and_drop_with_draggable_element( + bidi_session, top_context, get_element, load_static_test_page, drag_duration +): + new_context = await bidi_session.browsing_context.create(type_hint="window") + await load_static_test_page(page="test_actions.html", context=new_context) + drag_target = await get_element("#draggable") + drop_target = await get_element("#droppable") + + # Conclude chain with extra move to allow time for last queued + # coordinate-update of drag_target and to test that drag_target is "dropped". + actions = Actions() + ( + actions.add_pointer() + .pointer_move(x=0, y=0, origin=drag_target) + .pointer_down(button=0) + .pointer_move(x=50, y=25, duration=drag_duration, origin=drop_target) + .pointer_up(button=0) + .pointer_move(80, 50, duration=100, origin="pointer") + ) + + await bidi_session.input.perform_actions( + actions=actions, context=new_context["context"] + ) + + # mouseup that ends the drag is at the expected destination + events = await get_events(bidi_session, new_context["context"]) + + assert len(events) >= 5 + assert events[1]["type"] == "dragstart", f"Events captured were {events}" + assert events[2]["type"] == "dragover", f"Events captured were {events}" + drag_events_captured = [ + ev["type"] + for ev in events + if ev["type"].startswith("drag") or ev["type"].startswith("drop") + ] + assert "dragend" in drag_events_captured + assert "dragenter" in drag_events_captured + assert "dragleave" in drag_events_captured + assert "drop" in drag_events_captured diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse_modifier.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse_modifier.py new file mode 100644 index 00000000000..9f76e250a1a --- /dev/null +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse_modifier.py @@ -0,0 +1,240 @@ +import pytest + +from webdriver.bidi.modules.input import Actions +from webdriver.bidi.modules.script import ContextTarget + +from tests.support.helpers import filter_dict +from tests.support.keys import Keys + +from .. import get_events + +pytestmark = pytest.mark.asyncio + + +@pytest.mark.parametrize( + "modifier, prop", + [ + (Keys.CONTROL, "ctrlKey"), + (Keys.R_CONTROL, "ctrlKey"), + ], +) +async def test_control_click( + bidi_session, + current_session, + top_context, + get_element, + load_static_test_page, + modifier, + prop, +): + os = current_session.capabilities["platformName"] + + await load_static_test_page(page="test_actions.html") + outer = await get_element("#outer") + + actions = Actions() + key_sources = ( + actions.add_key() + .pause(duration=0) + .key_down(modifier) + .pause(duration=200) + .key_up(modifier) + ) + mouse_sources = ( + actions.add_pointer() + .pointer_move(x=0, y=0, origin=outer) + .pointer_down(button=0) + .pointer_up(button=0) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + if os != "mac": + expected = [ + {"type": "mousemove"}, + {"type": "mousedown"}, + {"type": "mouseup"}, + {"type": "click"}, + ] + else: + expected = [ + {"type": "mousemove"}, + {"type": "mousedown"}, + {"type": "contextmenu"}, + {"type": "mouseup"}, + ] + + defaults = {"altKey": False, "metaKey": False, "shiftKey": False, "ctrlKey": False} + + for e in expected: + e.update(defaults) + if e["type"] != "mousemove": + e[prop] = True + + all_events = await get_events(bidi_session, top_context["context"]) + filtered_events = [filter_dict(e, expected[0]) for e in all_events] + assert expected == filtered_events + + +async def test_control_click_release( + bidi_session, top_context, load_static_test_page, get_focused_key_input +): + await load_static_test_page(page="test_actions.html") + key_reporter = await get_focused_key_input() + + # The context menu stays visible during subsequent tests so let's not + # display it in the first place. + await bidi_session.script.evaluate( + expression=""" + var keyReporter = document.getElementById("keys"); + document.addEventListener("contextmenu", function(e) { + e.preventDefault(); + }); + """, + await_promise=False, + target=ContextTarget(top_context["context"]), + ) + + actions = Actions() + key_sources = actions.add_key().pause(duration=0).key_down(Keys.CONTROL) + mouse_sources = ( + actions.add_pointer() + .pointer_move(x=0, y=0, origin=key_reporter) + .pointer_down(button=0) + ) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + await bidi_session.script.evaluate( + expression=""" + var keyReporter = document.getElementById("keys"); + keyReporter.addEventListener("mousedown", recordPointerEvent); + keyReporter.addEventListener("mouseup", recordPointerEvent); + resetEvents(); + """, + await_promise=False, + target=ContextTarget(top_context["context"]), + ) + await bidi_session.input.release_actions(context=top_context["context"]) + + expected = [ + {"type": "mouseup"}, + {"type": "keyup"}, + ] + all_events = await get_events(bidi_session, top_context["context"]) + events = [filter_dict(e, expected[0]) for e in all_events] + assert events == expected + + +async def test_many_modifiers_click( + bidi_session, top_context, get_element, load_static_test_page +): + await load_static_test_page(page="test_actions.html") + outer = await get_element("#outer") + + dblclick_timeout = 800 + actions = Actions() + key_sources = ( + actions.add_key() + .pause(duration=0) + .key_down(Keys.ALT) + .key_down(Keys.SHIFT) + .pause(duration=dblclick_timeout) + .key_up(Keys.ALT) + .key_up(Keys.SHIFT) + ) + mouse_sources = ( + actions.add_pointer() + .pointer_move(x=0, y=0, origin=outer) + .pause(duration=0) + .pointer_down(button=0) + .pointer_up(button=0) + .pause(duration=0) + .pause(duration=0) + .pointer_down(button=0) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + expected = [ + {"type": "mousemove"}, + # shift and alt pressed + {"type": "mousedown"}, + {"type": "mouseup"}, + {"type": "click"}, + # no modifiers pressed + {"type": "mousedown"}, + ] + + defaults = {"altKey": False, "metaKey": False, "shiftKey": False, "ctrlKey": False} + + for e in expected: + e.update(defaults) + + for e in expected[1:4]: + e["shiftKey"] = True + e["altKey"] = True + + all_events = await get_events(bidi_session, top_context["context"]) + events = [filter_dict(e, expected[0]) for e in all_events] + assert events == expected + + +@pytest.mark.parametrize( + "modifier, prop", + [ + (Keys.ALT, "altKey"), + (Keys.R_ALT, "altKey"), + (Keys.META, "metaKey"), + (Keys.R_META, "metaKey"), + (Keys.SHIFT, "shiftKey"), + (Keys.R_SHIFT, "shiftKey"), + ], +) +async def test_modifier_click( + bidi_session, top_context, get_element, load_static_test_page, modifier, prop +): + await load_static_test_page(page="test_actions.html") + outer = await get_element("#outer") + + actions = Actions() + key_sources = ( + actions.add_key() + .pause(duration=200) + .key_down(modifier) + .pause(duration=200) + .key_up(modifier) + ) + mouse_sources = ( + actions.add_pointer() + .pointer_move(x=0, y=0, origin=outer) + .pointer_down(button=0) + .pointer_up(button=0) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + expected = [ + {"type": "mousemove"}, + {"type": "mousedown"}, + {"type": "mouseup"}, + {"type": "click"}, + ] + + defaults = {"altKey": False, "metaKey": False, "shiftKey": False, "ctrlKey": False} + + for e in expected: + e.update(defaults) + if e["type"] != "mousemove": + e[prop] = True + + all_events = await get_events(bidi_session, top_context["context"]) + filtered_events = [filter_dict(e, expected[0]) for e in all_events] + assert expected == filtered_events diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse_multiclick.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse_multiclick.py new file mode 100644 index 00000000000..4f67f8fda94 --- /dev/null +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_mouse_multiclick.py @@ -0,0 +1,125 @@ +import pytest + +from webdriver.bidi.modules.input import Actions +from webdriver.bidi.modules.script import ContextTarget + +from tests.support.asserts import assert_move_to_coordinates +from tests.support.helpers import filter_dict + +from .. import get_events +from . import get_element_rect + +pytestmark = pytest.mark.asyncio + + +_DBLCLICK_INTERVAL = 640 + + +@pytest.mark.parametrize("pause_during_click", [True, False]) +@pytest.mark.parametrize("click_pause", [0, 200, _DBLCLICK_INTERVAL + 10]) +async def test_dblclick_at_coordinates( + bidi_session, top_context, load_static_test_page, pause_during_click, click_pause +): + await load_static_test_page(page="test_actions.html") + + div_point = { + "x": 82, + "y": 187, + } + actions = Actions() + input_source = ( + actions.add_pointer() + .pointer_move(x=div_point["x"], y=div_point["y"]) + .pointer_down(button=0) + .pointer_up(button=0) + ) + + # Either pause before the second click, which might prevent the double click + # depending on the pause delay. Or between mousedown and mouseup for the + # second click, which will never prevent a double click. + if pause_during_click: + input_source.pointer_down(button=0).pause(duration=click_pause) + else: + input_source.pause(duration=click_pause).pointer_down(button=0) + + input_source.pointer_up(button=0) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + # mouseup that ends the drag is at the expected destination + events = await get_events(bidi_session, top_context["context"]) + + assert_move_to_coordinates(div_point, "outer", events) + + expected = [ + {"type": "mousedown", "button": 0}, + {"type": "mouseup", "button": 0}, + {"type": "click", "button": 0}, + {"type": "mousedown", "button": 0}, + {"type": "mouseup", "button": 0}, + {"type": "click", "button": 0}, + ] + + if pause_during_click or click_pause < _DBLCLICK_INTERVAL: + expected.append({"type": "dblclick", "button": 0}) + + filtered_events = [filter_dict(e, expected[0]) for e in events] + assert expected == filtered_events[1:] + + +lots_of_text = ( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " + "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud " + "exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." +) + + +async def test_tripleclick_at_coordinates( + bidi_session, top_context, inline, get_element +): + """ + This test does a triple click on a coordinate. On desktop platforms + this will select a paragraph. On mobile this will not have the same + desired outcome as taps are handled differently on mobile. + """ + url = inline( + f"""
+ {lots_of_text} +
""" + ) + + await bidi_session.browsing_context.navigate( + context=top_context["context"], url=url, wait="complete" + ) + + div = await get_element("div") + div_rect = await get_element_rect(bidi_session, context=top_context, element=div) + div_centre = { + "x": div_rect["x"] + div_rect["width"] / 2, + "y": div_rect["y"] + div_rect["height"] / 2, + } + + actions = Actions() + ( + actions.add_pointer() + .pointer_move(x=int(div_centre["x"]), y=int(div_centre["y"])) + .pointer_down(button=0) + .pointer_up(button=0) + .pointer_down(button=0) + .pointer_up(button=0) + .pointer_down(button=0) + .pointer_up(button=0) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + actual_text = await bidi_session.script.evaluate( + expression="document.getSelection().toString()", + await_promise=False, + target=ContextTarget(top_context["context"]), + ) + assert actual_text["value"] == lots_of_text diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_origin.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_origin.py new file mode 100644 index 00000000000..c953d3d1b02 --- /dev/null +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_origin.py @@ -0,0 +1,140 @@ +import pytest + +from webdriver.bidi.modules.input import Actions +from webdriver.bidi.modules.script import ContextTarget + +from tests.support.asserts import assert_move_to_coordinates +from tests.support.helpers import filter_dict + +from .. import get_events +from . import ( + get_element_rect, + get_inview_center_bidi, + get_viewport_rect, + remote_mapping_to_dict, +) + +pytestmark = pytest.mark.asyncio + + +async def get_click_coordinates(bidi_session, context): + """Helper to get recorded click coordinates on a page generated with the + actions_origins_doc fixture.""" + result = await bidi_session.script.evaluate( + expression="window.coords", + target=ContextTarget(context["context"]), + await_promise=False, + ) + return remote_mapping_to_dict(result["value"]) + + +async def test_viewport_inside(bidi_session, top_context, get_actions_origin_page): + point = {"x": 50, "y": 50} + + url = get_actions_origin_page("width: 100px; height: 50px; background: green;") + await bidi_session.browsing_context.navigate( + context=top_context["context"], + url=url, + wait="complete", + ) + + actions = Actions() + actions.add_pointer().pointer_move(x=point["x"], y=point["y"]) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + click_coords = await get_click_coordinates(bidi_session, context=top_context) + assert click_coords["x"] == pytest.approx(point["x"], abs=1.0) + assert click_coords["y"] == pytest.approx(point["y"], abs=1.0) + + +async def test_pointer_inside(bidi_session, top_context, get_actions_origin_page): + start_point = {"x": 50, "y": 50} + offset = {"x": 10, "y": 5} + + url = get_actions_origin_page("width: 100px; height: 50px; background: green;") + await bidi_session.browsing_context.navigate( + context=top_context["context"], + url=url, + wait="complete", + ) + + actions = Actions() + ( + actions.add_pointer() + .pointer_move(x=start_point["x"], y=start_point["y"]) + .pointer_move(x=offset["x"], y=offset["y"], origin="pointer") + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + click_coords = await get_click_coordinates(bidi_session, context=top_context) + assert click_coords["x"] == pytest.approx(start_point["x"] + offset["x"], abs=1.0) + assert click_coords["y"] == pytest.approx(start_point["y"] + offset["y"], abs=1.0) + + +@pytest.mark.parametrize( + "doc", + [ + "width: 100px; height: 50px; background: green;", + """width: 100px; height: 50px; background: green; + position: relative; left: -50px; top: -25px;""", + ], + ids=["element fully visible", "element partly visible"], +) +@pytest.mark.parametrize("offset_x, offset_y", [(10, 15), (0, 0)]) +async def test_element_center_point_with_offset( + bidi_session, + top_context, + get_actions_origin_page, + get_element, + doc, + offset_x, + offset_y, +): + url = get_actions_origin_page(doc) + await bidi_session.browsing_context.navigate( + context=top_context["context"], + url=url, + wait="complete", + ) + + elem = await get_element("#inner") + center = await get_inview_center_bidi(bidi_session, context=top_context, element=elem) + + actions = Actions() + actions.add_pointer().pointer_move(x=offset_x, y=offset_y, origin=elem) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + click_coords = await get_click_coordinates(bidi_session, context=top_context) + assert click_coords["x"] == pytest.approx(center["x"] + offset_x, abs=1.0) + assert click_coords["y"] == pytest.approx(center["y"] + offset_y, abs=1.0) + + +async def test_element_larger_than_viewport( + bidi_session, top_context, get_actions_origin_page, get_element +): + url = get_actions_origin_page("width: 300vw; height: 300vh; background: green;") + await bidi_session.browsing_context.navigate( + context=top_context["context"], + url=url, + wait="complete", + ) + + elem = await get_element("#inner") + center = await get_inview_center_bidi(bidi_session, context=top_context, element=elem) + + actions = Actions() + actions.add_pointer().pointer_move(x=0, y=0, origin=elem) + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + click_coords = await get_click_coordinates(bidi_session, context=top_context) + assert click_coords["x"] == pytest.approx(center["x"], abs=1.0) + assert click_coords["y"] == pytest.approx(center["y"], abs=1.0) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_pen.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_pen.py new file mode 100644 index 00000000000..5483a1436c1 --- /dev/null +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_pen.py @@ -0,0 +1,73 @@ +import pytest + +from webdriver.bidi.modules.input import Actions + +from .. import get_events +from . import get_inview_center_bidi + +pytestmark = pytest.mark.asyncio + + +async def test_pen_pointer_properties( + bidi_session, top_context, get_element, load_static_test_page +): + await load_static_test_page(page="test_actions_pointer.html") + + pointerArea = await get_element("#pointerArea") + center = await get_inview_center_bidi( + bidi_session, context=top_context, element=pointerArea + ) + + actions = Actions() + ( + actions.add_pointer(pointer_type="pen") + .pointer_move(x=0, y=0, origin=pointerArea) + .pointer_down(button=0, pressure=0.36, tilt_x=-72, tilt_y=9, twist=86) + .pointer_move(x=10, y=10, origin=pointerArea) + .pointer_up(button=0) + .pointer_move(x=80, y=50, origin=pointerArea) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + events = await get_events(bidi_session, top_context["context"]) + assert len(events) == 10 + event_types = [e["type"] for e in events] + assert [ + "pointerover", + "pointerenter", + "pointermove", + "pointerdown", + "pointerover", + "pointerenter", + "pointermove", + "pointerup", + "pointerout", + "pointerleave", + ] == event_types + assert events[3]["type"] == "pointerdown" + assert events[3]["pageX"] == pytest.approx(center["x"], abs=1.0) + assert events[3]["pageY"] == pytest.approx(center["y"], abs=1.0) + assert events[3]["target"] == "pointerArea" + assert events[3]["pointerType"] == "pen" + # The default value of width and height for mouse and pen inputs is 1 + assert round(events[3]["width"], 2) == 1 + assert round(events[3]["height"], 2) == 1 + assert round(events[3]["pressure"], 2) == 0.36 + assert events[3]["tiltX"] == -72 + assert events[3]["tiltY"] == 9 + assert events[3]["twist"] == 86 + assert events[6]["type"] == "pointermove" + assert events[6]["pageX"] == pytest.approx(center["x"] + 10, abs=1.0) + assert events[6]["pageY"] == pytest.approx(center["y"] + 10, abs=1.0) + assert events[6]["target"] == "pointerArea" + assert events[6]["pointerType"] == "pen" + assert round(events[6]["width"], 2) == 1 + assert round(events[6]["height"], 2) == 1 + # The default value of pressure for all inputs is 0.5, other properties are 0 + assert round(events[6]["pressure"], 2) == 0.5 + assert events[6]["tiltX"] == 0 + assert events[6]["tiltY"] == 0 + assert events[6]["twist"] == 0 diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_touch.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_touch.py new file mode 100644 index 00000000000..9c31b0127fe --- /dev/null +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/pointer_touch.py @@ -0,0 +1,150 @@ +import pytest + +from webdriver.bidi.modules.input import Actions + +from .. import get_events +from . import get_inview_center_bidi + +pytestmark = pytest.mark.asyncio + + +async def test_touch_pointer_properties( + bidi_session, top_context, get_element, load_static_test_page +): + await load_static_test_page(page="test_actions_pointer.html") + + pointerArea = await get_element("#pointerArea") + center = await get_inview_center( + bidi_session, context=top_context, element=pointerArea + ) + + actions = Actions() + ( + actions.add_pointer(pointer_type="touch") + .pointer_move(x=0, y=0, origin=pointerArea) + .pointer_down( + button=0, + width=23, + height=31, + pressure=0.78, + tilt_x=21, + tilt_y=-8, + twist=355, + ) + .pointer_move( + x=10, + y=10, + origin=pointerArea, + width=39, + height=35, + pressure=0.91, + tilt_x=-19, + tilt_y=62, + twist=345, + ) + .pointer_up(button=0) + .pointer_move(x=80, y=50, origin=pointerArea) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + events = await get_events(bidi_session, top_context["context"]) + + assert len(events) == 7 + event_types = [e["type"] for e in events] + assert [ + "pointerover", + "pointerenter", + "pointerdown", + "pointermove", + "pointerup", + "pointerout", + "pointerleave", + ] == event_types + assert events[2]["type"] == "pointerdown" + assert events[2]["pageX"] == pytest.approx(center["x"], abs=1.0) + assert events[2]["pageY"] == pytest.approx(center["y"], abs=1.0) + assert events[2]["target"] == "pointerArea" + assert events[2]["pointerType"] == "touch" + assert round(events[2]["width"], 2) == 23 + assert round(events[2]["height"], 2) == 31 + assert round(events[2]["pressure"], 2) == 0.78 + assert events[3]["type"] == "pointermove" + assert events[3]["pageX"] == pytest.approx(center["x"] + 10, abs=1.0) + assert events[3]["pageY"] == pytest.approx(center["y"] + 10, abs=1.0) + assert events[3]["target"] == "pointerArea" + assert events[3]["pointerType"] == "touch" + assert round(events[3]["width"], 2) == 39 + assert round(events[3]["height"], 2) == 35 + assert round(events[3]["pressure"], 2) == 0.91 + + +async def test_touch_pointer_properties_tilt_twist( + bidi_session, top_context, get_element, load_static_test_page +): + # This test only covers the tilt/twist properties which are + # more specific to pen-type pointers, but which the spec allows + # for generic touch pointers. Seperating this out gives better + # coverage of the basic properties in test_touch_pointer_properties + await load_static_test_page(page="test_actions_pointer.html") + + pointerArea = await get_element("#pointerArea") + center = await get_inview_center( + bidi_session, context=top_context, element=pointerArea + ) + + actions = Actions() + ( + actions.add_pointer(pointer_type="touch") + .pointer_move(x=0, y=0, origin=pointerArea) + .pointer_down( + button=0, + width=23, + height=31, + pressure=0.78, + tilt_x=21, + tilt_y=-8, + twist=355, + ) + .pointer_move( + x=10, + y=10, + origin=pointerArea, + width=39, + height=35, + pressure=0.91, + tilt_x=-19, + tilt_y=62, + twist=345, + ) + .pointer_up(button=0) + .pointer_move(x=80, y=50, origin=pointerArea) + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + + events = await get_events(bidi_session, top_context["context"]) + + assert len(events) == 7 + event_types = [e["type"] for e in events] + assert [ + "pointerover", + "pointerenter", + "pointerdown", + "pointermove", + "pointerup", + "pointerout", + "pointerleave", + ] == event_types + assert events[2]["type"] == "pointerdown" + assert events[2]["tiltX"] == 21 + assert events[2]["tiltY"] == -8 + assert events[2]["twist"] == 355 + assert events[3]["type"] == "pointermove" + assert events[3]["tiltX"] == -19 + assert events[3]["tiltY"] == 62 + assert events[3]["twist"] == 345 diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/wheel.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/wheel.py new file mode 100644 index 00000000000..00e10e91226 --- /dev/null +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/perform_actions/wheel.py @@ -0,0 +1,75 @@ +import pytest + +from webdriver.bidi.modules.input import Actions +from .. import get_events + +pytestmark = pytest.mark.asyncio + + +@pytest.mark.parametrize("delta_x, delta_y", [(0, 10), (5, 0), (5, 10)]) +async def test_wheel_scroll( + bidi_session, setup_wheel_test, top_context, get_element, delta_x, delta_y +): + actions = Actions() + + outer = await get_element("#outer") + actions.add_wheel().scroll(x=0, y=0, delta_x=delta_x, delta_y=delta_y, origin=outer) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + events = await get_events(bidi_session, top_context["context"]) + + assert len(events) == 1 + assert events[0]["type"] == "wheel" + assert events[0]["deltaX"] >= delta_x + assert events[0]["deltaY"] >= delta_y + assert events[0]["deltaZ"] == 0 + assert events[0]["target"] == "outer" + + +@pytest.mark.parametrize("delta_x, delta_y", [(0, 10), (5, 0), (5, 10)]) +async def test_wheel_scroll_iframe( + bidi_session, setup_wheel_test, top_context, get_element, delta_x, delta_y +): + actions = Actions() + + subframe = await get_element("#subframe") + actions.add_wheel().scroll( + x=0, y=0, delta_x=delta_x, delta_y=delta_y, origin=subframe + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + events = await get_events(bidi_session, top_context["context"]) + assert len(events) == 1 + assert events[0]["type"] == "wheel" + assert events[0]["deltaX"] >= delta_x + assert events[0]["deltaY"] >= delta_y + assert events[0]["deltaZ"] == 0 + assert events[0]["target"] == "iframeContent" + + +@pytest.mark.parametrize("delta_x, delta_y", [(0, 10), (5, 0), (5, 10)]) +async def test_wheel_scroll_overflow( + bidi_session, setup_wheel_test, top_context, get_element, delta_x, delta_y +): + actions = Actions() + + scrollable = await get_element("#scrollable") + + actions.add_wheel().scroll( + x=0, y=0, delta_x=delta_x, delta_y=delta_y, origin=scrollable + ) + + await bidi_session.input.perform_actions( + actions=actions, context=top_context["context"] + ) + events = await get_events(bidi_session, top_context["context"]) + assert len(events) == 1 + assert events[0]["type"] == "wheel" + assert events[0]["deltaX"] >= delta_x + assert events[0]["deltaY"] >= delta_y + assert events[0]["deltaZ"] == 0 + assert events[0]["target"] == "scrollContent" diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/context.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/context.py index 0cb407606d4..ba2ddd1471f 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/context.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/context.py @@ -9,9 +9,9 @@ pytestmark = pytest.mark.asyncio async def test_different_top_level_contexts( - bidi_session, new_tab, top_context, test_actions_page_bidi, get_focused_key_input + bidi_session, new_tab, top_context, load_static_test_page, get_focused_key_input ): - await test_actions_page_bidi() + await load_static_test_page(page="test_actions.html") await get_focused_key_input() actions = Actions() @@ -28,7 +28,7 @@ async def test_different_top_level_contexts( # Release actions in another context await bidi_session.input.release_actions(context=new_tab["context"]) - events = await get_events(top_context["context"], bidi_session) + events = await get_events(bidi_session, top_context["context"]) assert len(events) == 0 # Release actions in right context @@ -37,6 +37,6 @@ async def test_different_top_level_contexts( expected = [ {"code": "KeyA", "key": "a", "type": "keyup"}, ] - all_events = await get_events(top_context["context"], bidi_session) + all_events = await get_events(bidi_session, top_context["context"]) (events, expected) = filter_supported_key_events(all_events, expected) assert events == expected diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/release.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/release.py index c4990b702ae..2955314e3c6 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/release.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/release.py @@ -7,9 +7,9 @@ pytestmark = pytest.mark.asyncio async def test_release_no_actions_sends_no_events( - bidi_session, top_context, test_actions_page_bidi, get_focused_key_input + bidi_session, top_context, load_static_test_page, get_focused_key_input ): - await test_actions_page_bidi() + await load_static_test_page(page="test_actions.html") elem = await get_focused_key_input() await bidi_session.input.release_actions(context=top_context["context"]) @@ -22,7 +22,7 @@ async def test_release_no_actions_sends_no_events( target=ContextTarget(top_context["context"]), await_promise=False, ) - events = await get_events(top_context["context"], bidi_session) + events = await get_events(bidi_session, top_context["context"]) assert len(keys["value"]) == 0 assert len(events) == 0 diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/sequence.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/sequence.py index bd1d7752303..9b4535c1b5f 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/sequence.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/input/release_actions/sequence.py @@ -9,9 +9,9 @@ pytestmark = pytest.mark.asyncio async def test_release_char_sequence_sends_keyup_events_in_reverse( - bidi_session, top_context, test_actions_page_bidi, get_focused_key_input + bidi_session, top_context, load_static_test_page, get_focused_key_input ): - await test_actions_page_bidi() + await load_static_test_page(page="test_actions.html") await get_focused_key_input() actions = Actions() @@ -30,7 +30,7 @@ async def test_release_char_sequence_sends_keyup_events_in_reverse( {"code": "KeyB", "key": "b", "type": "keyup"}, {"code": "KeyA", "key": "a", "type": "keyup"}, ] - all_events = await get_events(top_context["context"], bidi_session) + all_events = await get_events(bidi_session, top_context["context"]) (events, expected) = filter_supported_key_events(all_events, expected) assert events == expected @@ -43,15 +43,13 @@ async def test_release_char_sequence_sends_keyup_events_in_reverse( async def test_release_mouse_sequence_resets_dblclick_state( bidi_session, top_context, - test_actions_page_bidi, + get_element, + load_static_test_page, release_actions ): - await test_actions_page_bidi() - reporter = await bidi_session.script.evaluate( - expression="document.querySelector('#outer')", - target=ContextTarget(top_context["context"]), - await_promise=False, - ) + await load_static_test_page(page="test_actions.html") + reporter = await get_element("#outer") + actions = Actions() actions.add_pointer(pointer_type="mouse").pointer_move( x=0, y=0, origin=reporter["value"] @@ -66,7 +64,7 @@ async def test_release_mouse_sequence_resets_dblclick_state( await bidi_session.input.perform_actions( actions=actions, context=top_context["context"] ) - events = await get_events(top_context["context"], bidi_session) + events = await get_events(bidi_session, top_context["context"]) expected = [ {"type": "mousedown", "button": 0}, diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/network/conftest.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/network/conftest.py index 5bf7ca012bd..5a6c6551ff9 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/network/conftest.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/network/conftest.py @@ -15,7 +15,7 @@ def fetch(bidi_session, top_context, configuration): """Perform a fetch from the page of the provided context, default to the top context. """ - async def fetch(url, method="GET", headers=None, context=top_context, timeout_in_seconds=1): + async def fetch(url, method="GET", headers=None, context=top_context, timeout_in_seconds=3): method_arg = f"method: '{method}'," headers_arg = "" diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/arguments.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/arguments.py index 9d2df76a756..0cb571038b7 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/arguments.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/arguments.py @@ -1,7 +1,7 @@ import pytest from tests.support.sync import AsyncPoll import webdriver.bidi.error as error -from webdriver.bidi.modules.script import ContextTarget +from webdriver.bidi.modules.script import ContextTarget, SerializationOptions from ... import any_string, recursive_compare @@ -461,6 +461,7 @@ async def test_remote_reference_dom_collection( result = await call_function( function_declaration=function_declaration, arguments=[remote_value], + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/exception_details.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/exception_details.py index ef1118d0de1..97f38d5aaae 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/exception_details.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/exception_details.py @@ -144,7 +144,6 @@ async def test_invalid_function(bidi_session, top_context): 'value': { 'attributes': {}, 'childNodeCount': 0, - 'children': [], 'localName': 'div', 'namespaceURI': 'http://www.w3.org/1999/xhtml', 'nodeType': 1, @@ -180,3 +179,33 @@ async def test_exception_details(bidi_session, top_context, await_promise, expre }, exception.value.result, ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("chained", [True, False]) +async def test_rejected_promise(bidi_session, top_context, chained): + if chained: + function_declaration = "() => Promise.reject('error').then(() => { })" + else: + function_declaration = "() => Promise.reject('error')" + + with pytest.raises(ScriptEvaluateResultException) as exception: + await bidi_session.script.call_function( + function_declaration=function_declaration, + await_promise=True, + target=ContextTarget(top_context["context"]), + ) + + recursive_compare( + { + "realm": any_string, + "exceptionDetails": { + "columnNumber": any_int, + "exception": {"type": "string", "value": "error"}, + "lineNumber": any_int, + "stackTrace": any_stack_trace, + "text": any_string, + }, + }, + exception.value.result, + ) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/invalid.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/invalid.py index 234699abb91..800c4e26a63 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/invalid.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/invalid.py @@ -1,7 +1,7 @@ import pytest import webdriver.bidi.error as error -from webdriver.bidi.modules.script import ContextTarget, RealmTarget +from webdriver.bidi.modules.script import ContextTarget, RealmTarget, SerializationOptions pytestmark = pytest.mark.asyncio @@ -354,3 +354,70 @@ async def test_params_result_ownership_invalid_value(bidi_session, top_context, await_promise=False, target=ContextTarget(top_context["context"]), result_ownership=result_ownership) + + +@pytest.mark.parametrize("serialization_options", [False, "_UNKNOWN_", 42, []]) +async def test_params_serialization_options_invalid_type(bidi_session, top_context, serialization_options): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.call_function( + function_declaration="(arg) => arg", + serialization_options=serialization_options, + target=ContextTarget(top_context["context"]), + await_promise=True) + + +@pytest.mark.parametrize("max_dom_depth", [False, "_UNKNOWN_", {}, []]) +async def test_params_max_dom_depth_invalid_type(bidi_session, top_context, max_dom_depth): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.call_function( + function_declaration="(arg) => arg", + serialization_options=SerializationOptions(max_dom_depth=max_dom_depth), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +async def test_params_max_dom_depth_invalid_value(bidi_session, top_context): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.call_function( + function_declaration="(arg) => arg", + serialization_options=SerializationOptions(max_dom_depth=-1), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +@pytest.mark.parametrize("max_object_depth", [False, "_UNKNOWN_", {}, []]) +async def test_params_max_object_depth_invalid_type(bidi_session, top_context, max_object_depth): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.call_function( + function_declaration="(arg) => arg", + serialization_options=SerializationOptions(max_object_depth=max_object_depth), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +async def test_params_max_object_depth_invalid_value(bidi_session, top_context): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.call_function( + function_declaration="(arg) => arg", + serialization_options=SerializationOptions(max_object_depth=-1), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +@pytest.mark.parametrize("include_shadow_tree", [False, 42, {}, []]) +async def test_params_max_object_depth_invalid_type(bidi_session, top_context, include_shadow_tree): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.call_function( + function_declaration="(arg) => arg", + serialization_options=SerializationOptions(include_shadow_tree=include_shadow_tree), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +async def test_params_max_object_depth_invalid_value(bidi_session, top_context): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.call_function( + function_declaration="(arg) => arg", + serialization_options=SerializationOptions(include_shadow_tree="foo"), + target=ContextTarget(top_context["context"]), + await_promise=True) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/result.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/result.py index 3303f03ecc9..4eb139532cc 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/result.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/result.py @@ -1,6 +1,6 @@ import pytest -from webdriver.bidi.modules.script import ContextTarget +from webdriver.bidi.modules.script import ContextTarget, SerializationOptions pytestmark = pytest.mark.asyncio @@ -135,6 +135,7 @@ async def test_remote_values(bidi_session, top_context, await_promise, expressio function_declaration=function_declaration, await_promise=await_promise, target=ContextTarget(top_context["context"]), + serialization_options=SerializationOptions(max_object_depth=1), ) assert result == expected diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/result_node.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/result_node.py index 8424de8b8d8..378f6bed927 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/result_node.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/call_function/result_node.py @@ -1,5 +1,5 @@ import pytest -from webdriver.bidi.modules.script import ContextTarget +from webdriver.bidi.modules.script import ContextTarget, SerializationOptions from ... import any_string, recursive_compare @@ -142,6 +142,7 @@ async def test_element_node( function_declaration=function_declaration, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) @@ -160,7 +161,6 @@ async def test_element_node( "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "localName": "id", "namespaceURI": None, "nodeType": 2, @@ -176,7 +176,6 @@ async def test_element_node( "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "localName": "foo", "namespaceURI": "http://www.w3.org/2000/svg", "nodeType": 2, @@ -218,7 +217,6 @@ async def test_attribute_node( "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 3, "nodeValue": "Lorem", } @@ -257,7 +255,6 @@ async def test_text_node( "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 4, "nodeValue": " < > & ", } @@ -296,7 +293,6 @@ async def test_cdata_node(bidi_session, inline, new_tab, function_declaration, e "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 7, "nodeValue": "href='foo.css'", } @@ -337,7 +333,6 @@ async def test_processing_instruction_node( "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 8, "nodeValue": " Comment ", } @@ -413,6 +408,7 @@ async def test_document_node( function_declaration=function_declaration, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) @@ -431,7 +427,6 @@ async def test_document_node( "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 10, } } @@ -514,6 +509,7 @@ async def test_document_fragment_node( function_declaration=function_declaration, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) @@ -613,6 +609,7 @@ async def test_node_within_dom_collection( function_declaration=function_declaration, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) @@ -643,7 +640,6 @@ async def test_custom_element_with_shadow_root( "id": "custom-element", }, "childNodeCount": 0, - "children": [], "localName": "custom-element", "namespaceURI": "http://www.w3.org/1999/xhtml", "nodeType": 1, diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/conftest.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/conftest.py index 6423f9778e0..61b1e09382e 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/conftest.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/conftest.py @@ -1,8 +1,8 @@ import pytest import pytest_asyncio -from typing import Any, List, Mapping +from typing import Any, List, Mapping, Optional -from webdriver.bidi.modules.script import ContextTarget, OwnershipModel +from webdriver.bidi.modules.script import ContextTarget, OwnershipModel, SerializationOptions @pytest.fixture @@ -14,6 +14,7 @@ def call_function(bidi_session, top_context): context: str = top_context["context"], sandbox: str = None, result_ownership: OwnershipModel = OwnershipModel.NONE.value, + serialization_options: Optional[SerializationOptions] = None, ) -> Mapping[str, Any]: if sandbox is None: target = ContextTarget(top_context["context"]) @@ -26,6 +27,7 @@ def call_function(bidi_session, top_context): this=this, await_promise=False, result_ownership=result_ownership, + serialization_options=serialization_options, target=target, ) return result @@ -46,6 +48,7 @@ def evaluate(bidi_session, top_context): context: str = top_context["context"], sandbox: str = None, result_ownership: OwnershipModel = OwnershipModel.NONE.value, + serialization_options: Optional[SerializationOptions] = None, ) -> Mapping[str, Any]: if sandbox is None: target = ContextTarget(top_context["context"]) @@ -56,6 +59,7 @@ def evaluate(bidi_session, top_context): expression=expression, await_promise=False, result_ownership=result_ownership, + serialization_options=serialization_options, target=target, ) return result diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/await_promise.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/await_promise.py index 04530984b22..e99b6575065 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/await_promise.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/await_promise.py @@ -59,7 +59,7 @@ async def test_await_promise_resolved(bidi_session, top_context): @pytest.mark.asyncio async def test_await_resolve_array(bidi_session, top_context): result = await bidi_session.script.evaluate( - expression="Promise.resolve([1, 'text', true, ['will not be serialized']])", + expression="Promise.resolve([1, 'text', true, ['will be serialized']])", await_promise=True, target=ContextTarget(top_context["context"]), ) @@ -70,7 +70,7 @@ async def test_await_resolve_array(bidi_session, top_context): {"type": "number", "value": 1}, {"type": "string", "value": "text"}, {"type": "boolean", "value": True}, - {"type": "array"}, + {"type": "array", "value": [{"type": "string", "value": "will be serialized"}]}, ], } @@ -97,7 +97,7 @@ async def test_await_resolve_map(bidi_session, top_context): new Map([ ['key1', 'value1'], [2, new Date(0)], - ['key3', new Map([['key4', 'not_serialized']])] + ['key3', new Map([['key4', 'serialized']])] ]) )""", await_promise=True, @@ -112,7 +112,10 @@ async def test_await_resolve_map(bidi_session, top_context): {"type": "number", "value": 2}, {"type": "date", "value": "1970-01-01T00:00:00.000Z"}, ], - ["key3", {"type": "map"}], + ["key3", {"type": "map", "value": [[ + "key4", + {"type": "string", "value": "serialized"} + ]]}], ], } @@ -176,7 +179,7 @@ async def test_await_resolve_set(bidi_session, top_context): 2, true, new Date(0), - new Set([-1, 'not serialized']) + new Set([-1, 'serialized']) ]) )""", await_promise=True, @@ -190,7 +193,7 @@ async def test_await_resolve_set(bidi_session, top_context): {"type": "number", "value": 2}, {"type": "boolean", "value": True}, {"type": "date", "value": "1970-01-01T00:00:00.000Z"}, - {"type": "set"}, + {"type": "set", "value": [{"type": "number", "value": -1}, {"type": "string", "value": "serialized"}]}, ], } diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/exception_details.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/exception_details.py index ac4b8b6944b..fa5d5c4ae2c 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/exception_details.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/exception_details.py @@ -144,7 +144,6 @@ async def test_invalid_script(bidi_session, top_context): 'value': { 'attributes': {}, 'childNodeCount': 0, - 'children': [], 'localName': 'div', 'namespaceURI': 'http://www.w3.org/1999/xhtml', 'nodeType': 1, @@ -181,3 +180,33 @@ async def test_exception_details(bidi_session, top_context, await_promise, expre }, exception.value.result, ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("chained", [True, False]) +async def test_rejected_promise(bidi_session, top_context, chained): + if chained: + expression = "Promise.reject('error').then(() => { })" + else: + expression = "Promise.reject('error')" + + with pytest.raises(ScriptEvaluateResultException) as exception: + await bidi_session.script.evaluate( + expression=expression, + await_promise=True, + target=ContextTarget(top_context["context"]), + ) + + recursive_compare( + { + "realm": any_string, + "exceptionDetails": { + "columnNumber": any_int, + "exception": {"type": "string", "value": "error"}, + "lineNumber": any_int, + "stackTrace": any_stack_trace, + "text": any_string, + }, + }, + exception.value.result, + ) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/invalid.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/invalid.py index b02989edcee..9923d7414e8 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/invalid.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/invalid.py @@ -1,7 +1,7 @@ import pytest import webdriver.bidi.error as error -from webdriver.bidi.modules.script import ContextTarget, RealmTarget +from webdriver.bidi.modules.script import ContextTarget, RealmTarget, SerializationOptions pytestmark = pytest.mark.asyncio @@ -84,3 +84,70 @@ async def test_params_result_ownership_invalid_value(bidi_session, top_context, result_ownership=result_ownership, target=ContextTarget(top_context["context"]), await_promise=True) + + +@pytest.mark.parametrize("serialization_options", [False, "_UNKNOWN_", 42, []]) +async def test_params_serialization_options_invalid_type(bidi_session, top_context, serialization_options): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.evaluate( + expression="1 + 2", + serialization_options=serialization_options, + target=ContextTarget(top_context["context"]), + await_promise=True) + + +@pytest.mark.parametrize("max_dom_depth", [False, "_UNKNOWN_", {}, []]) +async def test_params_max_dom_depth_invalid_type(bidi_session, top_context, max_dom_depth): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.evaluate( + expression="1 + 2", + serialization_options=SerializationOptions(max_dom_depth=max_dom_depth), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +async def test_params_max_dom_depth_invalid_value(bidi_session, top_context): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.evaluate( + expression="1 + 2", + serialization_options=SerializationOptions(max_dom_depth=-1), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +@pytest.mark.parametrize("max_object_depth", [False, "_UNKNOWN_", {}, []]) +async def test_params_max_object_depth_invalid_type(bidi_session, top_context, max_object_depth): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.evaluate( + expression="1 + 2", + serialization_options=SerializationOptions(max_object_depth=max_object_depth), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +async def test_params_max_object_depth_invalid_value(bidi_session, top_context): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.evaluate( + expression="1 + 2", + serialization_options=SerializationOptions(max_object_depth=-1), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +@pytest.mark.parametrize("include_shadow_tree", [False, 42, {}, []]) +async def test_params_max_object_depth_invalid_type(bidi_session, top_context, include_shadow_tree): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.evaluate( + expression="1 + 2", + serialization_options=SerializationOptions(include_shadow_tree=include_shadow_tree), + target=ContextTarget(top_context["context"]), + await_promise=True) + + +async def test_params_max_object_depth_invalid_value(bidi_session, top_context): + with pytest.raises(error.InvalidArgumentException): + await bidi_session.script.evaluate( + expression="1 + 2", + serialization_options=SerializationOptions(include_shadow_tree="foo"), + target=ContextTarget(top_context["context"]), + await_promise=True) diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/result.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/result.py index 0e1c98e3bb0..a8278dbfbb0 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/result.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/result.py @@ -1,5 +1,5 @@ import pytest -from webdriver.bidi.modules.script import ContextTarget +from webdriver.bidi.modules.script import ContextTarget, SerializationOptions @pytest.mark.asyncio @@ -135,6 +135,7 @@ async def test_remote_values(bidi_session, top_context, expression, expected): expression=expression, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_object_depth=1), ) assert result == expected diff --git a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/result_node.py b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/result_node.py index dbf59f9edcf..ae07b940d05 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/result_node.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/bidi/script/evaluate/result_node.py @@ -1,5 +1,5 @@ import pytest -from webdriver.bidi.modules.script import ContextTarget +from webdriver.bidi.modules.script import ContextTarget, SerializationOptions from ... import any_string, recursive_compare @@ -140,6 +140,7 @@ async def test_element_node(bidi_session, get_test_page, top_context, expression expression=expression, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) @@ -158,7 +159,6 @@ async def test_element_node(bidi_session, get_test_page, top_context, expression "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "localName": "id", "namespaceURI": None, "nodeType": 2, @@ -174,7 +174,6 @@ async def test_element_node(bidi_session, get_test_page, top_context, expression "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "localName": "foo", "namespaceURI": "http://www.w3.org/2000/svg", "nodeType": 2, @@ -214,7 +213,6 @@ async def test_attribute_node(bidi_session, get_test_page, top_context, expressi "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 3, "nodeValue": "Lorem", } @@ -251,7 +249,6 @@ async def test_text_node(bidi_session, get_test_page, top_context, expression, e "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 4, "nodeValue": " < > & ", } @@ -290,7 +287,6 @@ async def test_cdata_node(bidi_session, inline, new_tab, expression, expected): "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 7, "nodeValue": "href='foo.css'", } @@ -331,7 +327,6 @@ async def test_processing_instruction_node( "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 8, "nodeValue": " Comment ", } @@ -403,6 +398,7 @@ async def test_document_node(bidi_session, get_test_page, top_context, expressio expression=expression, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) @@ -421,7 +417,6 @@ async def test_document_node(bidi_session, get_test_page, top_context, expressio "sharedId": any_string, "value": { "childNodeCount": 0, - "children": [], "nodeType": 10, } } @@ -502,6 +497,7 @@ async def test_document_fragment_node( expression=expression, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) @@ -601,6 +597,7 @@ async def test_node_within_dom_collection( expression=expression, target=ContextTarget(top_context["context"]), await_promise=False, + serialization_options=SerializationOptions(max_dom_depth=1), ) recursive_compare(expected, result) @@ -631,7 +628,6 @@ async def test_custom_element_with_shadow_root( "id": "custom-element", }, "childNodeCount": 0, - "children": [], "localName": "custom-element", "namespaceURI": "http://www.w3.org/1999/xhtml", "nodeType": 1, diff --git a/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/conftest.py b/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/conftest.py index f2060a87eed..0694cce494f 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/conftest.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/conftest.py @@ -81,9 +81,9 @@ def test_actions_page(session, url): @pytest.fixture def test_actions_scroll_page(session, url): - session.url = url("/webdriver/tests/perform_actions/support/test_actions_scroll_wdspec.html") + session.url = url("/webdriver/tests/support/html/test_actions_scroll.html") @pytest.fixture def test_actions_pointer_page(session, url): - session.url = url("/webdriver/tests/perform_actions/support/test_actions_pointer_wdspec.html") + session.url = url("/webdriver/tests/support/html/test_actions_pointer.html") diff --git a/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_origin.py b/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_origin.py index c4e5db7a001..8d4dc9045e6 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_origin.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_origin.py @@ -5,127 +5,116 @@ from webdriver import MoveTargetOutOfBoundsException from tests.perform_actions.support.mouse import get_inview_center, get_viewport_rect -@pytest.fixture -def origin_doc(inline): - def origin_doc(inner_style, outer_style=""): - return inline(""" -
-
-
- """.format(inner_style, outer_style)) - return origin_doc - - def get_click_coordinates(session): return session.execute_script("return window.coords;") -def test_viewport_inside(session, mouse_chain, origin_doc): +def test_viewport_inside(session, mouse_chain, get_actions_origin_page): point = {"x": 50, "y": 50} - session.url = origin_doc("width: 100px; height: 50px; background: green;") - mouse_chain \ - .pointer_move(point["x"], point["y"], origin="viewport") \ - .perform() + session.url = get_actions_origin_page( + "width: 100px; height: 50px; background: green;" + ) + mouse_chain.pointer_move(point["x"], point["y"], origin="viewport").perform() click_coords = session.execute_script("return window.coords;") - assert click_coords["x"] == pytest.approx(point["x"], abs = 1.0) - assert click_coords["y"] == pytest.approx(point["y"], abs = 1.0) + assert click_coords["x"] == pytest.approx(point["x"], abs=1.0) + assert click_coords["y"] == pytest.approx(point["y"], abs=1.0) def test_viewport_outside(session, mouse_chain): with pytest.raises(MoveTargetOutOfBoundsException): - mouse_chain \ - .pointer_move(-50, -50, origin="viewport") \ - .perform() + mouse_chain.pointer_move(-50, -50, origin="viewport").perform() -def test_pointer_inside(session, mouse_chain, origin_doc): +def test_pointer_inside(session, mouse_chain, get_actions_origin_page): start_point = {"x": 50, "y": 50} offset = {"x": 10, "y": 5} - session.url = origin_doc("width: 100px; height: 50px; background: green;") - mouse_chain \ - .pointer_move(start_point["x"], start_point["y"]) \ - .pointer_move(offset["x"], offset["y"], origin="pointer") \ - .perform() + session.url = get_actions_origin_page( + "width: 100px; height: 50px; background: green;" + ) + mouse_chain.pointer_move(start_point["x"], start_point["y"]).pointer_move( + offset["x"], offset["y"], origin="pointer" + ).perform() click_coords = session.execute_script("return window.coords;") - assert click_coords["x"] == pytest.approx(start_point["x"] + offset["x"], abs = 1.0) - assert click_coords["y"] == pytest.approx(start_point["y"] + offset["y"], abs = 1.0) + assert click_coords["x"] == pytest.approx(start_point["x"] + offset["x"], abs=1.0) + assert click_coords["y"] == pytest.approx(start_point["y"] + offset["y"], abs=1.0) def test_pointer_outside(session, mouse_chain): with pytest.raises(MoveTargetOutOfBoundsException): - mouse_chain \ - .pointer_move(-50, -50, origin="pointer") \ - .perform() + mouse_chain.pointer_move(-50, -50, origin="pointer").perform() -def test_element_center_point(session, mouse_chain, origin_doc): - session.url = origin_doc("width: 100px; height: 50px; background: green;") +def test_element_center_point(session, mouse_chain, get_actions_origin_page): + session.url = get_actions_origin_page( + "width: 100px; height: 50px; background: green;" + ) elem = session.find.css("#inner", all=False) center = get_inview_center(elem.rect, get_viewport_rect(session)) - mouse_chain \ - .pointer_move(0, 0, origin=elem) \ - .perform() + mouse_chain.pointer_move(0, 0, origin=elem).perform() click_coords = get_click_coordinates(session) - assert click_coords["x"] == pytest.approx(center["x"], abs = 1.0) - assert click_coords["y"] == pytest.approx(center["y"], abs = 1.0) + assert click_coords["x"] == pytest.approx(center["x"], abs=1.0) + assert click_coords["y"] == pytest.approx(center["y"], abs=1.0) -def test_element_center_point_with_offset(session, mouse_chain, origin_doc): - session.url = origin_doc("width: 100px; height: 50px; background: green;") +def test_element_center_point_with_offset( + session, mouse_chain, get_actions_origin_page +): + session.url = get_actions_origin_page( + "width: 100px; height: 50px; background: green;" + ) elem = session.find.css("#inner", all=False) center = get_inview_center(elem.rect, get_viewport_rect(session)) - mouse_chain \ - .pointer_move(10, 15, origin=elem) \ - .perform() + mouse_chain.pointer_move(10, 15, origin=elem).perform() click_coords = get_click_coordinates(session) - assert click_coords["x"] == pytest.approx(center["x"] + 10, abs = 1.0) - assert click_coords["y"] == pytest.approx(center["y"] + 15, abs = 1.0) + assert click_coords["x"] == pytest.approx(center["x"] + 10, abs=1.0) + assert click_coords["y"] == pytest.approx(center["y"] + 15, abs=1.0) -def test_element_in_view_center_point_partly_visible(session, mouse_chain, origin_doc): - session.url = origin_doc("""width: 100px; height: 50px; background: green; - position: relative; left: -50px; top: -25px;""") +def test_element_in_view_center_point_partly_visible( + session, mouse_chain, get_actions_origin_page +): + session.url = get_actions_origin_page( + """width: 100px; height: 50px; background: green; + position: relative; left: -50px; top: -25px;""" + ) elem = session.find.css("#inner", all=False) center = get_inview_center(elem.rect, get_viewport_rect(session)) - mouse_chain \ - .pointer_move(0, 0, origin=elem) \ - .perform() + mouse_chain.pointer_move(0, 0, origin=elem).perform() click_coords = get_click_coordinates(session) - assert click_coords["x"] == pytest.approx(center["x"], abs = 1.0) - assert click_coords["y"] == pytest.approx(center["y"], abs = 1.0) + assert click_coords["x"] == pytest.approx(center["x"], abs=1.0) + assert click_coords["y"] == pytest.approx(center["y"], abs=1.0) -def test_element_larger_than_viewport(session, mouse_chain, origin_doc): - session.url = origin_doc("width: 300vw; height: 300vh; background: green;") +def test_element_larger_than_viewport(session, mouse_chain, get_actions_origin_page): + session.url = get_actions_origin_page( + "width: 300vw; height: 300vh; background: green;" + ) elem = session.find.css("#inner", all=False) center = get_inview_center(elem.rect, get_viewport_rect(session)) - mouse_chain \ - .pointer_move(0, 0, origin=elem) \ - .perform() + mouse_chain.pointer_move(0, 0, origin=elem).perform() click_coords = get_click_coordinates(session) - assert click_coords["x"] == pytest.approx(center["x"], abs = 1.0) - assert click_coords["y"] == pytest.approx(center["y"], abs = 1.0) + assert click_coords["x"] == pytest.approx(center["x"], abs=1.0) + assert click_coords["y"] == pytest.approx(center["y"], abs=1.0) -def test_element_outside_of_view_port(session, mouse_chain, origin_doc): - session.url = origin_doc("""width: 100px; height: 50px; background: green; - position: relative; left: -200px; top: -100px;""") +def test_element_outside_of_view_port(session, mouse_chain, get_actions_origin_page): + session.url = get_actions_origin_page( + """width: 100px; height: 50px; background: green; + position: relative; left: -200px; top: -100px;""" + ) elem = session.find.css("#inner", all=False) with pytest.raises(MoveTargetOutOfBoundsException): - mouse_chain \ - .pointer_move(0, 0, origin=elem) \ - .perform() + mouse_chain.pointer_move(0, 0, origin=elem).perform() diff --git a/tests/wpt/web-platform-tests/webdriver/tests/support/fixtures.py b/tests/wpt/web-platform-tests/webdriver/tests/support/fixtures.py index 0755d70d525..eca9fda4bef 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/support/fixtures.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/support/fixtures.py @@ -211,8 +211,8 @@ def url(server_config): @pytest.fixture -def modifier_key(session): - if session.capabilities["platformName"] == "mac": +def modifier_key(current_session): + if current_session.capabilities["platformName"] == "mac": return Keys.META else: return Keys.CONTROL @@ -255,6 +255,24 @@ def iframe(inline): return iframe +@pytest.fixture +def get_actions_origin_page(inline): + """Create a test pagefor action origin tests, recording mouse coordinates + automatically on window.coords.""" + + def get_actions_origin_page(inner_style, outer_style=""): + return inline( + f""" +
+
+
+ """ + ) + + return get_actions_origin_page + + @pytest.fixture def get_test_page(iframe, inline): def get_test_page( diff --git a/tests/wpt/web-platform-tests/webdriver/tests/support/fixtures_bidi.py b/tests/wpt/web-platform-tests/webdriver/tests/support/fixtures_bidi.py index 612718b89e5..39ed3a5bbfd 100644 --- a/tests/wpt/web-platform-tests/webdriver/tests/support/fixtures_bidi.py +++ b/tests/wpt/web-platform-tests/webdriver/tests/support/fixtures_bidi.py @@ -284,6 +284,18 @@ def compare_png_bidi(bidi_session, url): return compare_png_bidi +@pytest.fixture +def get_element(bidi_session, top_context): + async def get_element(css_selector, context=top_context): + result = await bidi_session.script.evaluate( + expression=f"document.querySelector('{css_selector}')", + target=ContextTarget(context["context"]), + await_promise=False, + ) + return result + return get_element + + @pytest.fixture def get_reference_png( bidi_session, inline, render_pdf_to_png_bidi, top_context @@ -337,14 +349,14 @@ def render_pdf_to_png_bidi(bidi_session, new_tab, url): @pytest.fixture -def test_actions_page_bidi(bidi_session, url, top_context): - """Navigate to test_actions.html.""" +def load_static_test_page(bidi_session, url, top_context): + """Navigate to a test page from the support/html folder.""" - async def test_actions_page_bidi(context=top_context): + async def load_static_test_page(page, context=top_context): await bidi_session.browsing_context.navigate( context=context["context"], - url=url("/webdriver/tests/support/html/test_actions.html"), + url=url(f"/webdriver/tests/support/html/{page}"), wait="complete", ) - return test_actions_page_bidi + return load_static_test_page diff --git a/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/support/test_actions_pointer_wdspec.html b/tests/wpt/web-platform-tests/webdriver/tests/support/html/test_actions_pointer.html similarity index 100% rename from tests/wpt/web-platform-tests/webdriver/tests/perform_actions/support/test_actions_pointer_wdspec.html rename to tests/wpt/web-platform-tests/webdriver/tests/support/html/test_actions_pointer.html diff --git a/tests/wpt/web-platform-tests/webdriver/tests/perform_actions/support/test_actions_scroll_wdspec.html b/tests/wpt/web-platform-tests/webdriver/tests/support/html/test_actions_scroll.html similarity index 100% rename from tests/wpt/web-platform-tests/webdriver/tests/perform_actions/support/test_actions_scroll_wdspec.html rename to tests/wpt/web-platform-tests/webdriver/tests/support/html/test_actions_scroll.html diff --git a/tests/wpt/web-platform-tests/webmessaging/postMessage_cross_domain_image_transfer_webgl.sub.htm b/tests/wpt/web-platform-tests/webmessaging/postMessage_cross_domain_image_transfer_webgl.sub.htm deleted file mode 100644 index 0c5458953f8..00000000000 --- a/tests/wpt/web-platform-tests/webmessaging/postMessage_cross_domain_image_transfer_webgl.sub.htm +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - diff --git a/tests/wpt/web-platform-tests/webmidi/idlharness.https.window.js b/tests/wpt/web-platform-tests/webmidi/idlharness.https.window.js index 1474b3845af..fabc836fdba 100644 --- a/tests/wpt/web-platform-tests/webmidi/idlharness.https.window.js +++ b/tests/wpt/web-platform-tests/webmidi/idlharness.https.window.js @@ -11,19 +11,23 @@ idl_test( ['html', 'dom', 'permissions'], async idl_array => { idl_array.add_objects({ - MIDIAccess: ['access'], - MIDIInputMap: ['inputs'], - MIDIOutputMap: ['outputs'], + MIDIPort: [], + MIDIMessageEvent: [ + 'new MIDIMessageEvent("type", { data: new Uint8Array([0]) })' + ], MIDIConnectionEvent: ['new MIDIConnectionEvent("type")'], }) self.access = await navigator.requestMIDIAccess(); self.inputs = access.inputs; + self.outputs = access.outputs; + idl_array.add_objects({ MIDIInputMap: ['inputs'] }); + idl_array.add_objects({ MIDIOutputMap: ['outputs'] }); + idl_array.add_objects({ MIDIAccess: ['access'] }); if (inputs.size) { self.input = Array.from(access.inputs.values())[0]; idl_array.add_objects({ MIDIInput: ['input'] }); } - self.outputs = access.outputs; if (outputs.size) { self.output = Array.from(access.outputs.values())[0]; idl_array.add_objects({ MIDIOutput: ['output'] }); diff --git a/tests/wpt/web-platform-tests/webnn/reduction.https.any.js b/tests/wpt/web-platform-tests/webnn/reduction.https.any.js index bff8aa22baa..20bd74d8dee 100644 --- a/tests/wpt/web-platform-tests/webnn/reduction.https.any.js +++ b/tests/wpt/web-platform-tests/webnn/reduction.https.any.js @@ -8,6 +8,17 @@ // https://webmachinelearning.github.io/webnn/#api-mlgraphbuilder-reduce testWebNNOperation( - ['reduceMax', 'reduceMean', 'reduceMin', 'reduceProduct', 'reduceSum'], + [ + 'reduceL1', + 'reduceL2', + 'reduceLogSum', + 'reduceLogSumExp', + 'reduceMax', + 'reduceMean', + 'reduceMin', + 'reduceProduct', + 'reduceSum', + 'reduceSumSquare', + ], buildOperationWithSingleInput ); \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_l1.json b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_l1.json new file mode 100644 index 00000000000..aa169299c7c --- /dev/null +++ b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_l1.json @@ -0,0 +1,702 @@ +{ + "tests": [ + { + "name": "reduceL1 float32 1D tensor all positive default options", // default options: {axes: null, keepDimensions: false} + "inputs": { + "input": { + "shape": [24], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 1092.72021484375, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 1D tensor all negative default options", + "inputs": { + "input": { + "shape": [24], + "data": [ + -98.83928567774318, + -57.66743928106195, + -57.101201850012814, + -6.693042101576822, + -45.305847421047595, + -86.68338950685379, + -74.71875033016443, + -76.46740234611214, + -75.37676973458242, + -18.22093937407911, + -54.64426752595342, + -36.45240031615904, + -18.322682023656796, + -47.94379514838312, + -40.1997828250384, + -15.830483512310494, + -48.88335705253115, + -41.60024225085446, + -20.65563368305152, + -92.29933856234294, + -46.288581883419646, + -80.57185804741187, + -25.494730168492268, + -48.96730121051369 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 1215.228515625, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 1D tensor all positive integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + 18, + 29, + 35, + 36, + 4, + 76, + 41, + 18, + 53, + 29, + 25, + 94, + 26, + 1, + 3, + 68, + 39, + 25, + 87, + 30, + 39, + 75, + 76, + 66 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 993, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 1D tensor all negative integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + -92, + -52, + -88, + -78, + -20, + -73, + -42, + -57, + -39, + -75, + -17, + -36, + -81, + -24, + -88, + -91, + -76, + -5, + -44, + -66, + -96, + -8, + -69, + -27 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 1344, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 2D tensor default options", + "inputs": { + "input": { + "shape": [4, 6], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 1092.72021484375, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 3D tensor default options", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 1092.72021484375, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 4D tensor default options", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 1092.72021484375, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 5D tensor default options", + "inputs": { + "input": { + "shape": [2, 1, 4, 1, 3], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 1092.72021484375, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 3D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "options": { + "axes": [2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 142.01541137695312, + 106.62430572509766, + 175.39280700683594, + 286.7269592285156, + 169.36322021484375, + 212.59750366210938 + ], + "type": "float32" + } + }, + { + "name": "reduceL1 float32 4D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "options": { + "axes": [0, 2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 258.57110595703125, + 174.42807006835938, + 102.19830322265625, + 134.52191162109375, + 207.92910766601562, + 215.07168579101562 + ], + "type": "float32" + } + }, + { + "name": "reduceL1 float32 3D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 1092.72021484375, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 3D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1], + "data": [ + 1092.72021484375 + ], + "type": "float32" + } + }, + { + "name": "reduceL1 float32 4D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 1092.72021484375, + "type": "float32" + } + }, + { + "name": "reduceL1 float32 4D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1, 1], + "data": [ + 1092.72021484375 + ], + "type": "float32" + } + }, + { + "name": "reduceL1 float32 4D tensor options.axes with options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [2, 2], + "data": [ + 108.43173217773438, + 315.6007995605469, + 359.5506591796875, + 309.13702392578125 + ], + "type": "float32" + } + }, + { + "name": "reduceL1 float32 4D tensor options.axes with options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 5.508826448139126, + 50.61575563515446, + 1.6773050539454992, + 84.21352292914005, + 15.664374631289203, + 52.89714899357876, + 9.12515782683123, + 28.93762412170997, + 12.567061064158146, + 11.399989904078245, + 86.91246376729916, + 64.51329469980782, + 71.28342153263038, + 76.34410635436484, + 41.53409150301335, + 97.56533284219819, + 31.803831597266385, + 6.0897547388209405, + 61.70843555684953, + 69.76119433406723, + 38.91940474525253, + 52.28833355637117, + 22.31783714884341, + 99.0719229634137 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [1, 2, 2, 1], + "data": [ + 108.43173217773438, + 315.6007995605469, + 359.5506591796875, + 309.13702392578125 + ], + "type": "float32" + } + } + ] +} \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_l2.json b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_l2.json new file mode 100644 index 00000000000..73397cbb7a8 --- /dev/null +++ b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_l2.json @@ -0,0 +1,702 @@ +{ + "tests": [ + { + "name": "reduceL2 float32 1D tensor all positive default options", // default options: {axes: null, keepDimensions: false} + "inputs": { + "input": { + "shape": [24], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 272.0996398925781, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 1D tensor all negative default options", + "inputs": { + "input": { + "shape": [24], + "data": [ + -66.80042739154972, + -53.00005108985402, + -59.58587770117833, + -46.14393008028177, + -49.60613922872308, + -12.832738832929593, + -88.05061277508285, + -75.56246522621561, + -50.767774970060664, + -36.96630141451547, + -26.34404432713906, + -58.905464928590476, + -94.28752832403735, + -22.780279721601616, + -84.34877530084705, + -60.477345782692815, + -41.45580712299912, + -92.84781353832356, + -85.0544854150549, + -30.23526041853337, + -47.33807956591096, + -25.26842900087003, + -78.1195878278582, + -28.3309437256642 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 292.57574462890625, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 1D tensor all positive integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + 4, + 29, + 8, + 56, + 42, + 78, + 89, + 64, + 56, + 81, + 85, + 18, + 6, + 39, + 35, + 63, + 87, + 50, + 81, + 89, + 5, + 8, + 37, + 37 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 274.4029846191406, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 1D tensor all negative integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + -70, + -78, + -65, + -77, + -25, + -47, + -63, + -67, + -66, + -15, + -28, + -75, + -88, + -54, + -13, + -27, + -5, + -18, + -68, + -71, + -50, + -56, + -99, + -99 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 300.3830871582031, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 2D tensor default options", + "inputs": { + "input": { + "shape": [4, 6], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 272.0996398925781, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 3D tensor default options", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 272.0996398925781, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 4D tensor default options", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 272.0996398925781, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 5D tensor default options", + "inputs": { + "input": { + "shape": [2, 1, 4, 1, 3], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 272.0996398925781, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 3D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "options": { + "axes": [2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 122.352783203125, + 124.8213119506836, + 128.20062255859375, + 128.14801025390625, + 87.18083953857422, + 55.043975830078125 + ], + "type": "float32" + } + }, + { + "name": "reduceL2 float32 4D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "options": { + "axes": [0, 2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 114.44775390625, + 110.26422882080078, + 133.47344970703125, + 64.96752166748047, + 128.0914764404297, + 101.677734375 + ], + "type": "float32" + } + }, + { + "name": "reduceL2 float32 3D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 272.0996398925781, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 3D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1], + "data": [ + 272.0996398925781 + ], + "type": "float32" + } + }, + { + "name": "reduceL2 float32 4D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 272.0996398925781, + "type": "float32" + } + }, + { + "name": "reduceL2 float32 4D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1, 1], + "data": [ + 272.0996398925781 + ], + "type": "float32" + } + }, + { + "name": "reduceL2 float32 4D tensor options.axes with options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [2, 2], + "data": [ + 138.580078125, + 166.67791748046875, + 149.91552734375, + 67.6578598022461 + ], + "type": "float32" + } + }, + { + "name": "reduceL2 float32 4D tensor options.axes with options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 4.860227954324237, + 88.23184532015614, + 54.489688892595865, + 64.75027573238448, + 6.855991445231058, + 91.3987084155092, + 41.888577644260664, + 73.65445188651776, + 35.31573479319383, + 48.345430062443896, + 82.3919051922353, + 77.86200561022456, + 93.31141688733462, + 62.486883544675194, + 60.292898644959706, + 13.23059966965019, + 20.535988317971942, + 53.451616950541414, + 11.32008585820996, + 64.75763553379184, + 43.65894603418228, + 0.8374307376408652, + 0.6848266407317727, + 33.504704671527506 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [1, 2, 2, 1], + "data": [ + 138.580078125, + 166.67791748046875, + 149.91552734375, + 67.6578598022461 + ], + "type": "float32" + } + } + ] +} \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_log_sum.json b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_log_sum.json new file mode 100644 index 00000000000..2e1fee804fd --- /dev/null +++ b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_log_sum.json @@ -0,0 +1,622 @@ +{ + "tests": [ + { + "name": "reduceLogSum float32 1D tensor all non-negative default options", // default options: {axes: null, keepDimensions: false} + "inputs": { + "input": { + "shape": [24], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 7.039101600646973, + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 1D tensor all non-negative integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + 63, + 82, + 49, + 23, + 98, + 67, + 15, + 9, + 89, + 7, + 69, + 61, + 47, + 50, + 41, + 39, + 58, + 52, + 35, + 83, + 81, + 7, + 34, + 9 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 7.063048362731934, + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 2D tensor default options", + "inputs": { + "input": { + "shape": [4, 6], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 7.039101600646973, + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 3D tensor default options", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 7.039101600646973, + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 4D tensor default options", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 7.039101600646973, + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 5D tensor default options", + "inputs": { + "input": { + "shape": [2, 1, 4, 1, 3], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 7.039101600646973, + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 3D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "options": { + "axes": [2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 5.593751907348633, + 4.773046016693115, + 5.3115739822387695, + 5.2497639656066895, + 4.973392486572266, + 5.373587131500244 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 4D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "options": { + "axes": [0, 2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 5.410027980804443, + 5.367736339569092, + 5.399682998657227, + 4.652334213256836, + 4.744638442993164, + 5.565346717834473 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 3D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 7.039101600646973, + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 3D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1], + "data": [ + 7.039101600646973 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 4D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 7.039101600646973, + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 4D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1, 1], + "data": [ + 7.039101600646973 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 4D tensor options.axes with options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [2, 2], + "data": [ + 5.7273993492126465, + 5.64375114440918, + 5.453810214996338, + 5.758983135223389 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSum float32 4D tensor options.axes with options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 64.54826901463852, + 97.87423374006126, + 26.529027351852186, + 79.79046651888517, + 50.394988743199434, + 14.578406888832252, + 20.86681803845336, + 32.43873432263156, + 64.91234005889837, + 71.54029915166349, + 11.13706890220647, + 55.07930697185586, + 43.791352286892106, + 13.831947671728972, + 97.39019470916091, + 35.50775651228035, + 52.275862097336166, + 82.838655037009, + 8.568099335705881, + 0.8337112078307563, + 69.23145833259072, + 3.8541642374881446, + 70.55673656397397, + 71.99264788951747 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [1, 2, 2, 1], + "data": [ + 5.7273993492126465, + 5.64375114440918, + 5.453810214996338, + 5.758983135223389 + ], + "type": "float32" + } + } + ] +} \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_log_sum_exp.json b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_log_sum_exp.json new file mode 100644 index 00000000000..00c55ded519 --- /dev/null +++ b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_log_sum_exp.json @@ -0,0 +1,702 @@ +{ + "tests": [ + { + "name": "reduceLogSumExp float32 1D tensor all positive default options", // default options: {axes: null, keepDimensions: false} + "inputs": { + "input": { + "shape": [24], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 90.59076690673828, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 1D tensor all negative default options", + "inputs": { + "input": { + "shape": [24], + "data": [ + -38.42346567796924, + -16.384904409140333, + -46.629634356968474, + -45.81843819006337, + -95.61458783306942, + -90.64578309257007, + -6.279945972307587, + -24.546370226192565, + -82.15882762280646, + -76.8746037170462, + -44.181029848800904, + -97.35032678020788, + -75.52388056554437, + -97.984203822517, + -97.46591756173142, + -85.89237745468532, + -27.34196668605746, + -76.80293743058324, + -93.91905595799426, + -25.62251637659385, + -36.49762778486478, + -96.2163796024006, + -33.56049055386055, + -94.06451375473459 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": -6.279904842376709, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 1D tensor all positive integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + 34, + 45, + 5, + 45, + 97, + 11, + 83, + 84, + 17, + 17, + 11, + 20, + 59, + 97, + 44, + 90, + 80, + 59, + 86, + 91, + 33, + 84, + 27, + 27 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 97.69485473632812, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 1D tensor all negative integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + -91, + -77, + -2, + -34, + -77, + -38, + -92, + -45, + -54, + -11, + -64, + -76, + -53, + -19, + -41, + -83, + -21, + -34, + -73, + -33, + -10, + -71, + -82, + -26 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": -1.999541163444519, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 2D tensor default options", + "inputs": { + "input": { + "shape": [4, 6], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 90.59076690673828, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 3D tensor default options", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 90.59076690673828, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 4D tensor default options", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 90.59076690673828, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 5D tensor default options", + "inputs": { + "input": { + "shape": [2, 1, 4, 1, 3], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 90.59076690673828, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 3D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "options": { + "axes": [2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 68.81230926513672, + 90.56975555419922, + 86.6993637084961, + 81.53412628173828, + 64.85645294189453, + 82.32090759277344 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 4D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "options": { + "axes": [0, 2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 81.53375244140625, + 86.180908203125, + 73.63322448730469, + 75.71652221679688, + 90.55726623535156, + 86.7118148803711 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 3D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 90.59076690673828, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 3D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1], + "data": [ + 90.59076690673828 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 4D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 90.59076690673828, + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 4D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1, 1], + "data": [ + 90.59076690673828 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 4D tensor options.axes with options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [2, 2], + "data": [ + 90.57815551757812, + 86.18093872070312, + 73.63323211669922, + 82.69600677490234 + ], + "type": "float32" + } + }, + { + "name": "reduceLogSumExp float32 4D tensor options.axes with options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 66.1870735698, + 68.69164623929768, + 15.529598361334717, + 65.62419160755422, + 86.18090584091544, + 7.382064010955736, + 1.6365860724411263, + 90.55726458445135, + 86.69934561770543, + 75.7165191675748, + 67.0074429215978, + 9.943717120210827, + 25.779723516449636, + 60.15386290165083, + 73.63322249161153, + 81.53375339603328, + 64.85643136289283, + 54.04977784193004, + 33.380943217138224, + 32.50357565109678, + 61.30902295453489, + 56.95015629977242, + 35.37182024244998, + 82.32090594141081 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [1, 2, 2, 1], + "data": [ + 90.57815551757812, + 86.18093872070312, + 73.63323211669922, + 82.69600677490234 + ], + "type": "float32" + } + } + ] +} \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_mean.json b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_mean.json index adc29023f89..db20b17a835 100644 --- a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_mean.json +++ b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_mean.json @@ -501,7 +501,9 @@ }, "expected": { "shape": [1, 1, 1], - "data": 40.31047439575195, + "data": [ + 40.31047439575195 + ], "type": "float32" } }, @@ -586,7 +588,9 @@ }, "expected": { "shape": [1, 1, 1, 1], - "data": 40.31047439575195, + "data": [ + 40.31047439575195 + ], "type": "float32" } }, diff --git a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_sum.json b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_sum.json index 3e887294631..6da78ae804a 100644 --- a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_sum.json +++ b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_sum.json @@ -501,7 +501,9 @@ }, "expected": { "shape": [1, 1, 1], - "data": 1313.87939453125, + "data": [ + 1313.87939453125 + ], "type": "float32" } }, @@ -586,7 +588,9 @@ }, "expected": { "shape": [1, 1, 1, 1], - "data": 1313.87939453125, + "data": [ + 1313.87939453125 + ], "type": "float32" } }, diff --git a/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_sum_square.json b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_sum_square.json new file mode 100644 index 00000000000..cf6bbb65d41 --- /dev/null +++ b/tests/wpt/web-platform-tests/webnn/resources/test_data/reduce_sum_square.json @@ -0,0 +1,702 @@ +{ + "tests": [ + { + "name": "reduceSumSquare float32 1D tensor all positive default options", // default options: {axes: null, keepDimensions: false} + "inputs": { + "input": { + "shape": [24], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 73275.859375, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 1D tensor all negative default options", + "inputs": { + "input": { + "shape": [24], + "data": [ + -21.452013864072896, + -57.30725907408611, + -72.83901116638569, + -0.059761520988928396, + -71.73678939977705, + -44.61909261218302, + -43.120022676836946, + -91.33738230600645, + -33.172438449832086, + -48.55593151678299, + -95.62864137865712, + -20.876631045259614, + -16.69083735987158, + -39.52110386011864, + -7.51078560359592, + -90.59026921164444, + -42.21683259824742, + -76.74274815005997, + -98.2242026863753, + -60.27295167122231, + -74.7320278737084, + -8.543684369072977, + -59.88873484887647, + -17.99894136421551 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 80052.015625, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 1D tensor all positive integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + 52, + 48, + 2, + 66, + 30, + 39, + 14, + 23, + 81, + 94, + 78, + 64, + 38, + 16, + 63, + 11, + 46, + 95, + 17, + 47, + 40, + 53, + 87, + 43 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 71347, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 1D tensor all negative integers default options", // test with float32 values which are equivalent to integers + "inputs": { + "input": { + "shape": [24], + "data": [ + -10, + -60, + -69, + -88, + -35, + -84, + -74, + -42, + -93, + -26, + -40, + -55, + -92, + -26, + -39, + -30, + -61, + -16, + -16, + -36, + -9, + -89, + -45, + -29 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 73634, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 2D tensor default options", + "inputs": { + "input": { + "shape": [4, 6], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 73275.859375, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 3D tensor default options", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 73275.859375, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 4D tensor default options", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 73275.859375, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 5D tensor default options", + "inputs": { + "input": { + "shape": [2, 1, 4, 1, 3], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "expected": { + "name": "output", + "data": 73275.859375, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 3D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "options": { + "axes": [2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 9709.013671875, + 10817.7685546875, + 14548.470703125, + 16385.8515625, + 9287.357421875, + 12527.3974609375 + ], + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 4D tensor options.axes", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "options": { + "axes": [0, 2] + }, + "expected": { + "name": "output", + "shape": [2, 3], + "data": [ + 8585.87109375, + 7700.654296875, + 19889.1796875, + 7113.0439453125, + 16775.708984375, + 13211.3994140625 + ], + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 3D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 73275.859375, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 3D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 3, 4], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1], + "data": [ + 73275.859375 + ], + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 4D tensor options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": false + }, + "expected": { + "name": "output", + "data": 73275.859375, + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 4D tensor options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "options": { + "keepDimensions": true + }, + "expected": { + "name": "output", + "shape": [1, 1, 1, 1], + "data": [ + 73275.859375 + ], + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 4D tensor options.axes with options.keepDimensions=false", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [2, 2], + "data": [ + 12302.474609375, + 22772.77734375, + 26919.09765625, + 11281.5068359375 + ], + "type": "float32" + } + }, + { + "name": "reduceSumSquare float32 4D tensor options.axes with options.keepDimensions=true", + "inputs": { + "input": { + "shape": [2, 2, 2, 3], + "data": [ + 52.5615351837915, + 2.6261063680439234, + 82.04877759500097, + 14.401411284784604, + 33.96051675758925, + 83.93837980977771, + 47.44504659398938, + 19.177289239472593, + 13.493006439137023, + 44.15238362662202, + 86.53118079678906, + 70.20919468463771, + 25.67262870756528, + 79.73770192548034, + 66.42284577584445, + 70.40363336301188, + 13.503327808732468, + 41.22539754662389, + 6.654552839238637, + 85.79743668166222, + 89.91348950671976, + 53.55647451130674, + 39.48537158474081, + 3.9460408540454184 + ], + "type": "float32" + } + }, + "options": { + "axes": [1, 3] + }, + "expected": { + "name": "output", + "shape": [1, 2, 2, 1], + "data": [ + 12302.474609375, + 22772.77734375, + 26919.09765625, + 11281.5068359375 + ], + "type": "float32" + } + } + ] +} \ No newline at end of file diff --git a/tests/wpt/web-platform-tests/webnn/resources/utils.js b/tests/wpt/web-platform-tests/webnn/resources/utils.js index 49f1762a3bb..37748fd57a4 100644 --- a/tests/wpt/web-platform-tests/webnn/resources/utils.js +++ b/tests/wpt/web-platform-tests/webnn/resources/utils.js @@ -33,11 +33,12 @@ const loadTests = (operationName) => { } }; - const capitalLetterMatches = operationName.match(/[A-Z]/); + const capitalLetterMatches = operationName.match(/[A-Z]/g); if (capitalLetterMatches !== null) { - // for example: the test data JSON file for leakyRelu is leaky_relu.json - const capitalLetter = capitalLetterMatches[0]; - operationName = operationName.replace(capitalLetter, `_${capitalLetter.toLowerCase()}`); + // for example: the test data JSON file for leakyRelu is leaky_relu.json and for reduceLogSum is reduce_log_sum.json + capitalLetterMatches.forEach( + capitalLetter => operationName = operationName.replace(capitalLetter, `_${capitalLetter.toLowerCase()}`) + ) } const json = loadJSON(`/webnn/resources/test_data/${operationName}.json`); const resources = JSON.parse(json.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m)); @@ -212,7 +213,7 @@ const getSoftmaxPrecisionTolerance = (resources, operationName) => { }; /** - * Get ULP tolerance of reduceMean, reduceProduct, reduceSum operations. + * Get ULP tolerance of reduction operations. * @param {Object} resources - Resources used for building a graph * @param {String} operationName - An operation name * @returns {Number} A tolerance number @@ -229,11 +230,33 @@ const getReductionPrecisionTolerance = (resources, operationName) => { } else { sizes = inputShape; } - let tolerance = sizes.reduce( - (accumulator, currentValue) => accumulator * currentValue + const reducedElementCount = sizes.reduce( + (accumulator, currentValue) => accumulator * currentValue ); - if (operationName === 'reduceMean') { - tolerance += 2; + let tolerance; + switch (operationName) { + case 'reduceL1': + case 'reduceProduct': + case 'reduceSum': + tolerance = reducedElementCount; + break; + case 'reduceL2': + tolerance = reducedElementCount * 2 + 1; + break; + case 'reduceMean': + tolerance = reducedElementCount + 2; + break; + case 'reduceLogSum': + tolerance = reducedElementCount + 18; + break; + case 'reduceLogSumExp': + tolerance = reducedElementCount * 2 + 18; + break; + case 'reduceSumSquare': + tolerance = reducedElementCount * 2; + break; + default: + break; } return tolerance; }; @@ -279,11 +302,16 @@ const PrecisionMetrics = { // End Pooling operations prelu: {ULP: {float32: 1, float16: 1}}, // Begin Reduction operations + reduceL1: {ULP: {float32: getReductionPrecisionTolerance, float16: getReductionPrecisionTolerance}}, + reduceL2: {ULP: {float32: getReductionPrecisionTolerance, float16: getReductionPrecisionTolerance}}, + reduceLogSum: {ULP: {float32: getReductionPrecisionTolerance, float16: getReductionPrecisionTolerance}}, + reduceLogSumExp: {ULP: {float32: getReductionPrecisionTolerance, float16: getReductionPrecisionTolerance}}, reduceMax: {ULP: {float32: 0, float16: 0}}, reduceMean: {ULP: {float32: getReductionPrecisionTolerance, float16: getReductionPrecisionTolerance}}, reduceMin: {ULP: {float32: 0, float16: 0}}, reduceProduct: {ULP: {float32: getReductionPrecisionTolerance, float16: getReductionPrecisionTolerance}}, reduceSum: {ULP: {float32: getReductionPrecisionTolerance, float16: getReductionPrecisionTolerance}}, + reduceSumSquare: {ULP: {float32: getReductionPrecisionTolerance, float16: getReductionPrecisionTolerance}}, // End Reduction operations relu: {ULP: {float32: 0, float16: 0}}, reshape: {ULP: {float32: 0, float16: 0}}, diff --git a/tests/wpt/web-platform-tests/webrtc/protocol/dtls-certificates.html b/tests/wpt/web-platform-tests/webrtc/protocol/dtls-certificates.html new file mode 100644 index 00000000000..bc4794cbc19 --- /dev/null +++ b/tests/wpt/web-platform-tests/webrtc/protocol/dtls-certificates.html @@ -0,0 +1,42 @@ + + + +RTCPeerConnection DTLS certifcate interop + + + +