prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib")<|fim▁hole|> def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default)<|fim▁end|>
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): <|fim_middle|> @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
""" Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): <|fim_middle|> def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): <|fim_middle|> def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): <|fim_middle|> class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
""" Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret))
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): <|fim_middle|> test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): <|fim_middle|> def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
self.expected_exception = expected_exception
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): <|fim_middle|> def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
return
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): <|fim_middle|> test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): <|fim_middle|> def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
""" Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): <|fim_middle|> <|fim▁end|>
""" Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): <|fim_middle|> else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): <|fim_middle|> else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: <|fim_middle|> def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): <|fim_middle|> def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: <|fim_middle|> else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
return RaisesContext(expected_exception)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: <|fim_middle|> class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret))
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: <|fim_middle|> class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
raise AssertionError("No exception raised. Return value: {}".format(ret))
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: <|fim_middle|> else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
raise AssertionError("No exception raised.")
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: <|fim_middle|> return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
_check_exception(self.expected_exception, exc_val, exc_tb)
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def <|fim_middle|>(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
treader
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def <|fim_middle|>(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
tmpdir
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def <|fim_middle|>(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
_check_exception
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def <|fim_middle|>(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
raises
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def <|fim_middle|>(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
__init__
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def <|fim_middle|>(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
__enter__
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def <|fim_middle|>(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
__exit__
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def <|fim_middle|>(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
treq
<|file_name|>tutils.py<|end_file_name|><|fim▁begin|>from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def <|fim_middle|>(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default) <|fim▁end|>
tresp
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label'<|fim▁hole|> 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main()<|fim▁end|>
],
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): <|fim_middle|> def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): <|fim_middle|> def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): <|fim_middle|> def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt)
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): <|fim_middle|> def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): <|fim_middle|> @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
counts = verify(opt) print(counts) return counts
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): <|fim_middle|> if __name__ == '__main__': VerifyData.main() <|fim▁end|>
@classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt)
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): <|fim_middle|> def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
return setup_args()
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): <|fim_middle|> if __name__ == '__main__': VerifyData.main() <|fim▁end|>
return verify_data(self.opt)
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: <|fim_middle|> # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
parser = ParlaiParser(True, True, 'Check tasks for common errors')
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): <|fim_middle|> else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
print(txt + ":\n" + str(act))
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: <|fim_middle|> def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
warn_once(txt)
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': <|fim_middle|> opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered'
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: <|fim_middle|> log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
log_every_n_secs = float('inf')
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): <|fim_middle|> if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
counts['did_not_return_message'] += 1
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: <|fim_middle|> if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: <|fim_middle|> else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: <|fim_middle|> if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: <|fim_middle|> else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
counts['missing_label_candidates'] += 1
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: <|fim_middle|> if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': <|fim_middle|> if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: <|fim_middle|> for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: <|fim_middle|> is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, )
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: <|fim_middle|> if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: <|fim_middle|> try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
text, log = report(world, counts, log_time) print(text)
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
VerifyData.main()
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def <|fim_middle|>(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
setup_args
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def <|fim_middle|>(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
report
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def <|fim_middle|>(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
warn
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def <|fim_middle|>(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
verify
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def <|fim_middle|>(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
verify_data
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def <|fim_middle|>(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
setup_args
<|file_name|>verify_data.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """ from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + ":\n" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning("changing datatype from train to train:ordered") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn("warning: missing text field:\n", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn("warning: missing labels/eval_labels field:\n", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn("warning: empty string label_candidate:\n", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( "warning: label mentioned twice in candidate_labels:\n", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn("warning: label missing in candidate_labels:\n", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def <|fim_middle|>(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() <|fim▁end|>
run
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>""" Django settings for sparta project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')mg$xo^v*2mmwidr0ak6%9&!@e18v8t#7@+vd+wqg8kydb48k7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'sparta.urls' <|fim▁hole|># https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER':'root', 'NAME':'fordjango', 'PASSWORD':'123456', 'HOST':'localhost', 'PORT':'' } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) STATIC_ROOT = os.path.join('/home/dexter/weaponx/Django/sparta/sparta/static') STATIC_URL = '/assets/' STATICFILES_DIRS = ( '/home/dexter/weaponx/Django/sparta/sparta/assets', ) TEMPLATE_DIRS=('/home/dexter/weaponx/Django/sparta/sparta/template',)<|fim▁end|>
WSGI_APPLICATION = 'sparta.wsgi.application' # Database
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|>import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00'))<|fim▁hole|> def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main()<|fim▁end|>
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): <|fim_middle|> if __name__ == '__main__': unittest.main() <|fim▁end|>
def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str)
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): <|fim_middle|> def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str']
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): <|fim_middle|> def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00'))
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal <|fim_middle|> def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13'))
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): <|fim_middle|> def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.assertEqual(self.header_arquivo.controle_banco, 341)
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) <|fim_middle|> def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5)
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): <|fim_middle|> @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME')
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects <|fim_middle|> def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy')
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): <|fim_middle|> def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA')
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): <|fim_middle|> def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario())
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): <|fim_middle|> if __name__ == '__main__': unittest.main() <|fim▁end|>
def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str)
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): <|fim_middle|> unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str)
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
unittest.main()
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def <|fim_middle|>(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
setUp
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def <|fim_middle|>(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_leitura_campo_num_decimal
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def <|fim_middle|>(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_escrita_campo_num_decimal
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def <|fim_middle|>(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_leitura_campo_num_int
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def <|fim_middle|>(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_escrita_campo_num_int
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def <|fim_middle|>(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_leitura_campo_alfa
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def <|fim_middle|>(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_escrita_campo_alfa
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def <|fim_middle|>(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_fromdict
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def <|fim_middle|>(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_necessario
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def <|fim_middle|>(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
test_unicode
<|file_name|>test_registro.py<|end_file_name|><|fim▁begin|> import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def <|fim_middle|>(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main() <|fim▁end|>
unicode_test
<|file_name|>config.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Configuration options for Invenio-Search. The documentation for the configuration is in docs/configuration.rst. """ # # ELASTIC configuration # SEARCH_CLIENT_CONFIG = None """Dictionary of options for the Elasticsearch client. The value of this variable is passed to :py:class:`elasticsearch.Elasticsearch` as keyword arguments and is used to configure the client. See the available keyword arguments in the two following classes: - :py:class:`elasticsearch.Elasticsearch` - :py:class:`elasticsearch.Transport` If you specify the key ``hosts`` in this dictionary, the configuration variable :py:class:`~invenio_search.config.SEARCH_ELASTIC_HOSTS` will have no effect. """ SEARCH_ELASTIC_HOSTS = None # default localhost<|fim▁hole|>"""Elasticsearch hosts. By default, Invenio connects to ``localhost:9200``. The value of this variable is a list of dictionaries, where each dictionary represents a host. The available keys in each dictionary is determined by the connection class: - :py:class:`elasticsearch.connection.Urllib3HttpConnection` (default) - :py:class:`elasticsearch.connection.RequestsHttpConnection` You can change the connection class via the :py:class:`~invenio_search.config.SEARCH_CLIENT_CONFIG`. If you specified the ``hosts`` key in :py:class:`~invenio_search.config.SEARCH_CLIENT_CONFIG` then this configuration variable will have no effect. """ SEARCH_MAPPINGS = None # loads all mappings and creates aliases for them """List of aliases for which, their search mappings should be created. - If `None` all aliases (and their search mappings) defined through the ``invenio_search.mappings`` entry point in setup.py will be created. - Provide an empty list ``[]`` if no aliases (or their search mappings) should be created. For example if you don't want to create aliases and their mappings for `authors`: .. code-block:: python # in your `setup.py` you would specify: entry_points={ 'invenio_search.mappings': [ 'records = invenio_foo_bar.mappings', 'authors = invenio_foo_bar.mappings', ], } # and in your config.py SEARCH_MAPPINGS = ['records'] """ SEARCH_RESULTS_MIN_SCORE = None """If set, the `min_score` parameter is added to each search request body. The `min_score` parameter excludes results which have a `_score` less than the minimum specified in `min_score`. Note that the `max_score` varies depending on the number of results for a given search query and it is not absolute value. Therefore, setting `min_score` too high can lead to 0 results because it can be higher than any result's `_score`. Please refer to `Elasticsearch min_score documentation <https://www.elastic.co/guide/en/elasticsearch/reference/current/ search-request-min-score.html>`_ for more information. """ SEARCH_INDEX_PREFIX = '' """Any index, alias and templates will be prefixed with this string. Useful to host multiple instances of the app on the same Elasticsearch cluster, for example on one app you can set it to `dev-` and on the other to `prod-`, and each will create non-colliding indices prefixed with the corresponding string. Usage example: .. code-block:: python # in your config.py SEARCH_INDEX_PREFIX = 'prod-' For templates, ensure that the prefix `__SEARCH_INDEX_PREFIX__` is added to your index names. This pattern will be replaced by the prefix config value. Usage example in your template.json: .. code-block:: json { "index_patterns": ["__SEARCH_INDEX_PREFIX__myindex-name-*"] } """<|fim▁end|>
<|file_name|>db_migrate.py<|end_file_name|><|fim▁begin|>#!hyphen-venv/bin/python import imp from migrate.versioning import api from app import db from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO migration = SQLALCHEMY_MIGRATE_REPO + \ '/versions/%03d_migration.py' % \ (api.db_version( SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) + 1) tmp_module = imp.new_module('old_model') old_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) exec old_model in tmp_module.__dict__ script = api.make_update_script_for_model( SQLALCHEMY_DATABASE_URI,<|fim▁hole|> tmp_module.meta, db.metadata) open(migration, "wt").write(script) api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) print 'New migration saved as ' + migration print 'Current database version: ' + \ str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))<|fim▁end|>
SQLALCHEMY_MIGRATE_REPO,
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when']<|fim▁hole|> sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): <|fim_middle|> def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() <|fim▁end|>
parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string <|fim_middle|> def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() <|fim▁end|>
lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace')
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages <|fim_middle|> # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() <|fim▁end|>
discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): <|fim_middle|> def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() <|fim▁end|>
if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,))
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock()
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: <|fim_middle|> return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() <|fim▁end|>
parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1)
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: <|fim_middle|> key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() <|fim▁end|>
pending.append(_('Pending subscriptions:')) first = False
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: <|fim_middle|> pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() <|fim▁end|>
if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname
<|file_name|>checkdbs.py<|end_file_name|><|fim▁begin|># Copyright (C) 1998-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # GNU Mailman is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # GNU Mailman. If not, see <http://www.gnu.org/licenses/>. import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_("""\ %prog [options] Check for pending admin requests and mail the list owners if necessary.""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): <|fim_middle|> fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_("""\ From: $sender on $date Subject: $subject Cause: $reason""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() <|fim▁end|>
fullname = fullname.encode(lcset, 'replace')