Skip to content

Commit

Permalink
1st pass at re-enabling automated linting/tests, + autopep8 some file…
Browse files Browse the repository at this point in the history
…s to reduce linter errors
  • Loading branch information
sqrrrl committed Dec 1, 2021
1 parent 3cd6507 commit cc9575c
Show file tree
Hide file tree
Showing 47 changed files with 384 additions and 183 deletions.
47 changes: 47 additions & 0 deletions .github/scripts/authorize.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#! /bin/bash

# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Utility for generating credentials used by tests.

# Union of scopes used by samples
SCOPES=(
"https://www.googleapis.com/auth/drive"
"https://www.googleapis.com/auth/drive.activity"
"https://mail.google.com/"
"https://www.googleapis.com/auth/classroom.courses"
"https://www.googleapis.com/auth/classroom.announcements"
"https://www.googleapis.com/auth/classroom.rosters"
"https://www.googleapis.com/auth/classroom.topics"
"https://www.googleapis.com/auth/classroom.guardianlinks.students"
"https://www.googleapis.com/auth/classroom.coursework.students"
)

if [ -z "$CLIENT_ID_FILE" ]; then
echo "CLIENT_ID_FILE environment not set. Please set and run again."
exit 1
fi

if [ ! -f "$CLIENT_ID_FILE" ]; then
echo "$CLIENT_ID_FILE not found."
exit 1
fi

printf -v EXPANDED_SCOPES '%s,' "${SCOPES[@]}"
gcloud auth application-default login \
--client-id-file=client_secret.json \
--scopes="${EXPANDED_SCOPES}"

cat "${HOME}/.config/gcloud/application_default_credentials.json"
21 changes: 21 additions & 0 deletions .github/scripts/lint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#! /bin/bash
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

export LC_ALL=C.UTF-8
export LANG=C.UTF-8

find . -iname "*.py" | xargs pylint
49 changes: 49 additions & 0 deletions .github/scripts/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#! /bin/bash
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

export LC_ALL=C.UTF-8
export LANG=C.UTF-8
export PIPENV_PYTHON="${PYENV_ROOT}/shims/python"
export GOOGLE_APPLICATION_CREDENTIALS="${HOME}/secrets/default_credentials.json"

if [ -f "requirements.txt" ]; then
pipenv install -r "requirements.txt"
fi

TEST_DIRS=`find . -name '*_test.py' -exec dirname '{}' \;| sort -u`

exit_code=0

for DIR in ${TEST_DIRS[@]}; do
pushd "${DIR}"
echo $DIR
if [ -f "requirements.txt" ]; then
# If requirements.txt present, create a new isolated environment
touch Pipfile
pipenv install -r "requirements.txt"
fi
pipenv run python -m unittest discover
status=$?
if [ $status -ne 0 ]; then
exit_code=$status
fi
popd
done

if [ $exit_code -ne 0 ]; then
echo "Tests failed."
fi

exit $exit_code
49 changes: 49 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: CI

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: 3.6
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pylint
- name: Lint with pylint
run: ./.github/scripts/lint.sh
test:
runs-on: ubuntu-latest
strategy:
matrix:
# TODO - expand matrix once stable
python-version: [3.6]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pipenv
- name: Write test credentials
run: |
mkdir $HOME/secrets
echo "$DEFAULT_CREDENTIALS" > $HOME/secrets/default_credentials.json
echo "$CLIENT_ID_FILE" > $HOME/secrets/client_id.json
env:
DEFAULT_CREDENTIALS: ${{secrets.SNIPPETS_DEFAULT_CREDENTIALS}}
CLIENT_ID_FILE: ${{secrets.SNIPPETS_CLIENT_ID_FILE}}
- name: Run tests
run: ./.github/scripts/test.sh
10 changes: 0 additions & 10 deletions .travis.yml

This file was deleted.

5 changes: 3 additions & 2 deletions admin_sdk/directory/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']


def main():
"""Shows basic usage of the Admin SDK Directory API.
Prints the emails and names of the first 10 users in the domain.
Expand Down Expand Up @@ -50,7 +51,7 @@ def main():
# Call the Admin SDK Directory API
print('Getting the first 10 users in the domain')
results = service.users().list(customer='my_customer', maxResults=10,
orderBy='email').execute()
orderBy='email').execute()
users = results.get('users', [])

if not users:
Expand All @@ -59,7 +60,7 @@ def main():
print('Users:')
for user in users:
print(u'{0} ({1})'.format(user['primaryEmail'],
user['name']['fullName']))
user['name']['fullName']))


if __name__ == '__main__':
Expand Down
6 changes: 4 additions & 2 deletions admin_sdk/reports/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/admin.reports.audit.readonly']


def main():
"""Shows basic usage of the Admin SDK Reports API.
Prints the time, email, and name of the last 10 login events in the domain.
Expand Down Expand Up @@ -50,7 +51,7 @@ def main():
# Call the Admin SDK Reports API
print('Getting the last 10 login events')
results = service.activities().list(userKey='all', applicationName='login',
maxResults=10).execute()
maxResults=10).execute()
activities = results.get('items', [])

if not activities:
Expand All @@ -59,7 +60,8 @@ def main():
print('Logins:')
for activity in activities:
print(u'{0}: {1} ({2})'.format(activity['id']['time'],
activity['actor']['email'], activity['events'][0]['name']))
activity['actor']['email'], activity['events'][0]['name']))


if __name__ == '__main__':
main()
Expand Down
4 changes: 3 additions & 1 deletion admin_sdk/reseller/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/apps.order']


def main():
"""Calls the Admin SDK Reseller API. Prints the customer ID, SKU ID,
and plan name of the first 10 subscriptions managed by the domain.
Expand Down Expand Up @@ -57,7 +58,8 @@ def main():
print('Subscriptions:')
for subscription in subscriptions:
print(u'{0} ({1}, {2})'.format(subscription['customerId'],
subscription['skuId'], subscription['plan']['planName']))
subscription['skuId'], subscription['plan']['planName']))


if __name__ == '__main__':
main()
Expand Down
5 changes: 3 additions & 2 deletions apps_script/execute/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from httplib2 import Http
from oauth2client import file as oauth_file, client, tools


def main():
"""Runs the sample.
"""
Expand All @@ -42,7 +43,7 @@ def main():
try:
# Make the API request.
response = service.scripts().run(body=request,
scriptId=SCRIPT_ID).execute()
scriptId=SCRIPT_ID).execute()

if 'error' in response:
# The API executed, but the script returned an error.
Expand All @@ -59,7 +60,7 @@ def main():
print("Script error stacktrace:")
for trace in error['scriptStackTraceElements']:
print("\t{0}: {1}".format(trace['function'],
trace['lineNumber']))
trace['lineNumber']))
else:
# The structure of the result depends upon what the Apps Script
# function returns. Here, the function returns an Apps Script Object
Expand Down
1 change: 1 addition & 0 deletions apps_script/quickstart/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
}
'''.strip()


def main():
"""Calls the Apps Script API.
"""
Expand Down
6 changes: 3 additions & 3 deletions calendar/quickstart/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ def main():
service = build('calendar', 'v3', credentials=creds)

# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])

if not events:
Expand Down
2 changes: 2 additions & 0 deletions classroom/quickstart/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']


def main():
"""Shows basic usage of the Classroom API.
Prints the names of the first 10 courses the user has access to.
Expand Down Expand Up @@ -58,6 +59,7 @@ def main():
for course in courses:
print(course['name'])


if __name__ == '__main__':
main()
# [END classroom_quickstart]
10 changes: 4 additions & 6 deletions classroom/snippets/base_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import unittest
import httplib2
from googleapiclient import errors
from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build
from oauth2client import file, client, tools

Expand All @@ -40,12 +41,9 @@ def tearDownClass(cls):

@classmethod
def create_credentials(cls):
store = file.Storage('token.json')
credentials = None
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
credentials = tools.run_flow(flow, store)
return credentials
cls.credentials = GoogleCredentials.get_application_default()
scope = ['https://www.googleapis.com/auth/drive']
return cls.credentials.create_scoped(scope)

def setUp(self):
self.courses_to_delete = []
Expand Down
Loading

0 comments on commit cc9575c

Please sign in to comment.