Skip to content
This repository has been archived by the owner on Dec 13, 2022. It is now read-only.

Commit

Permalink
Merge branch '42-in_out_options' of github.com:open-contracting/touca…
Browse files Browse the repository at this point in the history
…n into 42-in_out_options
  • Loading branch information
aguilerapy committed Apr 22, 2020
2 parents e9cdcdf + 68afb21 commit eeda6fc
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 37 deletions.
30 changes: 12 additions & 18 deletions default/drive_options.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import print_function
import logging

from django.http import HttpResponse, JsonResponse
from google.auth.exceptions import DefaultCredentialsError
from google.auth.transport.requests import Request
Expand All @@ -9,38 +10,33 @@
from oauthlib.oauth2 import AccessDeniedError
from ocdstoucan.settings import OCDS_TOUCAN_CREDENTIALS_DRIVE

logger = logging.getLogger(__name__)

SCOPES = 'https://www.googleapis.com/auth/drive.file'


def upload_to_drive(filename, filepath, format=None, test=None, credentials=None):
def upload_to_drive(filename, filepath, format=None, credentials=None):
try:
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
OCDS_TOUCAN_CREDENTIALS_DRIVE, SCOPES)
if not test:
credentials = flow.run_local_server(port=0)

credentials = flow.run_local_server(port=0)
if credentials and not credentials.valid:
raise AccessDeniedError
service = build('drive', 'v3', credentials=credentials)

except AccessDeniedError:
return HttpResponse("Access Denied", status=400)

except DefaultCredentialsError:
service = None
except (AccessDeniedError, DefaultCredentialsError):
return HttpResponse("There was an error when trying to authenticate", status=400)

try:
if format == 'xlsx':
mimeType = 'application/vnd.google-apps.spreadsheet'
else:
if format == 'csv' or format is None:
mimeType = 'application/zip'
else:
mimeType = '*/*'
mimeType = 'application/zip'

file_metadata = {
'name': filename,
Expand All @@ -56,8 +52,6 @@ def upload_to_drive(filename, filepath, format=None, test=None, credentials=None
'id': results["id"]
})

except (TypeError, Exception, IOError, UnknownFileType):
if test:
return HttpResponse("Test", status=200)
else:
return HttpResponse("Fail Uploading", status=400)
except (TypeError, Exception, IOError, UnknownFileType) as e:
logger.debug(e)
return HttpResponse("There was an error when trying to upload files", status=400)
3 changes: 1 addition & 2 deletions default/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ def retrieve_result(request, folder, id, format=None):
file = DataFile(prefix, ext, id=str(id), folder=folder)

if output == 'drive':
is_test = request.GET.get('test')
return upload_to_drive(filename, file.path, format, test=is_test)
return upload_to_drive(filename, file.path, format)
else:
return FileResponse(open(file.path, 'rb'), filename=filename, as_attachment=True)

Expand Down
51 changes: 34 additions & 17 deletions tests/test_drive_options.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from unittest.mock import Mock
from unittest.mock import Mock, patch
from oauthlib.oauth2 import AccessDeniedError

from default import drive_options

from tests import ViewTestCase, ViewTests, path


Expand All @@ -11,30 +11,47 @@ class DriveTestCase(ViewTestCase, ViewTests):
'1.1/release-packages/0001-tender.json',
]

def test_go_with_files(self):
@patch('google_auth_oauthlib.flow.InstalledAppFlow.run_local_server')
@patch('default.drive_options.build')
def test_go_with_files(self, mock_build, mock_run_local_server):
mock_run_local_server.return_value.valid = True
mock_build.return_value.files.return_value.create.return_value.execute.return_value = {'id': 1}
contents = self.upload_and_go({'type': 'release-package'})

for extension, content in contents.items():
response = self.client.get(content['url'] + '?out=drive&test=true')
response = self.client.get(content['url'] + '?out=drive')
self.assertEqual(response.status_code, 200)

def test_access_denied(self):
credentials = Mock(valid=False, expired=False, refresh_token='test')
@patch('google_auth_oauthlib.flow.InstalledAppFlow.run_local_server')
def test_invalid_credentials(self, mock_run_local_server):
mock_run_local_server.return_value.valid = False
contents = self.upload_and_go({'type': 'release-package'})

response = self.client.get(contents['csv']['url'] + '?out=drive')
self.assertEqual(response.status_code, 400)
self.assertEqual(response.content, b'There was an error when trying to authenticate')

def test_refresh_fail(self):
credentials = Mock(valid=False, expired=True, refresh_token='test')
credentials.refresh = Mock(side_effect=AccessDeniedError())
response = drive_options.upload_to_drive(
filename="test",
filepath="test",
test=True,
filepath=path(self.files[0]),
format="json",
credentials=credentials
)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.content, b'There was an error when trying to authenticate')

def test_fail_uploading(self):
@patch('default.drive_options.build')
def test_upload_fail(self, mock_build):
mock_build.files = Mock(side_effect=IOError())
credentials = Mock(valid=False, expired=True, refresh_token='test')
for file in self.files:
response = drive_options.upload_to_drive(
filename="test",
filepath=path(file),
format="json",
credentials=credentials
)
self.assertEqual(response.status_code, 400)
response = drive_options.upload_to_drive(
filename="test",
filepath=path(self.files[0]),
format="json",
credentials=credentials
)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.content, b'There was an error when trying to upload files')

0 comments on commit eeda6fc

Please sign in to comment.