Skip to content

Commit

Permalink
Working plugin module with dummy plugin and tests passing
Browse files Browse the repository at this point in the history
  • Loading branch information
jmathai committed Jun 28, 2019
1 parent 5bbaade commit e23f30e
Show file tree
Hide file tree
Showing 7 changed files with 233 additions and 14 deletions.
Empty file added elodie/plugins/__init__.py
Empty file.
Empty file.
17 changes: 17 additions & 0 deletions elodie/plugins/dummy/dummy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""
Dummy plugin object used for tests.
.. moduleauthor:: Jaisen Mathai <jaisen@jmathai.com>
"""
from __future__ import print_function
from builtins import object


class Dummy(object):
"""A dummy class to execute plugin actions for tests."""
def __init__(self):
self.before_ran = False

def before(self, file_path, destination_path, media):
self.before_ran = True

Empty file.
33 changes: 19 additions & 14 deletions elodie/plugins/googlephotos/googlephotos.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,18 @@
"""
Plugin object.
.. moduleauthor:: Jaisen Mathai <jaisen@jmathai.com>
"""
from __future__ import print_function
from builtins import object


class GooglePhotos(object):
"""A class to execute plugin actions."""
pass

"""
import json
from google_auth_oauthlib.flow import InstalledAppFlow
Expand All @@ -16,13 +31,9 @@
creds = Credentials.from_authorized_user_file(auth_file, scopes)
except:
print('no creds')
flow = InstalledAppFlow.from_client_secrets_file('/Users/jaisen/Downloads/client_secret_1004259275591-5g51kj0feetbet88o8le5i16hbr3ucb6.apps.googleusercontent.com-3.json', scopes)
#creds = tools.run_flow(flow, store)
creds = flow.run_local_server(host='localhost',
port=8080,
authorization_prompt_message="",
success_message='The auth flow is complete; you may close this window.',
open_browser=True)
#flow = InstalledAppFlow.from_client_secrets_file('/Users/jaisen/Downloads/client_secret_1004259275591-5g51kj0feetbet88o8le5i16hbr3ucb6.apps.googleusercontent.com-3.json', scopes)
flow = InstalledAppFlow.from_client_secrets_file('/Users/jaisen/Downloads/client_secret_1004259275591-ogsk179e96cs0h126qj590mofk86gdqo.apps.googleusercontent.com.json', scopes)
creds = flow.run_local_server()
cred_dict = {
'token': creds.token,
'refresh_token': creds.refresh_token,
Expand All @@ -39,10 +50,6 @@
session = AuthorizedSession(creds)
"""google_photos = build('photoslibrary', 'v1', http=creds.authorize(Http()))
results = google_photos.mediaItems().list().execute()
items = results.get('mediaItems', [])
print(items)"""
session.headers["Content-type"] = "application/octet-stream"
session.headers["X-Goog-Upload-Protocol"] = "raw"
Expand All @@ -51,13 +58,11 @@
photo_file = open("/Users/jaisen/Downloads/test.png", mode='rb')
photo_bytes = photo_file.read()
print(photo_bytes)

upload_token = session.post('https://photoslibrary.googleapis.com/v1/uploads', photo_bytes)
if (upload_token.status_code == 200) and (upload_token.content):
create_body = json.dumps({"newMediaItems":[{"description":"","simpleMediaItem":{"uploadToken":upload_token.content.decode()}}]}, indent=4)
resp = session.post('https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate', create_body).json()
print(resp)
if "newMediaItemResults" in resp:
status = resp["newMediaItemResults"][0]["status"]
print(status)
print(status)"""
54 changes: 54 additions & 0 deletions elodie/plugins/plugins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""
Plugin object.
.. moduleauthor:: Jaisen Mathai <jaisen@jmathai.com>
"""
from __future__ import print_function
from builtins import object

from importlib import import_module

from elodie.config import load_config
from elodie import log


class Plugins(object):
"""A class to execute plugin actions."""

def __init__(self):
self.plugins = []
self.classes = {}

def load(self):
"""Load plugins from config file.
"""
config = load_config()
if 'Plugins' in config and 'plugins' in config['Plugins']:
config_plugins = config['Plugins']['plugins'].split(',')
for plugin in config_plugins:
plugin_lower = plugin.lower()
try:
# We attempt to do the following.
# 1. Load the module of the plugin.
# 2. Instantiate an object of the plugin's class.
# 3. Add the plugin to the list of plugins.
#
# #3 should only happen if #2 doesn't throw an error
this_module = import_module('elodie.plugins.{}.{}'.format(plugin_lower, plugin_lower))
self.classes[plugin] = getattr(this_module, plugin)()
# We only append to self.plugins if we're able to load the class
self.plugins.append(plugin)
except ImportError:
log.warn('Could not load plugin {}'.format(plugin))
continue
except:
log.warn('Some error occurred initiating plugin {}'.format(plugin))
continue


def run_all_before(self, file_path, destination_path, media):
"""Process `before` methods of each plugin that was loaded.
"""
for cls in self.classes:
this_method = getattr(self.classes[cls], 'before')
this_method(file_path, destination_path, media)
143 changes: 143 additions & 0 deletions elodie/tests/plugins_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
from __future__ import absolute_import
# Project imports
import mock
import os
import sys
from tempfile import gettempdir

sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))))

from . import helper
from elodie.config import load_config
from elodie.plugins.plugins import Plugins

@mock.patch('elodie.config.config_file', '%s/config.ini-load-plugins-unset-backwards-compat' % gettempdir())
def test_load_plugins_unset_backwards_compat():
with open('%s/config.ini-load-plugins-unset-backwards-compat' % gettempdir(), 'w') as f:
f.write("""
""")
if hasattr(load_config, 'config'):
del load_config.config

plugins = Plugins()
plugins.load()

if hasattr(load_config, 'config'):
del load_config.config

assert plugins.plugins == [], plugins.plugins

@mock.patch('elodie.config.config_file', '%s/config.ini-load-plugins-exists-not-set' % gettempdir())
def test_load_plugins_exists_not_set():
with open('%s/config.ini-load-plugins-exists-not-set' % gettempdir(), 'w') as f:
f.write("""
[Plugins]
""")
if hasattr(load_config, 'config'):
del load_config.config

plugins = Plugins()
plugins.load()

if hasattr(load_config, 'config'):
del load_config.config

assert plugins.plugins == [], plugins.plugins

@mock.patch('elodie.config.config_file', '%s/config.ini-load-plugins-one' % gettempdir())
def test_load_plugins_one():
with open('%s/config.ini-load-plugins-one' % gettempdir(), 'w') as f:
f.write("""
[Plugins]
plugins=Dummy
""")
if hasattr(load_config, 'config'):
del load_config.config

plugins = Plugins()
plugins.load()

if hasattr(load_config, 'config'):
del load_config.config

assert plugins.plugins == ['Dummy'], plugins.plugins
assert len(plugins.classes) == 1, len(plugins.classes)

@mock.patch('elodie.config.config_file', '%s/config.ini-load-plugins-one-with-invalid' % gettempdir())
def test_load_plugins_one_with_invalid():
with open('%s/config.ini-load-plugins-one' % gettempdir(), 'w') as f:
f.write("""
[Plugins]
plugins=DNE
""")
if hasattr(load_config, 'config'):
del load_config.config

plugins = Plugins()
plugins.load()

if hasattr(load_config, 'config'):
del load_config.config

assert plugins.plugins == [], plugins.plugins
assert len(plugins.classes) == 0, len(plugins.classes)

@mock.patch('elodie.config.config_file', '%s/config.ini-load-plugins-many' % gettempdir())
def test_load_plugins_many():
with open('%s/config.ini-load-plugins-many' % gettempdir(), 'w') as f:
f.write("""
[Plugins]
plugins=GooglePhotos,Dummy
""")
if hasattr(load_config, 'config'):
del load_config.config

plugins = Plugins()
plugins.load()

if hasattr(load_config, 'config'):
del load_config.config

assert plugins.plugins == ['GooglePhotos','Dummy'], plugins.plugins
assert len(plugins.classes) == 2, len(plugins.classes)

@mock.patch('elodie.config.config_file', '%s/config.ini-load-plugins-many-with-invalid' % gettempdir())
def test_load_plugins_set_many_with_invalid():
with open('%s/config.ini-load-plugins-many-with-invalid' % gettempdir(), 'w') as f:
f.write("""
[Plugins]
plugins=GooglePhotos,Dummy,DNE
""")
if hasattr(load_config, 'config'):
del load_config.config

plugins = Plugins()
plugins.load()

if hasattr(load_config, 'config'):
del load_config.config

assert plugins.plugins == ['GooglePhotos','Dummy'], plugins.plugins

@mock.patch('elodie.config.config_file', '%s/config.ini-run-before' % gettempdir())
def test_run_before():
with open('%s/config.ini-run-before' % gettempdir(), 'w') as f:
f.write("""
[Plugins]
plugins=Dummy
""")
if hasattr(load_config, 'config'):
del load_config.config

plugins = Plugins()
plugins.load()
print(plugins.classes)
before_ran_1 = plugins.classes['Dummy'].before_ran
plugins.run_all_before('', '', '')
before_ran_2 = plugins.classes['Dummy'].before_ran

if hasattr(load_config, 'config'):
del load_config.config

assert before_ran_1 == False, before_ran_1
assert before_ran_2 == True, before_ran_2

0 comments on commit e23f30e

Please sign in to comment.