<commit_before>#!/usr/bin/python

#----------------------------------------------------------------------
# Copyright (c) 2011 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
""" Code for using Omni and unittest together"""

import copy as docopy
import datetime
from geni.util import rspec_util 
from geni.util import urn_util
from geni.util import error_util
import inspect
import sys
import unittest
import omni
import os.path
import pwd
import dateutil.parser
from omnilib.util import OmniError, naiveUTC, AMAPIError

SLICE_NAME = 'acc'
LOG_CONFIG_FILE = "logging.conf"

class BadArgsErrCode( AssertionError ):
    pass
class ErrorErrCode( AssertionError ):
    pass
class ForbiddenErrCode( AssertionError ):
    pass
class BadVersionErrCode( AssertionError ):
    pass
class ServerErrorErrCode( AssertionError ):
    pass
class TooBigErrCode( AssertionError ):
    pass
class RefusedErrCode( AssertionError ):
    pass
class TimedOutErrCode( AssertionError ):
    pass
class DBErrorErrCode( AssertionError ):
    pass
class RPCErrCode( AssertionError ):
    pass
class UnavailableErrCode( AssertionError ):
    pass
class SearchFailedErrCode( AssertionError ):
    pass
class UnsupportedErrCode( AssertionError ):
    pass
class BusyErrCode( AssertionError ):
    pass
class ExpiredErrCode( AssertionError ):
    pass
class InProgressErrCode( AssertionError ):
    pass
class AlreadyExistsErrCode( AssertionError ):
    pass
class MissingArgsErrCode( AssertionError ):
    pass
class OutOfRangeErrCode( AssertionError ):
    pass
class CredentialInvalidErrCode( AssertionError ):
    pass
class CredentialExpiredErrCode( AssertionError ):
    pass
class CredentialMismatchErrCode( AssertionError ):
    pass
class CredentialSignerUntrustedErrCode( AssertionError ):
    pass
class NotDictAssertionError( AssertionError ):
    pass
class NotListAssertionError( AssertionError ):
    pass
class NotStringAssertionError( AssertionError ):
    pass
class NotUnicodeAssertionError( AssertionError ):
    pass
class NotNoneAssertionError( AssertionError ):
    pass
class NoResourcesAssertionError( AssertionError ):
    pass
class NotXMLAssertionError( AssertionError ):
    pass
class NotEqualComponentIDsError( AssertionError ):
    pass
class NotEqualClientIDsError( AssertionError ):
    pass
class WrongRspecType( AssertionError ):
    pass
class NotSuccessError( AssertionError ):
    pass

class OmniUnittest(unittest.TestCase):
    """Methods for using unittest module with Omni. """
    def __init__(self, method_name='runTest'):
        super(OmniUnittest, self).__init__(method_name)
        # Add this script's args
        #        self.options, self.args = (TEST_OPTS, TEST_ARGS)
#        self.options = None
#        self.args = ()

    def section_break( self ):
        """Text to separate individual tests"""
        testname = inspect.stack()[1][3]
        pre_name = "NEW TEST: %s" % testname
        print pre_name


    def print_monitoring( self, result ):
        """prints a line of text like:
              MONITORING test_getversion 1"""

        if result is True:
            result_str = 1
        else:
            result_str = 0

        # inspect.stack()[0][3] returns the name of the method being called
        # inspect.stack()[1][3] returns the name of the parent of the
        #    method being called
        print "MONITORING %s %s" % (inspect.stack()[1][3], result_str)      

    def create_slice_name( self, prefix=SLICE_NAME ):
        """slice name to be used to create a test slice"""
        if self.options.reuse_slice_name:
            return self.options.reuse_slice_name
        else:
            user = pwd.getpwuid(os.getuid())[0]
            pre = prefix+user[:3]
            return datetime.datetime.strftime(datetime.datetime.utcnow(), pre+"-%H%M%S")
#            return prefix+pwd.getpwuid(os.getuid())[0]

    def create_slice_name_uniq( self, prefix=SLICE_NAME ):
        """Unique slice name to be used to create a test slice"""
        if self.options.reuse_slice_name:
            return self.options.reuse_slice_name
        else:
#            return prefix+os.getlogin()
            return datetime.datetime.strftime(datetime.datetime.utcnow(),
                                                    prefix+"-%H%M%S")

    def setUp( self ):
        self.options_copy = docopy.deepcopy(self.options)
        self.options_copy.raiseErrorOnV2AMAPIError = True

    def call( self, cmd, options ):
        """Make the Omni call"""
        ret_val = omni.call( cmd, options=options, verbose=True )
        return ret_val



    def assertIsNotNone(self, item, msg=None):
        if msg is None:
            msg = "Item is None."
        if item is None:
            raise NotNoneAssertionError, msg

    def assertDict(self, item, msg=None):
        if msg is None:
            msg = "Type of '%s' is '%s' not 'dict' as expected." % (item, type(item))
        if not type(item) == dict:
            raise NotDictAssertionError, msg

    def assertList(self, item, msg=None):
        if msg is None:
            msg = "Type of '%s' is '%s' not 'list' as expected." % (item, type(item))<commit_msg>When omni.call raises an error, print it before raising the error to the caller<commit_after>#!/usr/bin/python

#----------------------------------------------------------------------
# Copyright (c) 2011 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Work, and to permit persons to whom the Work
# is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Work.
#
# THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
# IN THE WORK.
#----------------------------------------------------------------------
""" Code for using Omni and unittest together"""

import copy as docopy
import datetime
from geni.util import rspec_util 
from geni.util import urn_util
from geni.util import error_util
import inspect
import sys
import unittest
import omni
import os.path
import pwd
import dateutil.parser
from omnilib.util import OmniError, naiveUTC, AMAPIError

SLICE_NAME = 'acc'
LOG_CONFIG_FILE = "logging.conf"

class BadArgsErrCode( AssertionError ):
    pass
class ErrorErrCode( AssertionError ):
    pass
class ForbiddenErrCode( AssertionError ):
    pass
class BadVersionErrCode( AssertionError ):
    pass
class ServerErrorErrCode( AssertionError ):
    pass
class TooBigErrCode( AssertionError ):
    pass
class RefusedErrCode( AssertionError ):
    pass
class TimedOutErrCode( AssertionError ):
    pass
class DBErrorErrCode( AssertionError ):
    pass
class RPCErrCode( AssertionError ):
    pass
class UnavailableErrCode( AssertionError ):
    pass
class SearchFailedErrCode( AssertionError ):
    pass
class UnsupportedErrCode( AssertionError ):
    pass
class BusyErrCode( AssertionError ):
    pass
class ExpiredErrCode( AssertionError ):
    pass
class InProgressErrCode( AssertionError ):
    pass
class AlreadyExistsErrCode( AssertionError ):
    pass
class MissingArgsErrCode( AssertionError ):
    pass
class OutOfRangeErrCode( AssertionError ):
    pass
class CredentialInvalidErrCode( AssertionError ):
    pass
class CredentialExpiredErrCode( AssertionError ):
    pass
class CredentialMismatchErrCode( AssertionError ):
    pass
class CredentialSignerUntrustedErrCode( AssertionError ):
    pass
class NotDictAssertionError( AssertionError ):
    pass
class NotListAssertionError( AssertionError ):
    pass
class NotStringAssertionError( AssertionError ):
    pass
class NotUnicodeAssertionError( AssertionError ):
    pass
class NotNoneAssertionError( AssertionError ):
    pass
class NoResourcesAssertionError( AssertionError ):
    pass
class NotXMLAssertionError( AssertionError ):
    pass
class NotEqualComponentIDsError( AssertionError ):
    pass
class NotEqualClientIDsError( AssertionError ):
    pass
class WrongRspecType( AssertionError ):
    pass
class NotSuccessError( AssertionError ):
    pass

class OmniUnittest(unittest.TestCase):
    """Methods for using unittest module with Omni. """
    def __init__(self, method_name='runTest'):
        super(OmniUnittest, self).__init__(method_name)
        # Add this script's args
        #        self.options, self.args = (TEST_OPTS, TEST_ARGS)
#        self.options = None
#        self.args = ()

    def section_break( self ):
        """Text to separate individual tests"""
        testname = inspect.stack()[1][3]
        pre_name = "NEW TEST: %s" % testname
        print pre_name


    def print_monitoring( self, result ):
        """prints a line of text like:
              MONITORING test_getversion 1"""

        if result is True:
            result_str = 1
        else:
            result_str = 0

        # inspect.stack()[0][3] returns the name of the method being called
        # inspect.stack()[1][3] returns the name of the parent of the
        #    method being called
        print "MONITORING %s %s" % (inspect.stack()[1][3], result_str)      

    def create_slice_name( self, prefix=SLICE_NAME ):
        """slice name to be used to create a test slice"""
        if self.options.reuse_slice_name:
            return self.options.reuse_slice_name
        else:
            user = pwd.getpwuid(os.getuid())[0]
            pre = prefix+user[:3]
            return datetime.datetime.strftime(datetime.datetime.utcnow(), pre+"-%H%M%S")
#            return prefix+pwd.getpwuid(os.getuid())[0]

    def create_slice_name_uniq( self, prefix=SLICE_NAME ):
        """Unique slice name to be used to create a test slice"""
        if self.options.reuse_slice_name:
            return self.options.reuse_slice_name
        else:
#            return prefix+os.getlogin()
            return datetime.datetime.strftime(datetime.datetime.utcnow(),
                                                    prefix+"-%H%M%S")

    def setUp( self ):
        self.options_copy = docopy.deepcopy(self.options)
        self.options_copy.raiseErrorOnV2AMAPIError = True

    def call( self, cmd, options ):
        """Make the Omni call"""
        try:
            ret_val = omni.call( cmd, options=options, verbose=True )
        except Exception, e:
            print "Omni raised an error: %r" % e
            raise
        return ret_val

    def assertIsNotNone(self, item, msg=None):
        if msg is None:
            msg = "Item is None."
        if item is None:
            raise NotNoneAssertionError, msg

    def assertDict(self, item, msg=None):
        if msg is None:
            msg = "Type of '%s' is '%s' not 'dict' as expected." % (item, type(item))
        if not type(item) == dict:
            raise NotDictAssertionError, msg

    def assertList(self, item, msg=None):
        if msg is None:
            msg = "Type of '%s' is '%s' not 'list' as expected." % (item, type(item))
{'fraction_non_alphanumeric': 0.10199380411470331, 'fraction_numerical': 0.003018508221463182, 'mean_word_length': 2.869084204056546, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1835959', 'n_tokens_mistral': 3539, 'n_tokens_neox': 3432, 'n_words': 1192}