Commit 921507f0 authored by Jérome Perrin's avatar Jérome Perrin

testRestrictedPythonSecurity: simplify and normalize multi lines tests

Always use textwrap.dedent implicitly so that we don't have to do it in
every test and disable the way of making multi lines scripts by passing
multiple arguments. Now there's only one way to do and every tests use the
same way
parent ef4060d7
...@@ -51,14 +51,13 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -51,14 +51,13 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
func = getattr(self.portal, name) func = getattr(self.portal, name)
return func(**kwargs) return func(**kwargs)
def createAndRunScript(self, *args, **kwargs): def createAndRunScript(self, code, **kwargs):
# we do not care the script name for security test thus use uuid1 # we do not care the script name for security test thus use uuid1
name = str(uuid.uuid1()) name = str(uuid.uuid1())
code = '\n'.join(args)
expected = kwargs.get('expected', None) expected = kwargs.get('expected', None)
script_container = self.portal.portal_skins.custom script_container = self.portal.portal_skins.custom
try: try:
createZODBPythonScript(script_container, name, '**kw', code) createZODBPythonScript(script_container, name, '**kw', textwrap.dedent(code))
if expected: if expected:
self.assertEqual(self.runScript(script_container, name, kwargs.get('kwargs', {})), expected) self.assertEqual(self.runScript(script_container, name, kwargs.get('kwargs', {})), expected)
else: else:
...@@ -72,13 +71,30 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -72,13 +71,30 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
and running the Script. and running the Script.
""" """
self.createAndRunScript('import datetime') self.createAndRunScript('import datetime')
self.createAndRunScript('import datetime', 'return datetime.datetime.now()') self.createAndRunScript('''
self.createAndRunScript('import datetime', 'return datetime.time.max') import datetime
self.createAndRunScript('import datetime', 'return datetime.date.today()') return datetime.datetime.now()
self.createAndRunScript('import datetime', 'return datetime.timedelta.min') ''')
self.createAndRunScript('import datetime', 'return datetime.tzinfo') self.createAndRunScript('''
self.createAndRunScript('import datetime', import datetime
"return datetime.datetime.strptime('', '')") return datetime.time.max
''')
self.createAndRunScript('''
import datetime
return datetime.date.today()
''')
self.createAndRunScript('''
import datetime
return datetime.timedelta.min
''')
self.createAndRunScript('''
import datetime
return datetime.tzinfo
''')
self.createAndRunScript('''
import datetime
return datetime.datetime.strptime('', '')
''')
def testDictClassMethod(self): def testDictClassMethod(self):
# This is intended to be allowed from the beggining # This is intended to be allowed from the beggining
...@@ -86,73 +102,99 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -86,73 +102,99 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
def testDecimalClassMethod(self): def testDecimalClassMethod(self):
# Now it is not allowed # Now it is not allowed
self.assertRaises(Unauthorized, self.assertRaises(
self.createAndRunScript, 'import decimal', Unauthorized,
'return decimal.Decimal.from_float(3.3)') self.createAndRunScript,
'''
import decimal
return decimal.Decimal.from_float(3.3)
''')
# allow it only in this test class to check # allow it only in this test class to check
import decimal import decimal
allow_class_attribute(decimal.Decimal, {"from_float":1}) allow_class_attribute(decimal.Decimal, {"from_float":1})
# make sure now we can run without raising Unauthorized # make sure now we can run without raising Unauthorized
self.createAndRunScript('import decimal', self.createAndRunScript('''
'return decimal.Decimal.from_float(3.3)') import decimal
return decimal.Decimal.from_float(3.3)
''')
def test_urlparse(self): def test_urlparse(self):
self.createAndRunScript( self.createAndRunScript('''
'import urlparse', import urlparse
'return urlparse.urlparse("http://example.com/pa/th/?q=s").path', return urlparse.urlparse("http://example.com/pa/th/?q=s").path
''',
expected='/pa/th/' expected='/pa/th/'
) )
# access computed attributes (property) is also OK # access computed attributes (property) is also OK
self.createAndRunScript( self.createAndRunScript('''
'import urlparse', import urlparse
'return urlparse.urlparse("http://example.com/pa/th/?q=s").hostname', return urlparse.urlparse("http://example.com/pa/th/?q=s").hostname
''',
expected='example.com' expected='example.com'
) )
self.createAndRunScript( self.createAndRunScript('''
'import urlparse', import urlparse
'return urlparse.urlsplit("http://example.com/pa/th/?q=s").path', return urlparse.urlsplit("http://example.com/pa/th/?q=s").path
''',
expected='/pa/th/' expected='/pa/th/'
) )
self.createAndRunScript( self.createAndRunScript('''
'import urlparse', import urlparse
'return urlparse.urldefrag("http://example.com/#frag")[1]', return urlparse.urldefrag("http://example.com/#frag")[1]
''',
expected='frag' expected='frag'
) )
self.createAndRunScript( self.createAndRunScript('''
'import urlparse', import urlparse
'return urlparse.parse_qs("q=s")', return urlparse.parse_qs("q=s")
''',
expected={'q': ['s']} expected={'q': ['s']}
) )
self.createAndRunScript( self.createAndRunScript('''
'import urlparse', import urlparse
'return urlparse.parse_qsl("q=s")', return urlparse.parse_qsl("q=s")
''',
expected=[('q', 's')] expected=[('q', 's')]
) )
def testRandom(self): def testRandom(self):
self.createAndRunScript('import random', self.createAndRunScript('''
'return random.Random().getrandbits(10)') import random
return random.Random().getrandbits(10)
''')
def testSystemRandom(self): def testSystemRandom(self):
self.createAndRunScript('import random', self.createAndRunScript('''
'return random.SystemRandom().getrandbits(10)') import random
return random.SystemRandom().getrandbits(10)
''')
def test_os_urandom(self): def test_os_urandom(self):
self.createAndRunScript('import os', self.createAndRunScript('''
'return os.urandom(10)') import os
return os.urandom(10)
''')
# other "unsafe" os members are not exposed # other "unsafe" os members are not exposed
self.assertRaises(Unauthorized, self.assertRaises(
self.createAndRunScript, 'import os', Unauthorized,
'return os.path.exists("/")') self.createAndRunScript,
self.assertRaises(Unauthorized, '''
self.createAndRunScript, 'import os', import os
'return os.system') return os.path.exists("/")
''')
self.assertRaises(
Unauthorized,
self.createAndRunScript,
'''
import os
return os.system
''')
self.assertRaises(Unauthorized, self.assertRaises(Unauthorized,
self.createAndRunScript, 'from os import system') self.createAndRunScript, 'from os import system')
def test_set(self): def test_set(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
s = set() s = set()
s.add(1) s.add(1)
s.clear() s.clear()
...@@ -174,12 +216,10 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -174,12 +216,10 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
s.symmetric_difference_update([1]) s.symmetric_difference_update([1])
s.union([1]) s.union([1])
s.update() s.update()
'''), ''')
)
def test_frozenset(self): def test_frozenset(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
s = frozenset([1, 2]) s = frozenset([1, 2])
s.copy() s.copy()
s.difference([1]) s.difference([1])
...@@ -189,73 +229,66 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -189,73 +229,66 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
s.issuperset([1]) s.issuperset([1])
s.symmetric_difference([1]) s.symmetric_difference([1])
s.union([1]) s.union([1])
'''), ''')
)
def test_sorted(self): def test_sorted(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
returned = [] returned = []
for i in sorted([2, 3, 1]): for i in sorted([2, 3, 1]):
returned.append(i) returned.append(i)
return returned return returned
'''), ''',
expected=[1, 2, 3], expected=[1, 2, 3],
) )
def test_reversed(self): def test_reversed(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
returned = [] returned = []
for i in reversed(('3', '2', '1')): for i in reversed(('3', '2', '1')):
returned.append(i) returned.append(i)
return returned return returned
'''), ''',
expected=['1', '2', '3'], expected=['1', '2', '3'],
) )
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
returned = [] returned = []
for i in reversed([3, 2, 1]): for i in reversed([3, 2, 1]):
returned.append(i) returned.append(i)
return returned return returned
'''), ''',
expected=[1, 2, 3], expected=[1, 2, 3],
) )
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
returned = [] returned = []
for i in reversed('321'): for i in reversed('321'):
returned.append(i) returned.append(i)
return returned return returned
'''), ''',
expected=['1', '2', '3'], expected=['1', '2', '3'],
) )
def test_enumerate(self): def test_enumerate(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
returned = [] returned = []
for i in enumerate(["zero", "one", "two",]): for i in enumerate(["zero", "one", "two",]):
returned.append(i) returned.append(i)
return returned return returned
'''), ''',
expected=[(0, "zero"), (1, "one"), (2, "two"), ], expected=[(0, "zero"), (1, "one"), (2, "two"), ],
) )
# with start= argument # with start= argument
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
returned = [] returned = []
for i in enumerate(["one", "two", "three"], start=1): for i in enumerate(["one", "two", "three"], start=1):
returned.append(i) returned.append(i)
return returned return returned
'''), ''',
expected=[(1, "one"), (2, "two"), (3, "three")], expected=[(1, "one"), (2, "two"), (3, "three")],
) )
def test_generator_iteration(self): def test_generator_iteration(self):
generator_iteration_script = textwrap.dedent( generator_iteration_script = textwrap.dedent(
'''\ '''
result = [] result = []
for elem in kw['generator']: for elem in kw['generator']:
result.append(elem) result.append(elem)
...@@ -298,8 +331,7 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -298,8 +331,7 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
kwargs={'generator': generator_with_not_allowed_objects()}, kwargs={'generator': generator_with_not_allowed_objects()},
) )
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
result = [] result = []
i = iter(kw['generator']) i = iter(kw['generator'])
for _ in range(100): # prevent infinite loop for _ in range(100): # prevent infinite loop
...@@ -310,23 +342,21 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -310,23 +342,21 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
except Exception as e: except Exception as e:
result.append(repr(e)) result.append(repr(e))
return result return result
'''), ''',
kwargs={'generator': generator_with_not_allowed_objects()}, kwargs={'generator': generator_with_not_allowed_objects()},
expected=["one", "Unauthorized()", 2], expected=["one", "Unauthorized()", 2],
) )
def test_json(self): def test_json(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
import json import json
return json.loads(json.dumps({"ok": [True]})) return json.loads(json.dumps({"ok": [True]}))
'''), ''',
expected={"ok": [True]} expected={"ok": [True]}
) )
def test_calendar(self): def test_calendar(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
import calendar import calendar
calendar.IllegalMonthError calendar.IllegalMonthError
calendar.IllegalWeekdayError calendar.IllegalWeekdayError
...@@ -342,60 +372,54 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -342,60 +372,54 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
calendar.weekday(2020, 1, 1) calendar.weekday(2020, 1, 1)
calendar.Calendar().getfirstweekday() calendar.Calendar().getfirstweekday()
calendar.HTMLCalendar().getfirstweekday() calendar.HTMLCalendar().getfirstweekday()
'''), ''')
)
def test_collections_Counter(self): def test_collections_Counter(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
from collections import Counter from collections import Counter
c = Counter(["a", "b"]) c = Counter(["a", "b"])
c["a"] = c["a"] + 1 c["a"] = c["a"] + 1
del c["b"] del c["b"]
c.update({"a": 1}) c.update({"a": 1})
return c.most_common(1) return c.most_common(1)
'''), ''',
expected=[('a', 3)] expected=[('a', 3)]
) )
def test_collections_defaultdict(self): def test_collections_defaultdict(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
from collections import defaultdict from collections import defaultdict
d = defaultdict(list) d = defaultdict(list)
d["x"].append(1) d["x"].append(1)
d["y"] = 2 d["y"] = 2
del d["y"] del d["y"]
return d return d
'''), ''',
expected={"x": [1]} expected={"x": [1]}
) )
def test_collections_namedtuple(self): def test_collections_namedtuple(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
from collections import namedtuple from collections import namedtuple
Object = namedtuple("Object", ["a", "b", "c"]) Object = namedtuple("Object", ["a", "b", "c"])
return Object(a=1, b=2, c=3).a return Object(a=1, b=2, c=3).a
'''), ''',
expected=1 expected=1
) )
# also make sure we can iterate on nametuples # also make sure we can iterate on nametuples
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
from collections import namedtuple from collections import namedtuple
Object = namedtuple("Object", ["a", "b", "c"]) Object = namedtuple("Object", ["a", "b", "c"])
returned = [] returned = []
for x in Object(a=1, b=2, c=3): for x in Object(a=1, b=2, c=3):
returned.append(x) returned.append(x)
return returned return returned
'''), ''',
expected=[1, 2, 3] expected=[1, 2, 3]
) )
def test_collections_OrderedDict(self): def test_collections_OrderedDict(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
from collections import OrderedDict from collections import OrderedDict
d = OrderedDict() d = OrderedDict()
d["a"] = 1 d["a"] = 1
...@@ -403,13 +427,12 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -403,13 +427,12 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
d["c"] = 3 d["c"] = 3
del d["c"] del d["c"]
return list(d.items()) return list(d.items())
'''), ''',
expected=[("a", 1), ("b", 2)] expected=[("a", 1), ("b", 2)]
) )
def test_lax_name(self): def test_lax_name(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
def _function(): def _function():
pass pass
class SimpleObject: class SimpleObject:
...@@ -418,207 +441,199 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase): ...@@ -418,207 +441,199 @@ class TestRestrictedPythonSecurity(ERP5TypeTestCase):
def _method(self): def _method(self):
_variable = 1 _variable = 1
return SimpleObject().attribute return SimpleObject().attribute
'''), ''',
expected=1 expected=1
) )
def test_StringIO(self): def test_StringIO(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
import StringIO import StringIO
s = StringIO.StringIO() s = StringIO.StringIO()
s.write("ok") s.write("ok")
return s.getvalue() return s.getvalue()
'''), ''',
expected="ok" expected="ok"
) )
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
import StringIO import StringIO
return StringIO.StringIO("ok").getvalue() return StringIO.StringIO("ok").getvalue()
'''), ''',
expected="ok" expected="ok"
) )
def test_cStringIO(self): def test_cStringIO(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
import cStringIO import cStringIO
s = cStringIO.StringIO() s = cStringIO.StringIO()
s.write("ok") s.write("ok")
return s.getvalue() return s.getvalue()
'''), ''',
expected="ok" expected="ok"
) )
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''\
import cStringIO import cStringIO
return cStringIO.StringIO("ok").getvalue() return cStringIO.StringIO("ok").getvalue()
'''), ''',
expected="ok" expected="ok"
) )
def testNumpy(self): def testNumpy(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import numpy as np import numpy as np
return [x for x in (np.dtype('int32').name, np.timedelta64(1, 'D').nbytes)] return [x for x in (np.dtype('int32').name, np.timedelta64(1, 'D').nbytes)]
'''), ''',
expected=["int32", 8] expected=["int32", 8]
) )
def testNdarrayWrite(self): def testNdarrayWrite(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import numpy as np import numpy as np
z = np.array([[1,2],[3,4]]) z = np.array([[1,2],[3,4]])
z[0][0] = 99 z[0][0] = 99
return z[0][0] return z[0][0]
'''), ''',
expected=99 expected=99
) )
def testPandasSeries(self): def testPandasSeries(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import pandas as pd import pandas as pd
return pd.Series([1,2,3]).tolist() return pd.Series([1,2,3]).tolist()
'''), ''',
expected=[1,2,3] expected=[1,2,3]
) )
def testPandasTimestamp(self): def testPandasTimestamp(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import pandas as pd import pandas as pd
return pd.Timestamp('2020-01').year return pd.Timestamp('2020-01').year
'''), ''',
expected=2020 expected=2020
) )
def testPandasDatetimeIndex(self): def testPandasDatetimeIndex(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import pandas as pd import pandas as pd
df = pd.DataFrame({'date':['2020-01-01','2020-03-01']}) df = pd.DataFrame({'date':['2020-01-01','2020-03-01']})
df['date'] = pd.to_datetime(df['date']) df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True) df.set_index('date', inplace=True)
return str(df.index.name) return str(df.index.name)
'''), ''',
expected='date' expected='date'
) )
def testPandasMultiIndex(self): def testPandasMultiIndex(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import pandas as pd import pandas as pd
df = pd.DataFrame({'a':[1,2],'b':[3,4],'c':[5,6]}) df = pd.DataFrame({'a':[1,2],'b':[3,4],'c':[5,6]})
df2 = df.set_index(['a','b'],drop=True) df2 = df.set_index(['a','b'],drop=True)
return list(df2.index.names) return list(df2.index.names)
'''), ''',
expected=['a','b'] expected=['a','b']
) )
def testPandasIndex(self): def testPandasIndex(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import pandas as pd import pandas as pd
df = pd.DataFrame({'a':[1,2],'b':[3,4]}) df = pd.DataFrame({'a':[1,2],'b':[3,4]})
df2 = df.set_index(['a'],drop=True) df2 = df.set_index(['a'],drop=True)
return list(df2.index.names) return list(df2.index.names)
'''), ''',
expected=['a'] expected=['a']
) )
def testPandasGroupBy(self): def testPandasGroupBy(self):
# test pandas.core.groupby.DataFrameGroupBy,SeriesGroupBy # test pandas.core.groupby.DataFrameGroupBy,SeriesGroupBy
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import pandas as pd import pandas as pd
df2 = pd.DataFrame({'id':[1,1,2],'quantity':[3,4,5],'price':[6,7,8]}) df2 = pd.DataFrame({'id':[1,1,2],'quantity':[3,4,5],'price':[6,7,8]})
return list(df2.groupby(['id'])['quantity'].agg('sum')) return list(df2.groupby(['id'])['quantity'].agg('sum'))
'''), ''',
expected=[7,5] expected=[7,5]
) )
def testPandasLocIndexer(self): def testPandasLocIndexer(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import pandas as pd import pandas as pd
df = pd.DataFrame({'a':[1,2],'b':[3,4]}) df = pd.DataFrame({'a':[1,2],'b':[3,4]})
return df.loc[df['a'] == 1]['b'][0] return df.loc[df['a'] == 1]['b'][0]
'''), ''',
expected=3 expected=3
) )
def testPandasDataFrameWrite(self): def testPandasDataFrameWrite(self):
self.createAndRunScript( self.createAndRunScript('''
textwrap.dedent('''
import pandas as pd import pandas as pd
df = pd.DataFrame({'a':[1,2], 'b':[3,4]}) df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
df.iloc[0, 0] = 999 df.iloc[0, 0] = 999
return df['a'][0] return df['a'][0]
'''), ''',
expected=999 expected=999
) )
def testPandasIORead(self): def testPandasIORead(self):
self.assertRaises(Unauthorized, self.assertRaises(
Unauthorized,
self.createAndRunScript, self.createAndRunScript,
textwrap.dedent(''' '''
import pandas as pd import pandas as pd
pd.read_csv('testPandasIORead.csv') pd.read_csv('testPandasIORead.csv')
''')) ''')
# Test the black_list configuration validity # Test the black_list configuration validity
for read_method in pandas_black_list: for read_method in pandas_black_list:
self.assertRaises(Unauthorized, self.assertRaises(
Unauthorized,
self.createAndRunScript, self.createAndRunScript,
textwrap.dedent(''' '''
import pandas as pd import pandas as pd
read_method = pd.{read_method} read_method = pd.{read_method}
read_method('testPandasIORead.data') read_method('testPandasIORead.data')
'''.format(read_method=read_method))) '''.format(read_method=read_method))
def testPandasDataFrameIOWrite(self): def testPandasDataFrameIOWrite(self):
self.assertRaises(ZopeGuardsUnauthorized, self.assertRaises(
ZopeGuardsUnauthorized,
self.createAndRunScript, self.createAndRunScript,
textwrap.dedent(''' '''
import pandas as pd import pandas as pd
df = pd.DataFrame({'a':[1,2,3]}) df = pd.DataFrame({'a':[1,2,3]})
df.to_csv('testPandasDataFrameIOWrite.csv') df.to_csv('testPandasDataFrameIOWrite.csv')
''')) ''')
# Test the black_list configuration validity # Test the black_list configuration validity
for write_method in dataframe_black_list: for write_method in dataframe_black_list:
self.assertRaises(ZopeGuardsUnauthorized, self.assertRaises(
ZopeGuardsUnauthorized,
self.createAndRunScript, self.createAndRunScript,
textwrap.dedent(''' '''
import pandas as pd import pandas as pd
df = pd.DataFrame(columns=['a','b'],data=[[1,2]]) df = pd.DataFrame(columns=['a','b'],data=[[1,2]])
write_method = df.{write_method} write_method = df.{write_method}
write_method('testPandasDataFrameIOWrite.data') write_method('testPandasDataFrameIOWrite.data')
'''.format(write_method=write_method))) '''.format(write_method=write_method))
def testPandasSeriesIOWrite(self): def testPandasSeriesIOWrite(self):
self.assertRaises(ZopeGuardsUnauthorized, self.assertRaises(
ZopeGuardsUnauthorized,
self.createAndRunScript, self.createAndRunScript,
textwrap.dedent(''' '''
import pandas as pd import pandas as pd
df = pd.Series([4,5,6]) df = pd.Series([4,5,6])
df.to_csv('testPandasSeriesIOWrite.csv') df.to_csv('testPandasSeriesIOWrite.csv')
''')) ''')
# Test the black_list configuration validity # Test the black_list configuration validity
for write_method in series_black_list: for write_method in series_black_list:
self.assertRaises(ZopeGuardsUnauthorized, self.assertRaises(
ZopeGuardsUnauthorized,
self.createAndRunScript, self.createAndRunScript,
textwrap.dedent(''' '''
import pandas as pd import pandas as pd
df = pd.Series([4,5,6]) df = pd.Series([4,5,6])
write_method = df.{write_method} write_method = df.{write_method}
write_method('testPandasSeriesIOWrite.data') write_method('testPandasSeriesIOWrite.data')
'''.format(write_method=write_method))) '''.format(write_method=write_method))
def test_suite(): def test_suite():
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment