Commit fe26e9d3 authored by rajendrant's avatar rajendrant Committed by Commit Bot

Remove chrome_proxy web_driver tests

Fixed: 1124785
Change-Id: I88e275c933ec12ee1d8630797f2c1dd3462bcb19
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2397535
Commit-Queue: rajendrant <rajendrant@chromium.org>
Reviewed-by: default avatarRobert Ogden <robertogden@chromium.org>
Cr-Commit-Position: refs/heads/master@{#804967}
parent 9e09e169
file://components/data_reduction_proxy/OWNERS
# COMPONENT: Internals>Network>DataProxy
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
runtime: go
api_version: go1
handlers:
- url: /image
static_dir: image
- url: /.*
script: _go_app
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Test server to facilitate the data reduction proxy Telemetry tests.
//
// The server runs at http://chromeproxy-test.appspot.com/. Please contact
// people in OWNERS for server issues.
//
// For running an AppEngine Go server, see:
// https://developers.google.com/appengine/docs/go/gettingstarted/introduction.
//
// The goal is to keep the test logic on the client side (Telemetry)
// as much as possible. This server will only return a resource
// and/or override the response as specified by the data encoded
// in the request URL queries.
//
// For example, on receiving the query
// /default?respBody=bmV3IGJvZHk=&respHeader=eyJWaWEiOlsiVmlhMSIsIlZpYTIiXX0%3D&respStatus=204
// the server sends back a response with
// Status code: 204
// Additional response headers: "Via: Via1" and "Via: Via2"
// Response body: "new body"
// where the overriding headers and body are base64 encoded in the request query.
package server
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
func init() {
http.HandleFunc("/requestHeader", requestHeader)
http.HandleFunc("/resource", resource)
http.HandleFunc("/default", defaultResponse)
http.HandleFunc("/blackhole", blackholeProxy)
}
// requestHander returns request headers in response body as text.
func requestHeader(w http.ResponseWriter, r *http.Request) {
r.Header.Write(w)
}
// resource returns the content of a data file specified by "r=" query as the response body.
// The response could be overridden by request queries.
// See parseOverrideQuery.
func resource(w http.ResponseWriter, r *http.Request) {
wroteBody, err := applyOverride(w, r)
if err != nil || wroteBody {
return
}
path, ok := r.URL.Query()["r"]
if !ok || len(path) != 1 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("no resource in query"))
return
}
if _, err := writeFromFile(w, path[0]); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf("Failed to get %s: %v", path[0], err)))
return
}
}
// defaultResponse returns "ok" as response body, if the body is not overridden.
// The response could be overridden by request queries.
// See parseOverrideQuery.
func defaultResponse(w http.ResponseWriter, r *http.Request) {
wroteBody, err := applyOverride(w, r)
if err != nil {
return
}
if !wroteBody {
w.Write([]byte("ok"))
}
}
// blackholePoxy delays 90 seconds for proxied responses, in order to test if
// the proxy will timeout on the site. Responds immediately to any other request.
func blackholeProxy(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.Header.Get("via"), "Chrome-Compression-Proxy") {
// Causes timeout on proxy, will then send BLOCK_ONCE.
// Appspot will 502 traffic at 120 seconds with no response.
time.Sleep(90 * time.Second);
w.Write([]byte("You are proxy"));
} else {
w.Write([]byte("You are direct"));
}
}
type override struct {
status int
header http.Header
body io.Reader
}
// parseOverrideQuery parses the queries in r and returns an override.
// It supports the following queries:
// "respStatus": an integer to override response status code;
// "respHeader": base64 encoded JSON data to override the response headers;
// "respBody": base64 encoded JSON data to override the response body.
func parseOverrideQuery(r *http.Request) (*override, error) {
q := r.URL.Query()
resp := &override{0, nil, nil}
if v, ok := q["respStatus"]; ok && len(v) == 1 && len(v[0]) > 0 {
status, err := strconv.ParseInt(v[0], 10, 0)
if err != nil {
return nil, errors.New(fmt.Sprintf("respStatus: %v", err))
}
resp.status = int(status)
}
if v, ok := q["respHeader"]; ok && len(v) == 1 && len(v[0]) > 0 {
// Example header after base64 decoding:
// {"Via": ["Telemetry Test", "Test2"], "Name": ["XYZ"], "Cache-Control": ["public"]}
headerValue, err := base64.URLEncoding.DecodeString(v[0])
if err != nil {
return nil, errors.New(fmt.Sprintf("Decoding respHeader: %v", err))
}
var header http.Header
err = json.Unmarshal(headerValue, &header)
if err != nil {
return nil, errors.New(
fmt.Sprintf("Unmarlshal (%s) error: %v", string(headerValue), err))
}
resp.header = header
}
if v, ok := q["respBody"]; ok && len(v) == 1 && len(v[0]) > 0 {
body, err := base64.URLEncoding.DecodeString(v[0])
if err != nil {
return nil, errors.New(
fmt.Sprintf("Decoding respBody error: %v", err))
}
resp.body = bytes.NewBuffer(body)
}
return resp, nil
}
// applyOverride applies the override queries in r to w and returns whether the response
// body is overridden.
func applyOverride(w http.ResponseWriter, r *http.Request) (wroteBody bool, err error) {
resp, err := parseOverrideQuery(r)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return false, err
}
headers := w.Header()
if resp.header != nil {
for k, v := range resp.header {
headers[k] = v
}
}
if resp.status > 0 {
w.WriteHeader(resp.status)
}
if resp.body != nil {
_, err := io.Copy(w, resp.body)
return true, err
}
return false, nil
}
func writeFromFile(w io.Writer, filename string) (int64, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
return io.Copy(w, f)
}
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package server
import (
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strconv"
"testing"
)
func composeQuery(path string, code int, headers http.Header, body []byte) (string, error) {
u, err := url.Parse(path)
if err != nil {
return "", err
}
q := u.Query()
if code > 0 {
q.Set("respStatus", strconv.Itoa(code))
}
if headers != nil {
h, err := json.Marshal(headers)
if err != nil {
return "", err
}
q.Set("respHeader", base64.URLEncoding.EncodeToString(h))
}
if len(body) > 0 {
q.Set("respBody", base64.URLEncoding.EncodeToString(body))
}
u.RawQuery = q.Encode()
return u.String(), nil
}
func TestResponseOverride(t *testing.T) {
tests := []struct {
name string
code int
headers http.Header
body []byte
}{
{name: "code", code: 204},
{name: "body", body: []byte("new body")},
{
name: "headers",
headers: http.Header{
"Via": []string{"Via1", "Via2"},
"Content-Type": []string{"random content"},
},
},
{
name: "everything",
code: 204,
body: []byte("new body"),
headers: http.Header{
"Via": []string{"Via1", "Via2"},
"Content-Type": []string{"random content"},
},
},
}
for _, test := range tests {
u, err := composeQuery("http://test.com/override", test.code, test.headers, test.body)
if err != nil {
t.Errorf("%s: composeQuery: %v", test.name, err)
return
}
req, err := http.NewRequest("GET", u, nil)
if err != nil {
t.Errorf("%s: http.NewRequest: %v", test.name, err)
return
}
w := httptest.NewRecorder()
defaultResponse(w, req)
if test.code > 0 {
if got, want := w.Code, test.code; got != want {
t.Errorf("%s: response code: got %d want %d", test.name, got, want)
return
}
}
if test.headers != nil {
for k, want := range test.headers {
got, ok := w.HeaderMap[k]
if !ok || !reflect.DeepEqual(got, want) {
t.Errorf("%s: header %s: code: got %v want %v", test.name, k, got, want)
return
}
}
}
if test.body != nil {
if got, want := string(w.Body.Bytes()), string(test.body); got != want {
t.Errorf("%s: body: got %s want %s", test.name, got, want)
return
}
}
}
}
This diff is collapsed.
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
from decorators import AndroidOnly
from decorators import ChromeVersionBetweenInclusiveM
from decorators import ChromeVersionEqualOrAfterM
from decorators import ChromeVersionBeforeM
from decorators import SkipIfForcedBrowserArg
from common import ParseFlags
from common import IntegrationTest
class DecoratorSmokeTest(IntegrationTest):
def setUp(self):
sys.argv.append('--browser_arg=test')
def AndroidOnlyFunction(self):
# This function should never be called.
self.fail()
@AndroidOnly
def testDecorator(self):
# This test should always result as 'skipped' or pass if --android given.
if not ParseFlags().android:
self.AndroidOnlyFunction()
@ChromeVersionBeforeM(0)
def testVersionBeforeDecorator(self):
self.fail('This function should not be called when the Chrome Milestone is '
'greater than 0')
@ChromeVersionBetweenInclusiveM(0, 999999999)
def testVersionBetweenDecorator(self):
pass
@ChromeVersionBetweenInclusiveM(0, 1)
def testVersionBetweenDecorator(self):
self.fail('This function should not be called when the Chrome Milestone is '
'outside the range [0, 1].')
@ChromeVersionEqualOrAfterM(999999999)
def testVersionAfterDecorator(self):
self.fail('This function should not be called when the Chrome Milestone is '
'less than 999999999')
@SkipIfForcedBrowserArg('test')
def testSkipBrowserArg(self):
self.fail('This function should not be called')
if __name__ == '__main__':
IntegrationTest.RunAllTests()
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import re
from common import ParseFlags
from common import TestDriver
# Platform-specific decorators.
# These decorators can be used to only run a test function for certain platforms
# by annotating the function with them.
def AndroidOnly(func):
def wrapper(*args, **kwargs):
if ParseFlags().android:
func(*args, **kwargs)
else:
args[0].skipTest('This test runs on Android only.')
return wrapper
def NotAndroid(func):
def wrapper(*args, **kwargs):
if not ParseFlags().android:
func(*args, **kwargs)
else:
args[0].skipTest('This test does not run on Android.')
return wrapper
def WindowsOnly(func):
def wrapper(*args, **kwargs):
if sys.platform == 'win32':
func(*args, **kwargs)
else:
args[0].skipTest('This test runs on Windows only.')
return wrapper
def NotWindows(func):
def wrapper(*args, **kwargs):
if sys.platform != 'win32':
func(*args, **kwargs)
else:
args[0].skipTest('This test does not run on Windows.')
return wrapper
def LinuxOnly(func):
def wrapper(*args, **kwargs):
if sys.platform.startswith('linux'):
func(*args, **kwargs)
else:
args[0].skipTest('This test runs on Linux only.')
return wrapper
def NotLinux(func):
def wrapper(*args, **kwargs):
if sys.platform.startswith('linux'):
func(*args, **kwargs)
else:
args[0].skipTest('This test does not run on Linux.')
return wrapper
def MacOnly(func):
def wrapper(*args, **kwargs):
if sys.platform == 'darwin':
func(*args, **kwargs)
else:
args[0].skipTest('This test runs on Mac OS only.')
return wrapper
def NotMac(func):
def wrapper(*args, **kwargs):
if sys.platform == 'darwin':
func(*args, **kwargs)
else:
args[0].skipTest('This test does not run on Mac OS.')
return wrapper
chrome_version = None
def GetChromeVersion():
with TestDriver() as t:
t.LoadURL('about:blank')
ua = t.ExecuteJavascriptStatement('navigator.userAgent')
match = re.search('Chrome/[0-9\.]+', ua)
if not match:
raise Exception('Could not find Chrome version in User-Agent: %s' % ua)
chrome_version = ua[match.start():match.end()]
version = chrome_version[chrome_version.find('/') + 1:]
version_split = version.split('.')
milestone = int(version_split[0])
print('Running on Chrome M%d (%s)' % (milestone, version))
return milestone
def ChromeVersionBeforeM(milestone):
def puesdo_wrapper(func):
def wrapper(*args, **kwargs):
global chrome_version
if chrome_version == None:
chrome_version = GetChromeVersion()
if chrome_version < milestone:
func(*args, **kwargs)
else:
args[0].skipTest('This test does not run above M%d.' % milestone)
return wrapper
return puesdo_wrapper
def ChromeVersionEqualOrAfterM(milestone):
def puesdo_wrapper(func):
def wrapper(*args, **kwargs):
global chrome_version
if chrome_version == None:
chrome_version = GetChromeVersion()
if chrome_version >= milestone:
func(*args, **kwargs)
else:
args[0].skipTest('This test does not run below M%d.' % milestone)
return wrapper
return puesdo_wrapper
def ChromeVersionBetweenInclusiveM(after, before):
def puesdo_wrapper(func):
def wrapper(*args, **kwargs):
global chrome_version
if chrome_version == None:
chrome_version = GetChromeVersion()
if chrome_version <= before and chrome_version >= after:
func(*args, **kwargs)
else:
args[0].skipTest('This test only runs between M%d and M%d (inclusive).'
% (after, before))
return wrapper
return puesdo_wrapper
def Slow(func):
def wrapper(*args, **kwargs):
if ParseFlags().skip_slow:
args[0].skipTest('Skipping slow test.')
else:
func(*args, **kwargs)
return wrapper
def SkipIfForcedBrowserArg(arg):
def puesdo_wrapper(func):
def wrapper(*args, **kwargs):
if ParseFlags().browser_args and arg in ParseFlags().browser_args:
args[0].skipTest(
'Test skipped because "%s" was given on the command line' % arg)
return wrapper
return puesdo_wrapper
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import SocketServer
import os
import socket
import ssl
import struct
import tempfile
import threading
from OpenSSL import crypto
class BlackHoleHandler(SocketServer.BaseRequestHandler):
"""This handler consumes all request input and makes no responses.
"""
def handle(self):
"""Consume the request and then do nothing.
"""
data = self.request.recv(4096)
while len(data) > 0:
data = self.request.recv(4096)
class InvalidTLSHandler(SocketServer.BaseRequestHandler):
"""This handler injects unencrypted TCP after a TLS handshake.
"""
def handle(self):
"""Do a TLS handshake on the new connection then inject unencrypted bytes.
"""
# ssl.wrap_socket will automatically do a TLS handshake before returning.
ssl_conn = ssl.wrap_socket(self.request, server_side=True,
**_CreateSelfSignedCert())
self.request.sendall('this is unencrypted. oops')
class TCPResetHandler(SocketServer.BaseRequestHandler):
"""This handler sends TCP RST immediately after the connection is established.
"""
def handle(self):
"""Reset the socket once connected.
"""
# Setting these socket options tells Python to TCP RST the connection when
# socket.close() is called instead of the default TCP FIN.
self.request.recv(4096)
self.request.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', 1, 0))
self.request.close()
class TLSResetHandler(SocketServer.BaseRequestHandler):
"""This handler sends TCP RST immediately after the TLS handshake.
"""
def handle(self):
"""Reset the socket after TLS handshake.
"""
# ssl.wrap_socket will automatically do a TLS handshake before returning.
ssl_conn = ssl.wrap_socket(self.request, server_side=True,
**_CreateSelfSignedCert())
# Allow the request to be sent.
ssl_conn.recv(4096)
# Setting these socket options tells the OS to TCP RST the connection when
# socket.close() is called instead of the default TCP FIN.
self.request.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', 1, 0))
self.request.close()
class LocalEmulationServer:
"""This server is a simple wrapper for building servers with request handlers.
This class wraps Python's basic network server stack, providing a simple API
for Chrome-Proxy tests to use.
Attributes:
_port: the port to bind and listen to
_handler_class: the handler class to handle new connections with
_server: a reference to the underlying server
"""
def __init__(self, port, handler_class, server_class=SocketServer.TCPServer):
self._port = port
self._handler_class = handler_class
self._server_class = server_class
self._server = None
def StartAndReturn(self, timeout=30):
"""Start the server in a new thread and return once the server is running.
A new server of the given server_class at init is started with the given
handler. The server will listen forever in a new thread unless Shutdown() is
called.
Args:
timeout: The timeout to start the server.
"""
self._server = self._server_class(("0.0.0.0", self._port),
self._handler_class)
event = threading.Event()
def StartServer():
self._server.serve_forever()
def WaitForRunning(event):
while not event.is_set():
try:
s = socket.create_connection(("127.0.0.1", self._port))
event.set()
s.close()
except:
pass
start_thread = threading.Thread(target=StartServer)
start_thread.daemon = True
start_thread.start()
thread = threading.Thread(target=WaitForRunning, args=[event])
thread.start()
if not event.wait(timeout=timeout):
event.set()
raise Exception("Emulation server didn't start in %d seconds" % timeout)
def Shutdown(self):
"""Shutdown a running server.
Calls shutdown() on the underlying server instance, closing the spawned
thread.
"""
if self._server:
self._server.shutdown()
self._server.server_close()
def _CreateSelfSignedCert():
"""Creates a self-signed certificate and key in the machine's temp directory.
Returns:
a dict suitable for expansion to many ssl functions
"""
temp_dir = tempfile.gettempdir()
cert_path = os.path.join(temp_dir, "selfsigned.crt")
pkey_path = os.path.join(temp_dir, "private.key")
# Create a private key pair.
pk = crypto.PKey()
pk.generate_key(crypto.TYPE_RSA, 3072)
# Create a certificate and sign it.
cert = crypto.X509()
cert.get_subject().C = "US"
cert.get_subject().ST = "California"
cert.get_subject().L = "Mountain View"
cert.get_subject().O = "Fake Company Name"
cert.get_subject().OU = "Fake Company Org Name"
cert.get_subject().CN = "localhost"
cert.set_serial_number(1337)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(60*60*24*365) # 1 year
cert.set_issuer(cert.get_subject())
cert.set_pubkey(pk)
cert.sign(pk, 'sha1')
# Dump to files.
with open(cert_path, "wt") as cert_f:
cert_f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
with open(pkey_path, "wt") as pkey_f:
pkey_f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pk))
# Return the filenames in a dict that can be expanded into ssl function args.
return {"certfile": cert_path, "keyfile": pkey_path}
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import common
import sys
if __name__ == "__main__":
results = common.IntegrationTest.RunAllTests(run_all_tests=True)
if results.errors or results.failures:
sys.exit(2)
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import re
from common import TestDriver
from common import IntegrationTest
from decorators import ChromeVersionEqualOrAfterM
LITEPAGES_REGEXP = r'https://\w+\.litepages\.googlezip\.net/.*'
class SubresourceRedirect(IntegrationTest):
def enableSubresourceRedirectFeature(self, test_driver):
test_driver.EnableChromeFeature('SubresourceRedirect<SubresourceRedirect')
test_driver.AddChromeArg('--force-variation-ids=-1')
test_driver.AddChromeArg('--force-fieldtrials=SubresourceRedirect/Enabled')
test_driver.AddChromeArg(
'--force-fieldtrial-params='
'SubresourceRedirect.Enabled:enable_subresource_server_redirect/true')
test_driver.EnableChromeFeature('OptimizationHints')
test_driver.EnableChromeFeature('OptimizationHintsFetching')
test_driver.EnableChromeFeature(
'OptimizationHintsFetchingAnonymousDataConsent')
test_driver.AddChromeArg('--enable-spdy-proxy-auth')
test_driver.AddChromeArg('--dont-require-litepage-redirect-infobar')
test_driver.AddChromeArg('--override-https-image-compression-infobar')
# Verifies that image subresources on a page have been returned
# from the compression server.
@ChromeVersionEqualOrAfterM(77)
def testCompressImage(self):
with TestDriver() as test_driver:
self.enableSubresourceRedirectFeature(test_driver)
test_driver.LoadURL(
'https://probe.googlezip.net/static/image_delayed_load.html')
test_driver.SleepUntilHistogramHasEntry(
'SubresourceRedirect.CompressionAttempt.ServerResponded')
image_responses = 0
for response in test_driver.GetHTTPResponses():
print response
content_type = ''
if 'content-type' in response.response_headers:
content_type = response.response_headers['content-type']
if ('image/' in content_type
and re.match(LITEPAGES_REGEXP, response.url)
and 200 == response.status):
image_responses += 1
self.assertEqual(5, image_responses)
# Verifies that when the image compression server serves a
# redirect, then Chrome fetches the image directly.
@ChromeVersionEqualOrAfterM(77)
def testOnRedirectImage(self):
with TestDriver() as test_driver:
self.enableSubresourceRedirectFeature(test_driver)
# Image compression server returns a 307 for all images on this webpage.
test_driver.LoadURL(
'https://testsafebrowsing.appspot.com/s/image_small.html')
server_bypass = 0
image_responses = 0
for response in test_driver.GetHTTPResponses():
content_type = ''
if 'content-type' in response.response_headers:
content_type = response.response_headers['content-type']
if ('image/' in content_type
and re.match(LITEPAGES_REGEXP, response.url)
and 200 == response.status):
image_responses += 1
if ('https://testsafebrowsing.appspot.com/s/bad_assets/small.png'
== response.url and 200 == response.status):
server_bypass += 1
self.assertEqual(1, server_bypass)
self.assertEqual(0, image_responses)
# Verifies that non-image subresources aren't redirected to the
# compression server.
@ChromeVersionEqualOrAfterM(77)
def testNoCompressNonImage(self):
with TestDriver() as test_driver:
self.enableSubresourceRedirectFeature(test_driver)
test_driver.LoadURL('https://probe.googlezip.net/testvideo.html')
image_responses = 0
for response in test_driver.GetHTTPResponses():
content_type = ''
if 'content-type' in response.response_headers:
content_type = response.response_headers['content-type']
if ('image/' in content_type
and re.match(LITEPAGES_REGEXP, response.url)
and 200 == response.status):
image_responses += 1
self.assertEqual(0, image_responses)
# Verifies that non-secure connections aren't redirected to the
# compression server.
@ChromeVersionEqualOrAfterM(77)
def testNoCompressNonHTTPS(self):
with TestDriver() as test_driver:
self.enableSubresourceRedirectFeature(test_driver)
test_driver.LoadURL('http://probe.googlezip.net/static/index.html')
image_responses = 0
for response in test_driver.GetHTTPResponses():
content_type = ''
if 'content-type' in response.response_headers:
content_type = response.response_headers['content-type']
if ('image/' in content_type
and re.match(LITEPAGES_REGEXP, response.url)
and 200 == response.status):
image_responses += 1
self.assertEqual(0, image_responses)
if __name__ == '__main__':
IntegrationTest.RunAllTests()
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import io
import os
import platform
import sys
import time
import unittest
import common
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,
os.pardir, 'tools', 'variations'))
import fieldtrial_util
test_blacklist = [
# These tests set their own field trials and should be ignored.
'quic.Quic.testCheckPageWithQuicProxy',
'quic.Quic.testCheckPageWithQuicProxyTransaction',
'smoke.Smoke.testCheckPageWithHoldback',
]
def GetExperimentArgs():
"""Returns a list of arguments with all tested field trials.
This function is a simple wrapper around the variation team's fieldtrail_util
script that generates command line arguments to test Chromium field trials.
Returns:
an array of command line arguments to pass to chrome
"""
config_path = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,
os.pardir, 'testing', 'variations', 'fieldtrial_testing_config.json')
my_platform = ''
if common.ParseFlags().android:
my_platform = 'android'
elif platform.system().lower() == 'linux':
my_platform = 'linux'
elif platform.system().lower() == 'windows':
my_platform = 'windows'
elif platform.system().lower() == 'darwin':
my_platform = 'mac'
else:
raise Exception('unknown platform!')
return fieldtrial_util.GenerateArgs(config_path, my_platform)
def GenerateTestSuites():
"""A generator function that yields non-blacklisted tests to run.
This function yields test suites each with a single test case whose id is not
blacklisted in the array at the top of this file.
Yields:
non-blacklisted test suites to run
"""
loader = unittest.TestLoader()
for test_suite in loader.discover(os.path.dirname(__file__), pattern='*.py'):
for test_case in test_suite:
for test_method in test_case:
if test_method.id() not in test_blacklist:
ts = unittest.TestSuite()
ts.addTest(test_method)
yield (ts, test_method.id())
def ParseFlagsWithExtraBrowserArgs(extra_args):
"""Generates a function to override common.ParseFlags.
The returned function will honor everything in the original ParseFlags(), but
adds on additional browser_args.
Args:
extra_args: The extra browser agruments to add.
Returns:
A function to override common.ParseFlags with additional browser_args.
"""
original_flags = common.ParseFlags()
def AddExtraBrowserArgs():
original_flags.browser_args = ((original_flags.browser_args if
original_flags.browser_args else '') + ' ' + extra_args)
return original_flags
return AddExtraBrowserArgs
def main():
"""Runs all non-blacklisted tests against Chromium field trials.
This script run all chrome proxy integration tests that haven't been
blacklisted against the field trial testing configuration used by Chromium
perf bots.
"""
flags = common.ParseFlags()
experiment_args = ' '.join(GetExperimentArgs())
common.ParseFlags = ParseFlagsWithExtraBrowserArgs(experiment_args)
# Each test is wrapped in its own test suite so results can be evaluated
# individually.
for test_suite, test_id in GenerateTestSuites():
buf = io.BytesIO()
sys.stdout.write('%s... ' % test_id)
sys.stdout.flush()
testRunner = unittest.runner.TextTestRunner(stream=buf, verbosity=2,
buffer=(not flags.disable_buffer))
result = testRunner.run(test_suite)
if result.wasSuccessful():
print('ok')
else:
print('failed')
print(buf.getvalue())
print('To repeat this test, run: ')
print("%s %s %s --test_filter=%s --browser_args='%s'" % (
sys.executable,
os.path.join(os.path.dirname(__file__), 'run_all_tests.py'), ' '.join(
sys.argv[1:]), '.'.join(test_id.split('.')[1:]), experiment_args))
if flags.failfast:
return
if __name__ == '__main__':
main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment