internal/screentest: check http status before page tasks

When a page request returned a 404 unexpectedly
it would cause a testcase that waited for a css
selector to timeout instead of reporting the
test failure for mismatched status. This change
adds the status check as a task instead of a post
test check to report the failure after navigating
to a page.

Change-Id: I31c1b5dab6a412558c501d99873bff91d8dbc105
Reviewed-on: https://go-review.googlesource.com/c/website/+/409615
Reviewed-by: Jonathan Amsterdam <jba@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Jamal Carvalho <jamal@golang.org>
Auto-Submit: Jamal Carvalho <jamal@golang.org>
diff --git a/internal/screentest/screentest.go b/internal/screentest/screentest.go
index 21912c0..868bcb5 100644
--- a/internal/screentest/screentest.go
+++ b/internal/screentest/screentest.go
@@ -777,6 +777,7 @@
 		chromedp.Navigate(url),
 		waitForEvent("networkIdle"),
 		reduceMotion(),
+		checkResponse(tc, &res),
 		tc.tasks,
 	)
 	switch tc.screenshotType {
@@ -790,10 +791,6 @@
 	if err := chromedp.Run(ctx, tasks); err != nil {
 		return nil, fmt.Errorf("chromedp.Run(...): %w", err)
 	}
-	if res.Status != tc.status {
-		fmt.Fprintf(&tc.output, "\nFAIL http status mismatch: got %d; want %d", res.Status, tc.status)
-		return nil, fmt.Errorf("bad status: %d", res.Status)
-	}
 	return buf, nil
 }
 
@@ -912,6 +909,16 @@
 	}
 }
 
+func checkResponse(tc *testcase, res *Response) chromedp.ActionFunc {
+	return func(context.Context) error {
+		if res.Status != tc.status {
+			fmt.Fprintf(&tc.output, "\nFAIL http status mismatch: got %d; want %d", res.Status, tc.status)
+			return fmt.Errorf("bad status: %d", res.Status)
+		}
+		return nil
+	}
+}
+
 // runConcurrently calls f on each integer from 0 to n-1,
 // with at most max invocations active at once.
 // It waits for all invocations to complete.
diff --git a/internal/screentest/testdata/fail.txt b/internal/screentest/testdata/fail.txt
index a64b335..2e99dee 100644
--- a/internal/screentest/testdata/fail.txt
+++ b/internal/screentest/testdata/fail.txt
@@ -3,3 +3,8 @@
 test homepage
 pathname /
 capture viewport
+
+test 404 missing selector
+pathname /404
+wait [role='treeitem'][aria-selected='true']
+capture viewport