Ejemplo n.º 1
0
def step_impl(context, page_name, format='json'):
    context.page_name = page_name.lower().replace(' ', '_')
    file_path = os.path.abspath(os.path.dirname(__file__))
    page_report_path = os.path.normpath(
        '../../../../%saccessibility/output/%s.report.%s' % (
            QA_FOLDER_PATH,
            context.page_name,
            format
        )
    )
    context.current_report = os.path.join(
        file_path,
        page_report_path

    )
    print(os.path.relpath)
    log.debug('Getting json from %s' % context.current_report)
    print(type(context.current_report))
    with open(context.current_report, 'r') as f:
        try:
            log.debug('Loading %s' % format)
            context.results_json = json.load(f)
        except Exception as e:
            sys.stdout.write(
                'Error: Invalid JSON in %s: %s\n' % (
                    context.current_report,
                    e
                )
            )
            assert False
Ejemplo n.º 2
0
 def write_json(self, text, page, directory):
     page = page.replace(' ', '_')
     if page == '/' or page == '':
         page = 'index'
     file_path = '%s/accessibility/output/%s.report.json' % (
         QA_FOLDER_PATH,
         page
     )
     log.debug('Writing json to path %s' % file_path)
     if not os.path.exists(directory):
         os.makedirs(directory)
     with open(file_path, 'w+') as f:
         f.write(text)
Ejemplo n.º 3
0
def score_under(context, expected_score):
    log.debug(context.current_node)
    if context.current_node < expected_score:
        assert True
    else:
        sys.stderr.write(
            "Expected a score under %s for %s:\nInstead got %s%s" % (
                str(expected_score),
                context.page_name,
                context.current_node,
                context.detailed_reason
            )
        )
        assert False
Ejemplo n.º 4
0
 def write_html(self, data, page):
     page = page.replace(' ', '_')
     if page == '/' or page == '':
         page = 'index'
     file_path = '%s/accessibility/output/%s.report.html' % (
         QA_FOLDER_PATH,
         page
     )
     data = response.content
     data.decode('utf-8')
     log.debug('Writing html to path %s' % file_path)
     if not os.path.exists(directory):
         os.makedirs(directory)
     with open(file_path, 'w') as f:
         f.write(data)
         f.close()
Ejemplo n.º 5
0
    def escaped_login(self, host, id_for_client):
        log.debug('Getting escaped login headers.')
        '''Lighthouse wants escaped double quotes for the headers passed to --extra-headers flag'''

        code, bearer_header = make_iap_request(host, id_for_client)
        assert code == 200, 'Did not get 200 creating bearer token: %d' % (
            code)
        stringified_code = str(bearer_header['Authorization'])
        headers = {
            'Authorization': stringified_code,
        }
        for h in default_headers:
            headers[h] = default_headers[h]
        log.debug('These are the escaped headers:\n%s' %
                  json.dumps(json.dumps(headers)))
        escaped_headers = json.dumps(json.dumps(headers))
        return escaped_headers, headers
Ejemplo n.º 6
0
 def get_page(self, escaped_headers, url, uri):
     '''This gets the lighthouse results for the page.'''
     headers = {"X-Extra-Headers": escaped_headers}
     log.debug('Headers for lighthouse request:\n%s' % headers)
     full_url = url + uri
     log.debug('full_url for lighthouse request:\n%s' % full_url)
     generated_command = '%s/lighthouse?url=%s' % (LIGHTHOUSE_IMAGE,
                                                   full_url)
     log.debug('Generated Command for lighthouse is %s' % generated_command)
     r = requests.get(generated_command, headers=headers)
     if r.status_code != requests.codes.ok:
         assert r.status_code == requests.codes.ok, '%s\n%s\ncommand:\n%s' % (
             str(r.status_code), str(r.text), str(generated_command))
     else:
         return r.text
Ejemplo n.º 7
0
 def __init__(self):
     log.debug('Setting up requests')
Ejemplo n.º 8
0
Archivo: seo.py Proyecto: Jiff21/qa
 def __init__(self):
     log.debug('Setting up seo checker')
Ejemplo n.º 9
0
def make_iap_request(url, client_id):
    """Makes a request to an application protected by Identity-Aware Proxy.

    Args:
      url: The Identity-Aware Proxy-protected URL to fetch.
      client_id: The client ID used by Identity-Aware Proxy.

    Returns:
      The page body, or raises an exception if the page couldn't be retrieved.
    """
    log.debug('In make_iap_request:\nurl is %s and client_id is %s.' %
              (url, client_id))
    # Figure out what environment we're running in and get some preliminary
    # information about the service account.
    bootstrap_credentials, _ = google.auth.default(scopes=[IAM_SCOPE])
    if isinstance(bootstrap_credentials,
                  google.oauth2.credentials.Credentials):
        raise Exception('make_iap_request is only supported for service '
                        'accounts.')
    elif isinstance(bootstrap_credentials, google.auth.app_engine.Credentials):
        requests_toolbelt.adapters.appengine.monkeypatch()

    # For service account's using the Compute Engine metadata service,
    # service_account_email isn't available until refresh is called.
    bootstrap_credentials.refresh(Request())

    signer_email = bootstrap_credentials.service_account_email
    if isinstance(bootstrap_credentials,
                  google.auth.compute_engine.credentials.Credentials):
        # Since the Compute Engine metadata service doesn't expose the service
        # account key, we use the IAM signBlob API to sign instead.
        # In order for this to work:
        #
        # 1. Your VM needs the https://www.googleapis.com/auth/iam scope.
        #    You can specify this specific scope when creating a VM
        #    through the API or gcloud. When using Cloud Console,
        #    you'll need to specify the "full access to all Cloud APIs"
        #    scope. A VM's scopes can only be specified at creation time.
        #
        # 2. The VM's default service account needs the "Service Account Actor"
        #    role. This can be found under the "Project" category in Cloud
        #    Console, or roles/iam.serviceAccountActor in gcloud.
        signer = google.auth.iam.Signer(Request(), bootstrap_credentials,
                                        signer_email)
    else:
        # A Signer object can sign a JWT using the service account's key.
        signer = bootstrap_credentials.signer

    # Construct OAuth 2.0 service account credentials using the signer
    # and email acquired from the bootstrap credentials.
    service_account_credentials = google.oauth2.service_account.Credentials(
        signer,
        signer_email,
        token_uri=OAUTH_TOKEN_URI,
        additional_claims={'target_audience': client_id})

    # service_account_credentials gives us a JWT signed by the service
    # account. Next, we use that to obtain an OpenID Connect token,
    # which is a JWT signed by Google.
    google_open_id_connect_token = get_google_open_id_connect_token(
        service_account_credentials)

    # Fetch the Identity-Aware Proxy-protected URL, including an
    # Authorization header containing "Bearer " followed by a
    # Google-issued OpenID Connect token for the service account.
    bearer_header = {
        'Authorization': 'Bearer {}'.format(google_open_id_connect_token)
    }
    resp = requests.get(url,
                        headers={
                            'Authorization':
                            'Bearer {}'.format(google_open_id_connect_token)
                        })
    if resp.status_code == 403:
        raise Exception(
            'Service account {} does not have permission to '
            'access the IAP-protected application.'.format(signer_email))
    elif resp.status_code != 200:
        raise Exception(
            'Bad response from application: {!r} / {!r} / {!r}'.format(
                resp.status_code, resp.headers, resp.text))
    else:
        print(resp.status_code)
        return resp.status_code, bearer_header