def test_two_piksies_btldr_mode(self):
   """
   Test if two Piksies can set eachother into bootloader mode (should fail).
   """
   unittest.skipIf(self.skip_double, 'Skipping double Piksi tests')
   if self.port2 is None:
     return
  def test_jump_to_app(self):
    """ Test that we can jump to the application after programming. """
    unittest.skipIf(self.skip_single, 'Skipping single Piksi tests')

    if self.verbose: print "--- test_jump_to_app ---"

    with serial_link.get_driver(use_ftdi=False, port=self.port1) as driver:
      with Handler(driver.read, driver.write) as handler:

        with Bootloader(handler) as piksi_bootloader:
          if self.verbose: print "Handshaking with bootloader"
          piksi_bootloader.handshake()
          if self.verbose: print "Jumping to application"
          piksi_bootloader.jump_to_app()

        # If we succesfully jump to the application, we should receive
        # Heartbeat messages.
        with Timeout(TIMEOUT_BOOT) as timeout:

          heartbeat = Heartbeat()
          handler.add_callback(heartbeat, SBP_MSG_HEARTBEAT)

          if self.verbose: print "Waiting to receive heartbeat"
          while not heartbeat.received:
            time.sleep(0.1)
          if self.verbose: print "Received hearbeat"

          handler.remove_callback(heartbeat, SBP_MSG_HEARTBEAT)
  def test_flashing_wrong_sender_id(self):
    """ Test flashing using an incorrect sender ID (should fail). """
    unittest.skipIf(self.skip_single, 'Skipping single Piksi tests')

    SECTOR = 1
    SENDER_ID = 0x41

    if self.verbose: print "--- test_flashing_wrong_sender_id ---"

    with serial_link.get_driver(use_ftdi=False, port=self.port1) as driver:
      with Handler(driver.read, driver.write) as handler:

        # Verify that flash erase times out when using incorrect sender ID.
        with Bootloader(handler) as piksi_bootloader:
          with Timeout(TIMEOUT_BOOT) as timeout:
            print "Handshaking with bootloader"
            piksi_bootloader.handshake()
          with Flash(handler, flash_type='STM',
                     sbp_version=piksi_bootloader.sbp_version) as piksi_flash:
            try:
              with Timeout(TIMEOUT_ERASE_SECTOR) as timeout:
                if self.verbose: print "Attempting to erase sector with incorrect sender ID"
                msg_buf = struct.pack("BB", piksi_flash.flash_type_byte, SECTOR)
                handler.send(SBP_MSG_FLASH_ERASE, msg_buf, sender=SENDER_ID)
                handler.wait(SBP_MSG_FLASH_DONE, TIMEOUT_ERASE_SECTOR+1)
                raise Exception("Should have timed out but didn't")
            except TimeoutError:
              if self.verbose: print "Timed out as expected"
  def test_erase_btldr(self):
    """ Test erasing the bootloader once its sector is locked. """
    unittest.skipIf(self.skip_single, 'Skipping single Piksi tests')

    SECTOR = 0

    if self.verbose: print "--- test_erase_btldr ---"

    with serial_link.get_driver(use_ftdi=False, port=self.port1) as driver:
      with Handler(driver.read, driver.write) as handler:

        with Bootloader(handler) as piksi_bootloader:
          with Timeout(TIMEOUT_BOOT) as timeout:
            if self.verbose: print "Waiting for bootloader handshake"
            piksi_bootloader.handshake()
          with Flash(handler, flash_type='STM',
                     sbp_version=piksi_bootloader.sbp_version) as piksi_flash:
            # Make sure the bootloader sector is locked.
            with Timeout(TIMEOUT_LOCK_SECTOR) as timeout:
              if self.verbose: print "Locking STM sector:", SECTOR
              piksi_flash.lock_sector(SECTOR)
            # Attempt to erase the sector.
            with Timeout(TIMEOUT_ERASE_SECTOR) as timeout:
              if self.verbose: print "Attempting to erase STM sector:", SECTOR
              piksi_flash.erase_sector(SECTOR, warn=False)
            # If the sector was successfully erased, we should timeout here
            # as the bootloader will stop sending handshakes.
            with Timeout(TIMEOUT_BOOT) as timeout:
              if self.verbose: print "Waiting for bootloader handshake"
              piksi_bootloader.handshake()
  def test_program_btldr(self):
    """ Test programming the bootloader once its sector is locked. """
    unittest.skipIf(self.skip_single, 'Skipping single Piksi tests')

    SECTOR = 0
    ADDRESS = 0x08003FFF

    if self.verbose: print "--- test_program_btldr ---"

    with serial_link.get_driver(use_ftdi=False, port=self.port1) as driver:
      with Handler(driver.read, driver.write) as handler:

        with Bootloader(handler) as piksi_bootloader:
          with Timeout(TIMEOUT_BOOT) as timeout:
            if self.verbose: print "Waiting for bootloader handshake"
            piksi_bootloader.handshake()
          with Flash(handler, flash_type='STM',
                     sbp_version=piksi_bootloader.sbp_version) as piksi_flash:
            # Make sure the bootloader sector is locked.
            with Timeout(TIMEOUT_LOCK_SECTOR) as timeout:
              if self.verbose: print "Locking STM sector:", SECTOR
              piksi_flash.lock_sector(SECTOR)
            # Make sure the address to test isn't already programmed.
            with Timeout(TIMEOUT_READ_STM) as timeout:
              byte_read = piksi_flash.read(ADDRESS, 1, block=True)
            self.assertEqual('\xFF', byte_read,
                             "Address to program is already programmed")
            # Attempt to write 0x00 to last address of the sector.
            if self.verbose: print "Attempting to lock STM sector:", SECTOR
            piksi_flash.program(0x08003FFF, '\x00')
            with Timeout(TIMEOUT_READ_STM) as timeout:
              byte_read = piksi_flash.read(0x08003FFF, 1, block=True)
            self.assertEqual('\xFF', byte_read,
                             "Bootloader sector was programmed")
  def test_flash_stm_firmware(self):
    """ Test flashing STM hexfile. """
    unittest.skipIf(self.skip_single, 'Skipping single Piksi tests')

    if self.verbose: print "--- test_flash_stm_firmware ---"

    with serial_link.get_driver(use_ftdi=False, port=self.port1) as driver:
      with Handler(driver.read, driver.write) as handler:

        # Wait until we receive a heartbeat or bootloader handshake so we
        # know what state Piksi is in.
        with Bootloader(handler) as piksi_bootloader:

          with Timeout(TIMEOUT_BOOT) as timeout:
            if self.verbose: print "Waiting for bootloader handshake"
            piksi_bootloader.handshake()
            if self.verbose: print "Received bootloader handshake"

          with Flash(handler, flash_type="STM",
                     sbp_version=piksi_bootloader.sbp_version) as piksi_flash:
            # Erase entire STM flash (except bootloader).
            if self.verbose: print "Erasing STM"
            with Timeout(TIMEOUT_ERASE_STM) as timeout:
              for s in range(1,12):
                piksi_flash.erase_sector(s)
            # Write STM firmware.
            with Timeout(TIMEOUT_PROGRAM_STM) as timeout:
              if self.verbose:
                if self.verbose: print "Programming STM"
                piksi_flash.write_ihx(self.stm_fw, sys.stdout, 0x10, erase=False)
              else:
                piksi_flash.write_ihx(self.stm_fw, erase=False)
  def test_get_versions(self):
    """ Get Piksi bootloader/firmware/NAP version from device. """
    unittest.skipIf(self.skip_single, 'Skipping single Piksi tests')

    if self.verbose: print "--- test_get_versions ---"

    with serial_link.get_driver(use_ftdi=False, port=self.port1) as driver:
      with Handler(driver.read, driver.write) as handler:

        with Bootloader(handler) as piksi_bootloader:

          # Get bootloader version, print, and jump to application firmware.
          with Timeout(TIMEOUT_BOOT) as timeout:
            if self.verbose: print "Waiting for bootloader handshake"
            piksi_bootloader.handshake()
          piksi_bootloader.jump_to_app()
          print "Piksi Bootloader Version:", piksi_bootloader.version

        # Wait for heartbeat, get settings, print firmware/NAP versions.
        heartbeat = Heartbeat()
        handler.add_callback(heartbeat, SBP_MSG_HEARTBEAT)
        if self.verbose: print "Waiting to receive heartbeat"
        while not heartbeat.received:
          time.sleep(0.1)
        if self.verbose: print "Received hearbeat"
        handler.remove_callback(heartbeat, SBP_MSG_HEARTBEAT)

        if self.verbose: print "Getting Piksi settings"
        settings = self.get_piksi_settings(handler)

        if self.verbose: print "Piksi Firmware Version:", \
                          settings['system_info']['firmware_version']

        if self.verbose: print "Piksi NAP Version:", \
                          settings['system_info']['nap_version']
	def test_likes(self):
		for i in range(10):
			x = map(str, list(range(i)))

			shuffle(x)

			self.assertEqual(aula2.likes(x), gabarito_aula2.likes(x)

	@unittest.skipIf('remove_duplicates' not in vars(aula2),
					 'Função "remove_duplicates" não foi encontrada')
	def test_remove_duplicates(self):
		for _ in range(40):
			t = [randint(0,5) for _ in range(randint(0, 30))]

			self.assertEqual(aula2.remove_duplicates(t), remove_duplicates(t))

	@unittest.skipIf('different_evenness' not in vars(aula2),
					 'Função "different_evenness" não foi encontrada')
	def test_different_evenness(self):
		for _ in range(40):
		    testlen=randint(3,50)
		    oddeven=randint(0,1)
		    testmat=[randint(0,25)*2+oddeven for x in range(testlen)]
		    solution=randint(1,testlen)
		    testmat[solution-1]+=1
		    testmat=(" ").join(map(str,testmat))
		    self.assertEqual(different_evenness(testmat), solution)

if __name__ == '__main__':
	unittest.main(verbosity=2)
    def test_insertion_success(self):
        params = {}
        params['server'] = 'mobiledata.bigdatacorp.com.br'
        params['port'] = '21766'
        params['database'] = 'MobileAppsData'
        params['username'] = '******'
        params['password'] = '******'
        params['seed_collection'] = 'Python_test'
        params['auth_database'] = 'MobileAppsData'
        params['write_concern'] = True

        mongo_uri = MongoDBWrapper.build_mongo_uri(**params)

        mongo_wrapper = MongoDBWrapper()

        is_connected = mongo_wrapper.connect(mongo_uri, params['database'],
                                             params['seed_collection'])

        unittest.skipIf(is_connected is False,
                     'Connection failed, insertion cancelled.')

        if is_connected:
            mongo_wrapper.insert_on_queue(self._test_app_url)

            # Find it on Mongo
            query = {'_id': self._test_app_url}
            self.assertTrue(mongo_wrapper._collection.find_one(query),
                            'Insert did not work.')

        else:
            self.fail('Connection problem, verify connection before insert.')
def skip_unless_any_pythons_present(*versions):
  """A decorator that only runs the decorated test method if any of the specified pythons are present.

  :param string *versions: Python version strings, such as 2.7, 3.
  """
  if any(v for v in versions if has_python_version(v)):
    return skipIf(False, 'At least one of the expected python versions found.')
  return skipIf(True, 'Could not find at least one of the required pythons from {} on the system. Skipping.'.format(versions))
示例#11
0
 def test_uart_rx_buffer_overflow(self):
   """
   Test if queuing too many operations causes a UART RX buffer overflow when
   another Piksi is sending data via another UART (should fail).
   """
   unittest.skipIf(self.skip_double, 'Skipping double Piksi tests')
   if self.port2 is None:
     return
def skip_unless_all_pythons_present(*versions):
  """A decorator that only runs the decorated test method if all of the specified pythons are present.

  :param string *versions: Python version strings, such as 2.7, 3.
  """
  missing_versions = [v for v in versions if not has_python_version(v)]
  if len(missing_versions) == 1:
    return skipIf(True, 'Could not find python {} on system. Skipping.'.format(missing_versions[0]))
  elif len(missing_versions) > 1:
    return skipIf(True,
                  'Skipping due to the following missing required pythons: {}'
                  .format(', '.join(missing_versions)))
  else:
    return skipIf(False, 'All required pythons present, continuing with test!')
示例#13
0
文件: testing.py 项目: bgyarfas/bokeh
def skipIfPy3(message):
    ''' unittest decorator to skip a test for Python 3

    '''
    from unittest import skipIf
    from .platform import is_py3
    return skipIf(is_py3(), message)
示例#14
0
    def _add_test_methods(mcs, attrs, urlpatterns):
        # loop through every URL pattern
        for index, (func, regex, url_name) in enumerate(extract_views_from_urlpatterns(urlpatterns)):

            if func.__module__.startswith("%s." % attrs["module"]):
                pass
            elif func.__module__ == attrs["module"]:
                pass
            else:
                continue

            if hasattr(func, "__name__"):
                func_name = func.__name__
            elif hasattr(func, "__class__"):
                func_name = "%s()" % func.__class__.__name__
            else:
                func_name = re.sub(r" at 0x[0-9a-f]+", "", repr(func))

            url_pattern = smart_text(simplify_regex(regex))
            name = "_".join(
                ["test", func.__module__.replace(".", "_"), slugify("%s" % func_name)]
                + slugify(url_pattern.replace("/", "_") or "root").replace("_", " ").split()
            )
            url = url_pattern

            for key, value in attrs["variables"].items():
                url = url.replace("<%s>" % key, value)

            # bail out if we don't know how to visit this URL properly
            testfunc = unittest.skipIf(
                any(re.search(stop_pattern, url) for stop_pattern in [r"<.*>"]),
                "URL pattern %r contains stop pattern." % url,
            )(make_test_get_function(name, url, url_pattern))

            attrs[name] = testfunc
示例#15
0
 def skip_from_python_(cls):
     decorator = unittest.skipIf(
         sys.version_info[:len(ver)] >= ver,
         "skipped because Python %s"
         % ".".join(map(str, sys.version_info[:len(ver)])),
     )
     return decorator(cls)
示例#16
0
def skip_if_windows(cls):
    """Skip a test if run on windows"""
    decorator = unittest.skipIf(
        platform.system() == 'Windows',
        "Not supported on Windows",
    )
    return decorator(cls)
示例#17
0
 def skip_after_libpq_(cls):
     v = libpq_version()
     decorator = unittest.skipIf(
         v >= int("%d%02d%02d" % ver),
         "skipped because libpq %s" % v,
     )
     return decorator(cls)
示例#18
0
文件: testing.py 项目: Wombatpm/bokeh
def skipIfPyPy(message):
    """ unittest decoractor to skip a test for PyPy

    """
    from unittest import skipIf
    from .platform import is_pypy
    return skipIf(is_pypy(), message)
示例#19
0
 def skip_before_libpq_(cls):
     v = libpq_version()
     decorator = unittest.skipIf(
         v < int("%d%02d%02d" % ver),
         "skipped because libpq %d" % v,
     )
     return decorator(cls)
示例#20
0
文件: helper.py 项目: bittnt/chainer
def with_requires(*requirements):
    """Run a test case only when given requirements are satisfied.

    .. admonition:: Example

       This test case runs only when `numpy>=1.10` is installed.

       >>> from cupy import testing
       ... class Test(unittest.TestCase):
       ...     @testing.with_requires('numpy>=1.10')
       ...     def test_for_numpy_1_10(self):
       ...         pass

    Args:
        requirements: A list of string representing requirement condition to
            run a given test case.

    """
    ws = pkg_resources.WorkingSet()
    try:
        ws.require(*requirements)
        skip = False
    except pkg_resources.VersionConflict:
        skip = True

    msg = 'requires: {}'.format(','.join(requirements))
    return unittest.skipIf(skip, msg)
示例#21
0
文件: testing.py 项目: bgyarfas/bokeh
def skipIfPyPy(message):
    ''' unittest decorator to skip a test for PyPy

    '''
    from unittest import skipIf
    from .platform import is_pypy
    return skipIf(is_pypy(), message)
示例#22
0
    def _add_test_methods(mcs, attrs, urlpatterns):
        # loop through every URL pattern
        for index, (func, regex, url_name) in enumerate(
                extract_views_from_urlpatterns(urlpatterns)):

            if 'module_exclude' not in attrs:
                attrs['module_exclude'] = None

            if attrs['module_exclude'] is not None:
                if func.__module__.startswith("%s." % attrs['module_exclude']):
                    continue
                elif func.__module__ == attrs['module_exclude']:
                    continue
                else:
                    pass

            if func.__module__.startswith("%s." % attrs['module']):
                pass
            elif func.__module__ == attrs['module']:
                pass
            else:
                continue

            if hasattr(func, '__name__'):
                func_name = func.__name__
            elif hasattr(func, '__class__'):
                func_name = '%s()' % func.__class__.__name__
            else:
                func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func))

            url_pattern = smart_text(simplify_regex(regex))
            name = '_'.join(
                [
                    'test',
                    func.__module__.replace('.', '_'),
                    slugify('%s' % func_name),
                ] + slugify(
                    url_pattern.replace('/', '_') or 'root'
                ).replace('_', ' ').split(),
            )
            url = url_pattern

            for key, value in attrs['variables'].items():
                url = url.replace('<%s>' % key, value)

            # bail out if we don't know how to visit this URL properly
            testfunc = unittest.skipIf(
                any(
                    re.search(stop_pattern, url)
                    for stop_pattern
                    in [
                        r'<.*>',
                    ]
                ),
                'URL pattern %r contains stop pattern.' % url,
            )(
                make_test_get_function(name, url, url_pattern),
            )

            attrs[name] = testfunc
示例#23
0
def sql_test(f):
    try:
        import psycopg2

        return unittest.skipIf(not sql_version, "Database is not running.")(f)
    except:
        return unittest.skip("Psycopg2 is required for sql tests.")(f)
示例#24
0
def broken_on_windows(function):
    """Decorator to skip temporarily a broken test on Windows."""
    reason = 'Test is broken and ignored on windows but should be fixed.'
    return unittest.skipIf(
        sys.platform == 'win32'
        and os.environ.get('SKIP_BROKEN_TESTS_ON_WINDOWS', 'true') == 'true',
        reason)(function)
示例#25
0
def test_type(name):
    """ Function creating decorators that allows skipping tests of declared type.

    :param str name: arbitrary name of test type e.g. acceptance,unit
    """
    should_ignore = name in os.environ.get("IGNORE_TESTS", "")
    return unittest.skipIf(should_ignore, "%s test skipped" % name)
示例#26
0
def when_s3_available(function):
    access_keys_defined = getattr(when_s3_available, 'access_keys_defined', None)
    if access_keys_defined is None:
        aws_access_key_id = os.getenv('AWS_ACCESS_KEY_ID')
        aws_secret_access_key = os.getenv('AWS_SECRET_ACCESS_KEY')
        access_keys_defined = aws_access_key_id is not None and aws_secret_access_key is not None
        when_s3_available.access_keys_defined = access_keys_defined  # Cache result to avoid having to compute it again
    if access_keys_defined:
        s3_available = getattr(when_s3_available, 's3_available', None)
        if s3_available is None:
            connection = boto.connect_s3()  # This will not error out if
                                            # AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are set,
                                            # so it can't be used to check if we have a valid connection to S3
            try:
                connection.get_all_buckets()
            except boto.exception.S3ResponseError:
                s3_available = False
            else:
                s3_available = True
            finally:
                when_s3_available.s3_available = s3_available  # Cache result to avoid having to compute it again
        return unittest.skipIf(
            not s3_available, 'S3 is not available'
        )(function)
    else:
        return unittest.skip('AWS access keys not defined')(function)
示例#27
0
def when_geolocation_data_available(function):
    config = get_test_config()
    geolocation_data = config.get('geolocation_data')
    geolocation_data_available = bool(geolocation_data) and os.path.isfile(geolocation_data)
    return unittest.skipIf(
        not geolocation_data_available, 'Geolocation data is not available'
    )(function)
示例#28
0
def skipRemote(func):
    """Decorator to skip tests based on whether server is remote,
    Remote in the sense whether it is Sauce Labs"""

    remote = int(conf.properties['main.remote'])
    return unittest.skipIf(
        remote == 1,
        "Skipping as setup related to sauce labs is missing")(func)
def when_geolocation_data_available(function):
    config = get_test_config()
    geolocation_data = config.get('geolocation_data')
    geolocation_data_available = bool(geolocation_data)
    if geolocation_data_available:
        geolocation_data_available = get_target_from_url(get_jenkins_safe_url(geolocation_data)).exists()
    return unittest.skipIf(
        not geolocation_data_available, 'Geolocation data is not available'
    )(function)
示例#30
0
文件: utils.py 项目: BrianHicks/emit
def skipIf(condition, message):
    try:
        from unittest import skipIf
        return skipIf(condition, message)
    except ImportError:  # skipIf/skip not implemented
        if condition:
            return lambda x: None
        else:
            return lambda x: x
示例#31
0
                            and not inspect.isfunction(obj))):
                    continue
                # Add to dict to ensure no duplicates
                to_test[cls.__module__ + "." + cls.__qualname__ + "." +
                        obj.__qualname__] = (import_name, module, obj)

for name, (import_name, module, obj) in to_test.items():
    # Check that class or function has an example that could be doctested
    docstring = inspect.getdoc(obj)
    if docstring is None or not "\n>>>" in docstring:
        continue
    # Remove the package name from the Python style path to the object
    name = name[len(package_name) + 1:]
    # Create the test case class. One doctest per class
    testcase = type(
        name.replace(".", "_"),
        (unittest.TestCase, ),
        {
            "obj": obj,
            "test_docstring": mktestcase(name, import_name, module, obj),
        },
    )
    # Create the name of the class using the path to it and the object name
    # Add the class to this file's globals
    setattr(sys.modules[__name__], testcase.__qualname__, testcase)

cli_cli_Version_Version_git_hash.test_docstring = unittest.skipIf(
    platform.system() == "Windows",
    "Test cleanup doesn't seem to work on Windows",
)(cli_cli_Version_Version_git_hash.test_docstring)
示例#32
0
    def setUp(self):
        super().setUp()
        set_audio_backend(self.backend)


class TorchaudioTestCase(TestBaseMixin, PytorchTestCase):
    pass


def skipIfNoExec(cmd):
    return unittest.skipIf(shutil.which(cmd) is None, f'`{cmd}` is not available')


def skipIfNoModule(module, display_name=None):
    display_name = display_name or module
    return unittest.skipIf(not is_module_available(module), f'"{display_name}" is not available')


skipIfNoSoxBackend = unittest.skipIf(
    'sox' not in torchaudio.list_audio_backends(), 'Sox backend not available')
skipIfNoCuda = unittest.skipIf(not torch.cuda.is_available(), reason='CUDA not available')
skipIfNoSox = unittest.skipIf(not is_sox_available(), reason='Sox not available')


def skipIfNoExtension(test_item):
    if is_module_available('torchaudio._torchaudio'):
        return test_item
    if 'TORCHAUDIO_TEST_FAIL_IF_NO_EXTENSION' in os.environ:
        raise RuntimeError('torchaudio C++ extension is not available.')
    return unittest.skip('torchaudio C++ extension is not available')(test_item)
示例#33
0
def skipIfNoModule(module, display_name=None):
    display_name = display_name or module
    return unittest.skipIf(not is_module_available(module), f'"{display_name}" is not available')
示例#34
0
        return fn

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        if 'fbgemm' not in torch.backends.quantized.supported_engines:
            raise unittest.SkipTest(reason)
        else:
            fn(*args, **kwargs)
    return wrapper

try:
    import torchvision  # noqa: F401
    HAS_TORCHVISION = True
except ImportError:
    HAS_TORCHVISION = False
skip_if_no_torchvision = unittest.skipIf(not HAS_TORCHVISION, "no torchvision")

def get_script_module(model, tracing, data):
    return torch.jit.trace(model, data) if tracing else torch.jit.script(model)

def lengths_to_offsets(t, offset_type=np.int64, use_begin_offset=True):
    """
    Convert lengths to offsets for embedding_bag
    """
    tt = np.zeros((t.shape[0] + 1,), dtype=offset_type)
    tt[1:] = t
    tt = torch.from_numpy(np.cumsum(tt, dtype=offset_type))
    if use_begin_offset:
        return tt[:-1]
    return tt[1:]
示例#35
0
from django_mysql.models.functions import (
    CRC32, ELT, MD5, SHA1, SHA2, Abs, AsType, Ceiling, ColumnAdd, ColumnDelete,
    ColumnGet, ConcatWS, Field, Floor, Greatest, If, JSONExtract, JSONKeys,
    JSONLength, LastInsertId, Least, RegexpInstr, RegexpReplace, RegexpSubstr,
    Round, Sign, UpdateXML, XMLExtractValue)
from testapp.models import Alphabet, Author, DynamicModel, JSONModel
from testapp.test_dynamicfield import DynColTestCase
from testapp.test_jsonfield import JSONFieldTestCase

try:
    from django.db.models.functions import Length, Lower, Upper
except ImportError:
    Length = Lower = Upper = None

requiresDatabaseFunctions = skipIf(
    django.VERSION[:2] < (1, 8),
    "Requires Database Functions from Django 1.8+")


@requiresDatabaseFunctions
class ComparisonFunctionTests(TestCase):
    def test_greatest(self):
        Alphabet.objects.create(d='A', e='B')
        ab = Alphabet.objects.annotate(best=Greatest('d', 'e')).first()
        assert ab.best == 'B'

    def test_greatest_takes_no_kwargs(self):
        with pytest.raises(TypeError):
            Greatest('a', something='wrong')

    def test_least(self):
示例#36
0
def skip_if_quick(obj):
    is_quick = os.environ.get(quick_test_var, "").lower() == "true"

    return unittest.skipIf(is_quick, "Skipping slow tests")(obj)
示例#37
0
        """Test for the Place class docstring"""
        self.assertIsNot(Place.__doc__, None, "Place class needs a docstring")
        self.assertTrue(
            len(Place.__doc__) >= 1, "Place class needs a docstring")

    def test_place_func_docstrings(self):
        """Test for the presence of docstrings in Place methods"""
        for func in self.place_f:
            self.assertIsNot(func[1].__doc__, None,
                             "{:s} method needs a docstring".format(func[0]))
            self.assertTrue(
                len(func[1].__doc__) >= 1,
                "{:s} method needs a docstring".format(func[0]))


unittest.skipIf(os.getenv("HBNB_TYPE_STORAGE") == "db", "Not Using MySQL")


class TestPlace(unittest.TestCase):
    """Test the Place class"""
    def test_is_subclass(self):
        """Test that Place is a subclass of BaseModel"""
        place = Place()
        self.assertIsInstance(place, BaseModel)
        self.assertTrue(hasattr(place, "id"))
        self.assertTrue(hasattr(place, "created_at"))
        self.assertTrue(hasattr(place, "updated_at"))

    @unittest.skipIf(
        os.getenv('HBNB_TYPE_STORAGE') == 'db', "Testing DBStorage")
    def test_city_id_attr(self):
示例#38
0
def skip_if_cudadevrt_missing(fn):
    return unittest.skipIf(cudadevrt_missing(), 'cudadevrt missing')(fn)
示例#39
0
def skip_on_cudasim(reason):
    """Skip this test if running on the CUDA simulator"""
    return unittest.skipIf(config.ENABLE_CUDASIM, reason)
示例#40
0
def skip_if_external_memmgr(reason):
    """Skip test if an EMM Plugin is in use"""
    return unittest.skipIf(config.CUDA_MEMORY_MANAGER != 'default', reason)
示例#41
0
def skip_under_cuda_memcheck(reason):
    return unittest.skipIf(os.environ.get('CUDA_MEMCHECK') is not None, reason)
示例#42
0
def skip_with_nvdisasm(reason):
    nvdisasm_path = shutil.which('nvdisasm')
    return unittest.skipIf(nvdisasm_path is not None, reason)
示例#43
0
                    '\n'
                    '%s') % (
                        ' '.join([interpreter, fn]),
                        'env=%s' % self.env,
                        fn,
                        '----\n%s\n----' % f.read(),
                    )
            if not hasattr(e, 'output'):
                # The attribute CalledProcessError.output doesn't exist on Py2.6
                e.output = None
            raise VerboseCalledProcessError(msg, e.returncode, e.cmd, output=e.output)
        return output


# Decorator to skip some tests on Python 2.6 ...
skip26 = unittest.skipIf(PY26, "this test is known to fail on Py2.6")


def expectedFailurePY3(func):
    if not PY3:
        return func
    return unittest.expectedFailure(func)

def expectedFailurePY26(func):
    if not PY26:
        return func
    return unittest.expectedFailure(func)


def expectedFailurePY27(func):
    if not PY27:
示例#44
0
    Example usage:
        @skip_plot
        class MyPlotTests(test.GraphicsTest):
            ...

    """
    skip = unittest.skipIf(
        condition=not MPL_AVAILABLE,
        reason='Graphics tests require the matplotlib library.')

    return skip(fn)


skip_grib = unittest.skipIf(
    not GRIB_AVAILABLE, 'Test(s) require "iris-grib" package, '
    'which is not available.')

skip_sample_data = unittest.skipIf(not SAMPLE_DATA_AVAILABLE,
                                   ('Test(s) require "iris_sample_data", '
                                    'which is not available.'))

skip_nc_time_axis = unittest.skipIf(
    not NC_TIME_AXIS_AVAILABLE,
    'Test(s) require "nc_time_axis", which is not available.')

skip_inet = unittest.skipIf(not INET_AVAILABLE,
                            ('Test(s) require an "internet connection", '
                             'which is not available.'))

skip_stratify = unittest.skipIf(
示例#45
0
def skipIfTravis():
    msg = ("since Travis uses Python 3.4.1 instead of 3.4.2. "
           "See: http://bugs.python.org/issue22386")
    return unittest.skipIf(os.getenv('TRAVIS', False), msg)
示例#46
0
def skip_on_arm(reason):
    cpu = platform.processor()
    is_arm = cpu.startswith('arm') or cpu.startswith('aarch')
    return unittest.skipIf(is_arm, reason)
示例#47
0
import sys
import unittest
import unittest.mock as mock
import textwrap
import errno
import contextlib

import test.support
from test.support import (EnvironmentVarGuard, TESTFN, check_warnings, forget,
                          is_jython, make_legacy_pyc, rmtree, run_unittest,
                          swap_attr, swap_item, temp_umask, unlink, unload,
                          create_empty_file, cpython_only, TESTFN_UNENCODABLE,
                          temp_dir)
from test.support import script_helper

skip_if_dont_write_bytecode = unittest.skipIf(
    sys.dont_write_bytecode, "test meaningful only when writing bytecode")


def remove_files(name):
    for f in (name + ".py", name + ".pyc", name + ".pyw", name + "$py.class"):
        unlink(f)
    rmtree('__pycache__')


@contextlib.contextmanager
def _ready_to_import(name=None, source=""):
    # sets up a temporary directory and removes it
    # creates the module file
    # temporarily clears the module from sys.modules (if any)
    # reverts or removes the module when cleaning up
    name = name or "spam"
示例#48
0
def requires_load_dynamic(meth):
    """Decorator to skip a test if not running under CPython or lacking
    imp.load_dynamic()."""
    meth = support.cpython_only(meth)
    return unittest.skipIf(not hasattr(imp, 'load_dynamic'),
                           'imp.load_dynamic() required')(meth)
示例#49
0
 def wrapper(cls):
     return unittest.skipIf(any(var not in os.environ for var in args),
                            f"Define {vars} to run {cls.__name__}")(cls)
示例#50
0
from aio_pika.exceptions import ChannelClosed

import aio_pika
import aio_pika.exceptions
from copy import copy
from aio_pika import connect, Message, DeliveryMode
from aio_pika.exceptions import ProbableAuthenticationError, MessageProcessError
from aio_pika.exchange import ExchangeType
from aio_pika.tools import wait
from unittest import mock
from . import BaseTestCase, AMQP_URL


log = logging.getLogger(__name__)
skip_for_py34 = skipIf(version_info < (3, 5), "async/await syntax supported only for python 3.5+")


class TestCase(BaseTestCase):
    @pytest.mark.asyncio
    def test_channel_close(self):
        client = yield from self.create_connection()

        self.get_random_name("test_connection")
        self.get_random_name()

        self.__closed = False

        def on_close(ch):
            log.info("Close called")
            self.__closed = True
from torch.fx.experimental.unify_refinements import infer_symbolic_types
from torch.fx.experimental.refinement_types import Equality
from torch.fx.tensor_type import TensorType, Dyn, is_consistent, is_more_precise
from torch.fx.annotate import annotate
from torch.fx.experimental.graph_gradual_typechecker import GraphTypeChecker, broadcast_types, Refine
from torch.fx.experimental.rewriter import RewritingTracer
from torch.fx import GraphModule
from torch.fx.passes.shape_prop import ShapeProp
from torch.testing._internal.common_utils import TestCase

try:
    import sympy
    HAS_SYMPY = True
except ImportError:
    HAS_SYMPY = False
skipIfNoSympy = unittest.skipIf(not HAS_SYMPY, "no sympy")

try:
    from torchvision.models import resnet50

    HAS_TORCHVISION = True
except ImportError:
    HAS_TORCHVISION = False
skipIfNoTorchVision = unittest.skipIf(not HAS_TORCHVISION, "no torchvision")


def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
    """3x3 convolution with padding"""
    return torch.nn.Conv2d(in_planes,
                           out_planes,
                           kernel_size=3,
TEST_MODES = [TestModes.DEVSIM, TestModes.RECSIM]

TEST_TEMPERATURES = [0.0, 0.01, 0.333, 300]
TEST_HEATER_PERCENTAGES = [0.0, 0.01, 99.98, 100.0]

CHANNELS = ["HE3SORB", "HE4POT", "HELOW", "HEHIGH"]

CHANNELS_WITH_STABILITY = ["HE3SORB", "HE4POT"]

CHANNELS_WITH_HEATER_AUTO = ["HE3SORB", "HEHIGH", "HELOW"]

# We only know some of these statuses - not an exhaustive set.
HELIOX_STATUSES = ["Low Temp", "High Temp", "Regenerate", "Shutdown"]

SKIP_SLOW_TESTS = False
slow_test = unittest.skipIf(SKIP_SLOW_TESTS, "Slow test skipped")


class HelioxTests(unittest.TestCase):
    """
    Tests for the heliox IOC.
    """
    def setUp(self):
        self._lewis, self._ioc = get_running_lewis_and_ioc(
            EMULATOR_NAME, DEVICE_PREFIX)
        self.ca = ChannelAccess(device_prefix=DEVICE_PREFIX,
                                default_timeout=10)
        self._lewis.backdoor_run_function_on_device("reset")

    def test_WHEN_ioc_is_started_THEN_it_is_not_disabled(self):
        self.ca.assert_that_pv_is("DISABLE", "COMMS ENABLED")
示例#53
0
# Import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests

import iris
import iris.exceptions
import iris.tests.stock
import iris.util
from unittest import skipIf

# Skip out some tests that fail now that grib edition 2 files no longer use
# the GribWrapper.
# TODO: either fix these problems, or remove the tests.
skip_irisgrib_fails = skipIf(
    True, "Test(s) are not currently usable with the new "
    "grib 2 loader.")


@tests.skip_data
@tests.skip_grib
class TestBasicLoad(tests.GraphicsTest):
    def test_load_rotated(self):
        cubes = iris.load(
            tests.get_data_path(("GRIB", "rotated_uk", "uk_wrongparam.grib1")))
        self.assertCML(cubes, ("grib_load", "rotated.cml"))

    def test_load_time_bound(self):
        cubes = iris.load(
            tests.get_data_path(
                ("GRIB", "time_processed", "time_bound.grib1")))
import unittest
import uuid

TEST_TENSORBOARD = True
try:
    import tensorboard.summary.writer.event_file_writer  # noqa F401
    from tensorboard.compat.proto.summary_pb2 import Summary
except ImportError:
    TEST_TENSORBOARD = False

HAS_TORCHVISION = True
try:
    import torchvision
except ImportError:
    HAS_TORCHVISION = False
skipIfNoTorchVision = unittest.skipIf(not HAS_TORCHVISION, "no torchvision")

TEST_CAFFE2 = True
try:
    from caffe2.python import brew, cnn, core, workspace
    from caffe2.python.model_helper import ModelHelper
except ImportError:
    TEST_CAFFE2 = False
skipIfNoCaffe2 = unittest.skipIf(not TEST_CAFFE2, "no caffe2")

TEST_MATPLOTLIB = True
try:
    import matplotlib
    if os.environ.get('DISPLAY', '') == '':
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt
示例#55
0
def skipIfNoExec(cmd):
    return unittest.skipIf(shutil.which(cmd) is None, f'`{cmd}` is not available')
示例#56
0
 def wrapper(function):
     """Wrapped version"""
     return unittest.skipIf(sys.platform == 'win32', reason)(function)
示例#57
0
    resource = None

HAS_ALARM = hasattr(signal, "alarm")

LONG_SELECT = 1.0
SHORT_SELECT = 0.01

skipUnlessHasSelector = skipUnless(hasattr(selectors2, 'SelectSelector'),
                                   "Platform doesn't have a selector")
skipUnlessHasENOSYS = skipUnless(hasattr(errno, 'ENOSYS'),
                                 "Platform doesn't have errno.ENOSYS")
skipUnlessHasAlarm = skipUnless(hasattr(signal, 'alarm'),
                                "Platform doesn't have signal.alarm()")
skipUnlessJython = skipUnless(platform.system() == 'Java',
                              "Platform is not Jython")
skipIfRetriesInterrupts = skipIf(sys.version_info >= (3, 5),
                                 "Platform retries interrupts")


def patch_select_module(testcase, *keep, **replace):
    """ Helper function that removes all selectors from the select module
    except those listed in *keep and **replace. Those in keep will be kept
    if they exist in the select module and those in replace will be patched
    with the value that is given regardless if they exist or not. Cleanup
    will restore previous state. This helper also resets the selectors module
    so that a call to DefaultSelector() will do feature detection again. """

    selectors2._DEFAULT_SELECTOR = None
    for s in ['select', 'poll', 'epoll', 'kqueue']:
        if s in replace:
            if hasattr(select, s):
                old_selector = getattr(select, s)
示例#58
0
import torch.nn.functional as F
import unittest
from contextlib import contextmanager
from itertools import product
from torch.autograd import Variable, Function
from torch.autograd.function import traceable
from common import TestCase, run_tests
import io

try:
    import torchvision
    HAS_TORCHVISION = True
except ImportError:
    HAS_TORCHVISION = False

skipIfNoTorchVision = unittest.skipIf(not HAS_TORCHVISION, "no torchvision")

RUN_CUDA = torch.cuda.is_available()
if torch.cuda.is_available():
    CUDA_VERSION = torch._C._cuda_getCompiledVersion()
    for d in range(torch.cuda.device_count()):
        major = torch.cuda.get_device_capability(d)[0]
        if (CUDA_VERSION < 8000 and major >= 6) or (CUDA_VERSION < 9000
                                                    and major >= 7):
            RUN_CUDA = False


def LSTMCell(input, hidden, w_ih, w_hh, b_ih=None, b_hh=None):
    hx, cx = hidden
    gates = F.linear(input, w_ih, b_ih) + F.linear(hx, w_hh, b_hh)
示例#59
0
from c7n.config import Bag

from c7n.testing import TestUtils, TextTestIO, functional  # NOQA

from .zpill import PillTest

logging.getLogger("placebo.pill").setLevel(logging.DEBUG)
logging.getLogger("botocore").setLevel(logging.WARNING)

# Custodian Test Account. This is used only for testing.
# Access is available for community project maintainers.
ACCOUNT_ID = "644160558196"

C7N_VALIDATE = bool(os.environ.get("C7N_VALIDATE", ""))

skip_if_not_validating = unittest.skipIf(
    not C7N_VALIDATE, reason="We are not validating schemas.")

# Set this so that if we run nose directly the tests will not fail
if "AWS_DEFAULT_REGION" not in os.environ:
    os.environ["AWS_DEFAULT_REGION"] = "us-east-1"


class BaseTest(TestUtils, PillTest):

    # custodian_schema = C7N_SCHEMA

    @property
    def account_id(self):
        return ACCOUNT_ID

    def _get_policy_config(self, **kw):
示例#60
0
def case_insensitive_tests(test):
    """Class decorator that nullifies tests requiring a case-insensitive
    file system."""
    return unittest.skipIf(not CASE_INSENSITIVE_FS,
                           "requires a case-insensitive filesystem")(test)