Skip to content

Commit

Permalink
moved validation function to utils//test working
Browse files Browse the repository at this point in the history
  • Loading branch information
Kully committed May 1, 2018
1 parent fe31851 commit e55e81c
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 62 deletions.
2 changes: 1 addition & 1 deletion plotly/tests/test_core/test_stream/test_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
tk = 'vaia8trjjb'
config = {'plotly_domain': 'https://plot.ly',
'plotly_streaming_domain': 'stream.plot.ly',
'plotly_api_domain': 'https://api.plot.ly',
'plotly_api_domain': 'https://api.plot.ly',
'plotly_ssl_verification': False}


Expand Down
15 changes: 8 additions & 7 deletions plotly/tests/test_core/test_tools/test_file_tools.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from plotly import tools, session
from plotly.tests.utils import PlotlyTestCase

import ipdb
import warnings


Expand Down Expand Up @@ -54,14 +53,16 @@ def test_set_config_file_world_readable(self):
self.assertRaises(TypeError, tools.set_config_file, **kwargs)

def test_set_config_expected_error_msg(self):
kwargs = {'plotly_domain': 'http://www.foo-bar.com'}
#self.assertRaises(UserWarning, tools.set_config_file, **kwargs)
print 'abcd'
b = tools.set_config_file(**kwargs)
print type(b)


# Check that UserWarning is being called with http plotly_domain

with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
kwargs = {'plotly_domain': 'http://www.foo-bar.com'}
tools.set_config_file(**kwargs)
assert len(w) == 1
assert issubclass(w[-1].category, UserWarning)
assert "plotly_domain" in str(w[-1].message)

def test_reset_config_file(self):

Expand Down
64 changes: 11 additions & 53 deletions plotly/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,36 +49,6 @@
ALTERNATIVE_HISTNORM = 'probability'


http_msg = (
"The plotly_domain and plotly_api_domain of your config file must start "
"with 'https', 'http'.\n If you are not using On-Prem then run the "
"following code to ensure your plotly_domain and plotly_api_domain start "
"with 'https':\n\n\n"
"import plotly\n"
"plotly.tools.set_config_file(\n"
" plotly_domain='https://plot.ly',\n"
" plotly_api_domain='https://api.plot.ly'\n"
")\n\n\n"
"If you are using On-Prem then you will need to use your company's "
"domain and api_domain urls:\n\n\n"
"import plotly\n"
"plotly.tools.set_config_file(\n"
" plotly_domain='https://plotly.your-company.com',\n"
" plotly_api_domain='https://plotly.your-company.com'\n"
")\n\n\n"
"Make sure to replace `your-company.com` with the URL of your Plotly "
"On-Premise server.\nSee "
"https://plot.ly/python/getting-started/#special-instructions-for-plotly-onpremise-users "
"for more help with getting started with On-Prem."
)


def _validate_domains(*domains):
for d in domains:
if not d.lower().startswith('https'):
warnings.warn(http_msg, category=UserWarning)


# Warning format
def warning_on_one_line(message, category, filename, lineno,
file=None, line=None):
Expand Down Expand Up @@ -216,14 +186,15 @@ def set_config_file(plotly_domain=None,
:param (bool) world_readable: True = public, False = private
"""
# import ipdb; ipdb.set_trace()
if not check_file_permissions():
raise exceptions.PlotlyError("You don't have proper file permissions "
"to run this function.")
ensure_local_plotly_files() # make sure what's there is OK
utils.validate_world_readable_and_sharing_settings({
'sharing': sharing, 'world_readable': world_readable})

settings = get_config_file(validate=False)
settings = get_config_file()
if isinstance(plotly_domain, six.string_types):
settings['plotly_domain'] = plotly_domain
elif plotly_domain is not None:
Expand All @@ -250,12 +221,9 @@ def set_config_file(plotly_domain=None,
raise TypeError('auto_open should be a boolean')

# validate plotly_domain and plotly_api_domain
list_of_domains = []
if plotly_domain is not None:
list_of_domains.append(plotly_domain)
if plotly_api_domain is not None:
list_of_domains.append(plotly_api_domain)
_validate_domains(*list_of_domains)
utils.validate_plotly_domains(
{'plotly_domain': plotly_domain, 'plotly_api_domain': plotly_api_domain}
)

if isinstance(world_readable, bool):
settings['world_readable'] = world_readable
Expand All @@ -272,7 +240,7 @@ def set_config_file(plotly_domain=None,
ensure_local_plotly_files() # make sure what we just put there is OK


def get_config_file(validate=True, *args):
def get_config_file(*args):
"""Return specified args from `~/.plotly/.config`. as tuple.
Returns all if no arguments are specified.
Expand All @@ -283,19 +251,9 @@ def get_config_file(validate=True, *args):
"""
if check_file_permissions():
ensure_local_plotly_files() # make sure what's there is OK
returned_obj = utils.load_json_dict(CONFIG_FILE, *args)
return utils.load_json_dict(CONFIG_FILE, *args)
else:
returned_obj = FILE_CONTENT[CONFIG_FILE]

list_of_domains = []
for domain in ['plotly_domain', 'plotly_api_domain']:
if domain in returned_obj:
list_of_domains.append(returned_obj[domain])

if validate:
_validate_domains(*list_of_domains)

return returned_obj
return FILE_CONTENT[CONFIG_FILE]


def reset_config_file():
Expand Down Expand Up @@ -331,7 +289,7 @@ def get_embed(file_owner_or_url, file_id=None, width="100%", height=525):
"""
plotly_rest_url = (session.get_session_config().get('plotly_domain') or
get_config_file(validate=False)['plotly_domain'])
get_config_file()['plotly_domain'])
if file_id is None: # assume we're using a url
url = file_owner_or_url
if url[:len(plotly_rest_url)] != plotly_rest_url:
Expand Down Expand Up @@ -428,7 +386,7 @@ def embed(file_owner_or_url, file_id=None, width="100%", height=525):
if file_id:
plotly_domain = (
session.get_session_config().get('plotly_domain') or
get_config_file(validate=False)['plotly_domain']
get_config_file()['plotly_domain']
)
url = "{plotly_domain}/~{un}/{fid}".format(
plotly_domain=plotly_domain,
Expand All @@ -454,7 +412,7 @@ def embed(file_owner_or_url, file_id=None, width="100%", height=525):


### mpl-related tools ###
@utils.template_doc(**get_config_file(validate=False))
@utils.template_doc(**get_config_file())
def mpl_to_plotly(fig, resize=False, strip_style=False, verbose=False):
"""Convert a matplotlib figure to plotly dictionary and send.
Expand Down
38 changes: 37 additions & 1 deletion plotly/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
"""
from __future__ import absolute_import

import decimal
import os.path
import re
import sys
import threading
import decimal
import warnings
from collections import deque

import pytz
Expand All @@ -32,6 +33,30 @@
lock = threading.Lock()


http_msg = (
"The plotly_domain and plotly_api_domain of your config file must start "
"with 'https', 'http'.\n If you are not using On-Prem then run the "
"following code to ensure your plotly_domain and plotly_api_domain start "
"with 'https':\n\n\n"
"import plotly\n"
"plotly.tools.set_config_file(\n"
" plotly_domain='https://plot.ly',\n"
" plotly_api_domain='https://api.plot.ly'\n"
")\n\n\n"
"If you are using On-Prem then you will need to use your company's "
"domain and api_domain urls:\n\n\n"
"import plotly\n"
"plotly.tools.set_config_file(\n"
" plotly_domain='https://plotly.your-company.com',\n"
" plotly_api_domain='https://plotly.your-company.com'\n"
")\n\n\n"
"Make sure to replace `your-company.com` with the URL of your Plotly "
"On-Premise server.\nSee "
"https://plot.ly/python/getting-started/#special-instructions-for-plotly-onpremise-users "
"for more help with getting started with On-Prem."
)


### general file setup tools ###

def load_json_dict(filename, *args):
Expand Down Expand Up @@ -297,6 +322,7 @@ def encode_as_decimal(obj):
else:
raise NotEncodable


### unicode stuff ###
def decode_unicode(coll):
if isinstance(coll, list):
Expand Down Expand Up @@ -436,6 +462,16 @@ def validate_world_readable_and_sharing_settings(option_set):
)


def validate_plotly_domains(option_set):
domains_not_none = []
for d in ['plotly_domain', 'plotly_api_domain']:
if d in option_set and option_set[d]:
domains_not_none.append(option_set[d])

if not all(d.lower().startswith('https') for d in domains_not_none):
warnings.warn(http_msg, category=UserWarning)


def set_sharing_and_world_readable(option_set):
if 'world_readable' in option_set and 'sharing' not in option_set:
option_set['sharing'] = (
Expand Down

0 comments on commit e55e81c

Please sign in to comment.