Beispiel #1
0
def _website_expected_redirect_response(res, status, reason, new_url):
    body = res.read()
    print(body)
    __website_expected_reponse_status(res, status, reason)
    loc = res.getheader('Location', None)
    eq(loc, new_url, 'Location header should be set "%s" != "%s"' % (loc,new_url,))
    ok(len(body) == 0, 'Body of a redirect should be empty')
Beispiel #2
0
 def test_cancel_missing_id(self):
     '''
     Test ``jobs cancel`` with a missing ID.
     '''
     code, stdout, stderr = paster(u'jobs', u'cancel', fail_on_error=False)
     neq(code, 0)
     ok(stderr)
Beispiel #3
0
def test_website_private_bucket_list_private_index_blockederrordoc():
    bucket = get_new_bucket()
    f = _test_website_prep(bucket, WEBSITE_CONFIGS_XMLFRAG['IndexDocErrorDoc'])
    bucket.set_canned_acl('private')
    indexhtml = bucket.new_key(f['IndexDocument_Suffix'])
    indexstring = choose_bucket_prefix(template=INDEXDOC_TEMPLATE, max_len=256)
    indexhtml.set_contents_from_string(indexstring)
    indexhtml.set_canned_acl('private')
    errorhtml = bucket.new_key(f['ErrorDocument_Key'])
    errorstring = choose_bucket_prefix(template=ERRORDOC_TEMPLATE, max_len=256)
    errorhtml.set_contents_from_string(errorstring)
    errorhtml.set_canned_acl('private')
    #time.sleep(1)
    while bucket.get_key(f['ErrorDocument_Key']) is None:
        time.sleep(SLEEP_INTERVAL)

    res = _website_request(bucket.name, '')
    body = res.read()
    print(body)
    _website_expected_error_response(res, bucket.name, 403, 'Forbidden', 'AccessDenied', content=_website_expected_default_html(Code='AccessDenied'), body=body)
    ok(errorstring not in body, 'error content should match error.html set content')

    indexhtml.delete()
    errorhtml.delete()
    bucket.delete()
Beispiel #4
0
 def test_cancel_missing_id(self):
     '''
     Test ``jobs cancel`` with a missing ID.
     '''
     code, stdout, stderr = paster(u'jobs', u'cancel', fail_on_error=False)
     neq(code, 0)
     ok(stderr)
Beispiel #5
0
 def test_show_missing_id(self):
     '''
     Test ``jobs show`` with a missing ID.
     '''
     code, stdout, stderr = paster(u'jobs', u'show', fail_on_error=False)
     neq(code, 0)
     ok(stderr)
Beispiel #6
0
def start(service):
    """
    Start a service and wait until it's running.
    """
    ok(service.start(block=TIMEOUT))
    assert_running()
    return service
Beispiel #7
0
def test_valid():
    vim.command('split')
    window = vim.windows[1]
    vim.current.window = window
    ok(window.valid)
    vim.command('q')
    ok(not window.valid)
Beispiel #8
0
def routing_check(*args, **kwargs):
    bucket = kwargs['bucket']
    args=args[0]
    #print(args)
    pprint(args)
    xml_fields = kwargs.copy()
    xml_fields.update(args['xml'])

    k = bucket.get_key('debug-ws.xml')
    k.set_contents_from_string(str(args)+str(kwargs), policy='public-read')

    pprint(xml_fields)
    f = _test_website_prep(bucket, WEBSITE_CONFIGS_XMLFRAG['IndexDocErrorDoc'], hardcoded_fields=xml_fields)
    #print(f)
    config_xmlcmp = bucket.get_website_configuration_xml()
    config_xmlcmp = common.normalize_xml(config_xmlcmp, pretty_print=True) # For us to read
    res = _website_request(bucket.name, args['url'])
    print(config_xmlcmp)
    new_url = args['location']
    if new_url is not None:
        new_url = get_website_url(**new_url)
        new_url = new_url.format(bucket_name=bucket.name)
    if args['code'] >= 200 and args['code'] < 300:
        #body = res.read()
        #print(body)
        #eq(body, args['content'], 'default content should match index.html set content')
        ok(res.getheader('Content-Length', -1) > 0)
    elif args['code'] >= 300 and args['code'] < 400:
        _website_expected_redirect_response(res, args['code'], IGNORE_FIELD, new_url)
    elif args['code'] >= 400:
        _website_expected_error_response(res, bucket.name, args['code'], IGNORE_FIELD, IGNORE_FIELD)
    else:
        assert(False)
Beispiel #9
0
def _website_expected_redirect_response(res, status, reason, new_url):
    body = res.read()
    print(body)
    __website_expected_reponse_status(res, status, reason)
    loc = res.getheader('Location', None)
    eq(loc, new_url, 'Location header should be set "%s" != "%s"' % (loc,new_url,))
    ok(len(body) == 0, 'Body of a redirect should be empty')
Beispiel #10
0
def test_website_private_bucket_list_private_index_blockederrordoc():
    bucket = get_new_bucket()
    f = _test_website_prep(bucket, WEBSITE_CONFIGS_XMLFRAG['IndexDocErrorDoc'])
    bucket.set_canned_acl('private')
    indexhtml = bucket.new_key(f['IndexDocument_Suffix'])
    indexstring = choose_bucket_prefix(template=INDEXDOC_TEMPLATE, max_len=256)
    indexhtml.set_contents_from_string(indexstring)
    indexhtml.set_canned_acl('private')
    errorhtml = bucket.new_key(f['ErrorDocument_Key'])
    errorstring = choose_bucket_prefix(template=ERRORDOC_TEMPLATE, max_len=256)
    errorhtml.set_contents_from_string(errorstring)
    errorhtml.set_canned_acl('private')
    #time.sleep(1)
    while bucket.get_key(f['ErrorDocument_Key']) is None:
        time.sleep(SLEEP_INTERVAL)

    res = _website_request(bucket.name, '')
    body = res.read()
    print(body)
    _website_expected_error_response(res, bucket.name, 403, 'Forbidden', 'AccessDenied', content=_website_expected_default_html(Code='AccessDenied'), body=body)
    ok(errorstring not in body, 'error content should match error.html set content')

    indexhtml.delete()
    errorhtml.delete()
    bucket.delete()
Beispiel #11
0
def test_2DmultiRegion(verbose=0):
    """Test for loading gmsh mesh through PUMI with multiple-regions"""
    testDir = os.path.dirname(os.path.abspath(__file__))
    Model = testDir + '/TwoQuads.dmg'
    Mesh = testDir + '/TwoQuads.smb'
    domain = Domain.PUMIDomain(
        dim=2, manager=MeshAdapt.AdaptManager())  #initialize the domain

    domain.AdaptManager.reconstructedFlag = 0  #this is used to indicate that no mesh reconstruction is being done.
    domain.AdaptManager.PUMIAdapter.loadModelAndMesh(bytes(Model, 'utf-8'),
                                                     bytes(Mesh, 'utf-8'))
    domain.faceList = [[14], [12], [11], [13], [15], [16]]
    domain.boundaryLabels = [1, 2, 3, 4, 5, 6]
    domain.regList = [[41], [42]]

    mesh = MeshTools.TriangularMesh()
    mesh.cmesh = cmeshTools.CMesh()
    comm = Comm.init()
    mesh.convertFromPUMI(domain,
                         domain.AdaptManager.PUMIAdapter,
                         domain.faceList,
                         domain.regList,
                         parallel=comm.size() > 1,
                         dim=domain.nd)
    ok(mesh.elementMaterialTypes[0] == 1)
    ok(mesh.elementMaterialTypes[-1] == 2)
Beispiel #12
0
def routing_check(*args, **kwargs):
    bucket = kwargs['bucket']
    args=args[0]
    #print(args)
    pprint(args)
    xml_fields = kwargs.copy()
    xml_fields.update(args['xml'])

    k = bucket.get_key('debug-ws.xml')
    k.set_contents_from_string(str(args)+str(kwargs), policy='public-read')

    pprint(xml_fields)
    f = _test_website_prep(bucket, WEBSITE_CONFIGS_XMLFRAG['IndexDocErrorDoc'], hardcoded_fields=xml_fields)
    #print(f)
    config_xmlcmp = bucket.get_website_configuration_xml()
    config_xmlcmp = common.normalize_xml(config_xmlcmp, pretty_print=True) # For us to read
    res = _website_request(bucket.name, args['url'])
    print(config_xmlcmp)
    new_url = args['location']
    if new_url is not None:
        new_url = get_website_url(**new_url)
        new_url = new_url.format(bucket_name=bucket.name)
    if args['code'] >= 200 and args['code'] < 300:
        #body = res.read()
        #print(body)
        #eq(body, args['content'], 'default content should match index.html set content')
        ok(res.getheader('Content-Length', -1) > 0)
    elif args['code'] >= 300 and args['code'] < 400:
        _website_expected_redirect_response(res, args['code'], IGNORE_FIELD, new_url)
    elif args['code'] >= 400:
        _website_expected_error_response(res, bucket.name, args['code'], IGNORE_FIELD, IGNORE_FIELD)
    else:
        assert(False)
Beispiel #13
0
 def test_show_missing_id(self):
     '''
     Test ``jobs show`` with a missing ID.
     '''
     code, stdout, stderr = paster(u'jobs', u'show', fail_on_error=False)
     neq(code, 0)
     ok(stderr)
Beispiel #14
0
 def test_is_running(self):
     """
     Test ``Service.is_running``.
     """
     service = TimedService(1)
     ok(not service.is_running())
     start(service)
     ok(service.is_running())
Beispiel #15
0
 def test_is_running(self):
     """
     Test ``Service.is_running``.
     """
     service = WaitingService()
     ok(not service.is_running())
     start(service)
     ok(service.is_running())
Beispiel #16
0
def test_command():
    fname = tempfile.mkstemp()[1]
    vim.command('new')
    vim.command('edit %s' % fname)
    vim.command('normal itesting\npython\napi')
    vim.command('w')
    ok(os.path.isfile(fname))
    eq(file(fname).read(), 'testing\npython\napi\n')
    os.unlink(fname)
Beispiel #17
0
def test_command():
    fname = tempfile.mkstemp()[1]
    vim.command('new')
    vim.command('edit %s' % fname)
    vim.command('normal itesting\npython\napi')
    vim.command('w')
    ok(os.path.isfile(fname))
    eq(file(fname).read(), 'testing\npython\napi\n')
    os.unlink(fname)
Beispiel #18
0
def test_name():
    vim.command("new")
    eq(vim.current.buffer.name, "")
    new_name = vim.eval("tempname()")
    vim.current.buffer.name = new_name
    eq(vim.current.buffer.name, new_name)
    vim.command("w!")
    ok(os.path.isfile(new_name))
    os.unlink(new_name)
Beispiel #19
0
def test_name():
    vim.command('new')
    eq(vim.current.buffer.name, '')
    new_name = vim.eval('resolve(tempname())')
    vim.current.buffer.name = new_name
    eq(vim.current.buffer.name, new_name)
    vim.command('silent w!')
    ok(os.path.isfile(new_name))
    os.unlink(new_name)
Beispiel #20
0
def test_name():
    vim.command('new')
    eq(vim.current.buffer.name, '')
    new_name = vim.eval('resolve(tempname())')
    vim.current.buffer.name = new_name
    eq(vim.current.buffer.name, new_name)
    vim.command('silent w!')
    ok(os.path.isfile(new_name))
    os.unlink(new_name)
Beispiel #21
0
def test_command():
    fname = tempfile.mkstemp()[1]
    vim.command("new")
    vim.command("edit %s" % fname)
    vim.command("normal itesting\npython\napi")
    vim.command("w")
    ok(os.path.isfile(fname))
    eq(file(fname).read(), "testing\npython\napi\n")
    os.unlink(fname)
Beispiel #22
0
def __website_expected_reponse_status(res, status, reason):
    if not isinstance(status, collections.Container):
        status = set([status])
    if not isinstance(reason, collections.Container):
        reason = set([reason])

    if status is not IGNORE_FIELD:
        ok(res.status in status, 'HTTP code was %s should be %s' % (res.status, status))
    if reason is not IGNORE_FIELD:
        ok(res.reason in reason, 'HTTP reason was was %s should be %s' % (res.reason, reason))
Beispiel #23
0
def __website_expected_reponse_status(res, status, reason):
    if not isinstance(status, collections.Container):
        status = set([status])
    if not isinstance(reason, collections.Container):
        reason = set([reason])

    if status is not IGNORE_FIELD:
        ok(res.status in status, 'HTTP code was %s should be %s' % (res.status, status))
    if reason is not IGNORE_FIELD:
        ok(res.reason in reason, 'HTTP reason was was %s should be %s' % (res.reason, reason))
Beispiel #24
0
 def dependency_order(self):
     with Workspace() as bit:
         with bit.test as test: pass
         with bit.test2 as test: pass
         bit.test << bit.test2
         ok('test2' not in bit.dependencies)
         ok('test2' not in bit.order)
         ok('test2' in bit.test.dependencies)
         ok('test2' in bit.test.order)
         ok(isinstance(bit.test.test2, Target))
Beispiel #25
0
 def test_exception_in_run(self):
     """
     Test that exceptions in ``run`` are handled correctly.
     """
     def run(service):
         service.logger.addHandler(logging.FileHandler(self.logfile.name))
         raise Exception('FOOBAR')
     CallbackService(run).start(block=TIMEOUT)
     assert_not_running()
     ok(not pid_file_exists())
     self.assert_log_contains('FOOBAR')
Beispiel #26
0
def test_get_mirrors_with_all():
    cfg = get_config()
    mirrors = list(mirror.get_mirrors(cfg, "baz"))
    eq(0, len(mirrors))

    cfg.add_section("mirror github")
    cfg.set("mirror github", "repos", "@all")
    cfg.set("mirror github", "uri", "[email protected]:res0nat0r/%s.git")
    mirrors = list(mirror.get_mirrors(cfg, "baz"))
    ok("[email protected]:res0nat0r/baz.git" in mirrors)
    eq(1, len(mirrors))
Beispiel #27
0
def test_get_mirrors_with_all():
    cfg = get_config()
    mirrors = list(mirror.get_mirrors(cfg, 'baz'))
    eq(0, len(mirrors))
    
    cfg.add_section('mirror github')
    cfg.set('mirror github', 'repos', '@all')
    cfg.set('mirror github', 'uri', '[email protected]:res0nat0r/%s.git')
    mirrors = list(mirror.get_mirrors(cfg, 'baz'))
    ok('[email protected]:res0nat0r/baz.git' in mirrors)
    eq(1, len(mirrors))
Beispiel #28
0
def test_command():
    fname = tempfile.mkstemp()[1]
    vim.command('new')
    vim.command('edit %s' % fname)
    # skip the "press return" state, which does not handle deferred calls
    vim.input('\r')
    vim.command('normal itesting\npython\napi')
    vim.command('w')
    ok(os.path.isfile(fname))
    eq(open(fname).read(), 'testing\npython\napi\n')
    os.unlink(fname)
Beispiel #29
0
 def spawn(self):
     with Target('test', None) as target:
         target.cache = 'build'
         with target.task as task:
             eq(task.name, 'task')
         with target.task('words') as task:
             eq(task.name, 'words')
         ok('words' in target.dependencies)
         ok('task' in target.dependencies)
         eq(target.task, target.dependencies['words'])
         eq(target.task, target.dependencies['task'])
Beispiel #30
0
def test_command():
    fname = tempfile.mkstemp()[1]
    vim.command('new')
    vim.command('edit %s' % fname)
    # skip the "press return" state, which does not handle deferred calls
    vim.input('\r')
    vim.command('normal itesting\npython\napi')
    vim.command('w')
    ok(os.path.isfile(fname))
    eq(open(fname).read(), 'testing\npython\napi\n')
    os.unlink(fname)
Beispiel #31
0
 def test_parent_does_not_remove_pid_file(self):
     """
     Test that the parent does not remote the PID file unintentionally.
     """
     # This could happen with older versions of the ``pid`` module,
     # which installed an ``atexit`` handler that automatically removed
     # the PID file. That mechanism could be triggered from within the
     # parent process under certain circumstances. See
     # https://github.com/torfsen/service/issues/10
     subprocess.check_call(['python', '-m', 'test.start_waiting_service'])
     ok(os.path.exists(WaitingService().pid_file._path),
        'PID file does not exist')
Beispiel #32
0
    def test_kill_timeout_fail(self):
        """
        Test ``Service.kill`` with too short a timeout.
        """
        os_kill = os.kill

        def kill_mock(pid, sig):
            if sig != signal.SIGKILL:
                return os_kill(pid, sig)

        with mock.patch('os.kill', side_effect=kill_mock):
            ok(not start(ForeverService()).kill(block=0.1))
Beispiel #33
0
def test_position():
    height = vim.windows[0].height
    width = vim.windows[0].width
    vim.command('split')
    vim.command('vsplit')
    eq((vim.windows[0].row, vim.windows[0].col), (0, 0))
    vsplit_pos = width / 2
    split_pos = height / 2
    eq(vim.windows[1].row, 0)
    ok(vsplit_pos - 1 <= vim.windows[1].col <= vsplit_pos + 1)
    ok(split_pos - 1 <= vim.windows[2].row <= split_pos + 1)
    eq(vim.windows[2].col, 0)
Beispiel #34
0
 def test_existing_job(self):
     '''
     Test showing an existing job.
     '''
     job = self.enqueue(queue=u'my_queue', title=u'Title')
     d = call_action(u'job_show', id=job.id)
     eq(d[u'id'], job.id)
     eq(d[u'title'], u'Title')
     eq(d[u'queue'], u'my_queue')
     dt = datetime.datetime.strptime(d[u'created'], u'%Y-%m-%dT%H:%M:%S')
     now = datetime.datetime.utcnow()
     ok(abs((now - dt).total_seconds()) < 10)
Beispiel #35
0
 def test_list_default_queue(self):
     '''
     Test output of ``jobs list`` for default queue.
     '''
     job = self.enqueue()
     stdout = paster(u'jobs', u'list')[1]
     fields = stdout.split()
     eq(len(fields), 3)
     dt = datetime.datetime.strptime(fields[0], u'%Y-%m-%dT%H:%M:%S')
     now = datetime.datetime.utcnow()
     ok(abs((now - dt).total_seconds()) < 10)
     eq(fields[1], job.id)
     eq(fields[2], jobs.DEFAULT_QUEUE_NAME)
Beispiel #36
0
 def test_list_default_queue(self):
     '''
     Test output of ``jobs list`` for default queue.
     '''
     job = self.enqueue()
     stdout = paster(u'jobs', u'list')[1]
     fields = stdout.split()
     eq(len(fields), 3)
     dt = datetime.datetime.strptime(fields[0], u'%Y-%m-%dT%H:%M:%S')
     now = datetime.datetime.utcnow()
     ok(abs((now - dt).total_seconds()) < 10)
     eq(fields[1], job.id)
     eq(fields[2], jobs.DEFAULT_QUEUE_NAME)
Beispiel #37
0
 def test_comments(self):
     now = datetime.datetime.now()
     now_ts = int(time.mktime(now.timetuple()))
     before_ts = int(
         time.mktime((now - datetime.timedelta(minutes=15)).timetuple()))
     message = 'test message ' + str(now_ts)
     comment_id = dog.Comment.create(handle=TEST_USER,
                                     message=message)['comment']['id']
     time.sleep(self.wait_time)
     event = dog.Event.get(comment_id)
     eq(event['event']['text'], message)
     dog.Comment.update(comment_id,
                        handle=TEST_USER,
                        message=message + ' updated')
     time.sleep(self.wait_time)
     event = dog.Event.get(comment_id)
     eq(event['event']['text'], message + ' updated')
     reply_id = dog.Comment.create(
         handle=TEST_USER,
         message=message + ' reply',
         related_event_id=comment_id)['comment']['id']
     time.sleep(30)
     stream = dog.Event.query(start=before_ts, end=now_ts + 100)['events']
     ok(stream is not None, msg="No events found in stream")
     ok(isinstance(stream, list), msg="Event stream is not a list")
     ok(len(stream) > 0, msg="No events found in stream")
     comment_ids = [x['id'] for x in stream[0]['comments']]
     ok(reply_id in comment_ids,
        msg="Should find {0} in {1}".format(reply_id, comment_ids))
     # Delete the reply
     dog.Comment.delete(reply_id)
     # Then the post itself
     dog.Comment.delete(comment_id)
Beispiel #38
0
 def test_comments(self):
     now = datetime.datetime.now()
     now_ts = int(time.mktime(now.timetuple()))
     before_ts = int(time.mktime((now - datetime.timedelta(minutes=15)).timetuple()))
     message = 'test message ' + str(now_ts)
     comment_id = dog.Comment.create(handle=TEST_USER, message=message)['comment']['id']
     time.sleep(self.wait_time)
     event = dog.Event.get(comment_id)
     eq(event['event']['text'], message)
     dog.Comment.update(comment_id, handle=TEST_USER, message=message + ' updated')
     time.sleep(self.wait_time)
     event = dog.Event.get(comment_id)
     eq(event['event']['text'], message + ' updated')
     reply_id = dog.Comment.create(handle=TEST_USER, message=message + ' reply',
                                   related_event_id=comment_id)['comment']['id']
     time.sleep(3)
     stream = dog.Event.query(start=before_ts, end=now_ts + 100)['events']
     ok(stream is not None, msg="No events found in stream")
     ok(isinstance(stream, list), msg="Event stream is not a list")
     ok(len(stream) > 0, msg="No events found in stream")
     comment_ids = [x['id'] for x in stream[0]['comments']]
     ok(reply_id in comment_ids,
        msg="Should find {0} in {1}".format(reply_id, comment_ids))
     # Delete the reply
     dog.Comment.delete(reply_id)
     # Then the post itself
     dog.Comment.delete(comment_id)
     time.sleep(self.wait_time)
     try:
         dog.Event.get(comment_id)
     except:
         pass
     else:
         assert False
Beispiel #39
0
def validate_response(r, **options):
    " Validate webtest response "

    # Validate: status, status_int, status_code
    ok(r.status.startswith("%d " % r.status_int))
    ok(r.status_int >= 100)
    eq(r.status_int, r.status_code)
    eq(r.status_int, options.get("status_int", 200))

    # Validate: headers
    " Ref: https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters "
    message = "Must be printable ASCII characters: %s"
    for key, value in r.headers.iteritems():
        ok(re.match("^[\x20-\x7e]*$", value), message % repr(value))
    # endfold

    eq(r.content_type, options.get("content_type", "text/plain"))

    # Validate: status: 200
    if r.status_int == 200:
        ok("location" not in r.headers)

    # Validate: status: 301, 302
    if r.status_int in [301, 302]:
        eq(urllib.unquote(r.headers["location"]), options["location"])
        eq(r.normal_body, "")
Beispiel #40
0
    def test_aio_notify(self):
        with self.ioctx.watch(self.OID, self.make_callback_reply(),
                              self.make_error_callback()) as watch1:
            watch_id1 = watch1.get_id()
            ok(watch_id1 > 0)

            with self.rados.open_ioctx('test_pool') as ioctx:
                watch2 = ioctx.watch(self.OID, self.make_callback_reply(),
                                     self.make_error_callback())
            watch_id2 = watch2.get_id()
            ok(watch_id2 > 0)

            comp = self.ioctx.aio_notify(self.OID, self.notify_callback, msg='test')
            comp.wait_for_complete_and_cb()
            with self.lock:
                ok(self.instance_id in self.ack_cnt)
                eq(self.ack_cnt[self.instance_id], 2)
                eq(self.ack_data[self.instance_id], b'test')

            ok(watch1.check() >= timedelta())
            ok(watch2.check() >= timedelta())

            comp = self.ioctx.aio_notify(self.OID, self.notify_callback, msg='best')
            comp.wait_for_complete_and_cb()
            with self.lock:
                eq(self.ack_cnt[self.instance_id], 4)
                eq(self.ack_data[self.instance_id], b'best')

            watch2.close()

            comp = self.ioctx.aio_notify(self.OID, self.notify_callback, msg='rest')
            comp.wait_for_complete_and_cb()
            with self.lock:
                eq(self.ack_cnt[self.instance_id], 5)
                eq(self.ack_data[self.instance_id], b'rest')

            assert(watch1.check() >= timedelta())
            self.ioctx.remove_object(self.OID)

            for i in range(10):
                with self.lock:
                    if watch_id1 in self.notify_error:
                        break
                time.sleep(1)
            eq(self.notify_error[watch_id1], -errno.ENOTCONN)
            assert_raises(NotConnected, watch1.check)

            comp = self.ioctx.aio_notify(self.OID, self.notify_callback_err, msg='test')
            comp.wait_for_complete_and_cb()
Beispiel #41
0
def test_getAliasRepos():
    cfg = RawConfigParser()
    cfg.add_section('gitosis')
    cfg.set('gitosis', 'foo', 'bar baz')
    repos = list(util.getAliasRepositories(cfg, 'foo'))
    ok('bar' in repos)
    ok('baz' in repos)
    eq(2, len(repos))
    
    cfg.set('gitosis', 'foobar', '@foo foo')
    repos = list(util.getAliasRepositories(cfg, 'foobar'))
    ok('bar' in repos)
    ok('baz' in repos)
    ok('foo' in repos)
    eq(3, len(repos))
def test_norm_triangle_inequality():
    """test_norm_triangle_inequality

    Test if defined norms in proteus.LinearAlgebraTools obey
    the triangle inequality for several trials.
    """

    from proteus.LinearAlgebraTools import Vec
    from proteus.LinearAlgebraTools import Mat

    h = Vec(2)
    h[:] = [1.0, 1.0]

    #need an SPD matrix for this to be a norm
    A = Mat(2, 2)
    A[0, :] = [4, 2]
    A[1, :] = [2, 5]

    v1 = Vec(2)
    v1[:] = [1, 1]

    v2 = Vec(2)
    v2[:] = [-1, 4]

    for name, norms in compute_norms(h, A, [v1+v2, v1, v2]):
        t1, t2, t3 = norms
        test = lambda b: ok(b)
        test.description = 'test_norm_triangle_inequality[{}]'.format(name)
        yield test, t1 <= t2 + t3
Beispiel #43
0
def test_list_runtime_paths():
    # Is this the default runtime path list?
    homedir = os.environ['HOME'] + '/.nvim'
    dflt_rtp = [
        homedir,
        '/usr/local/share/nvim/vimfiles',
        '/usr/local/share/nvim',
        '/usr/local/share/nvim/vimfiles/after'
    ]
    # If the runtime is installed the default path
    # is nvim/runtime
    dflt_rtp2 = list(dflt_rtp)
    dflt_rtp2[2] += '/runtime'

    rtp = vim.list_runtime_paths()
    ok(rtp == dflt_rtp or rtp == dflt_rtp2)
Beispiel #44
0
def test_norm_triangle_inequality():
    """test_norm_triangle_inequality

    Test if defined norms in proteus.LinearAlgebraTools obey
    the triangle inequality for several trials.
    """

    from proteus.LinearAlgebraTools import Vec
    from proteus.LinearAlgebraTools import Mat

    h = Vec(2)
    h[:] = [1.0, 1.0]

    #need an SPD matrix for this to be a norm
    A = Mat(2, 2)
    A[0, :] = [4, 2]
    A[1, :] = [2, 5]

    v1 = Vec(2)
    v1[:] = [1, 1]

    v2 = Vec(2)
    v2[:] = [-1, 4]

    for name, norms in compute_norms(h, A, [v1 + v2, v1, v2]):
        t1, t2, t3 = norms
        test = lambda b: ok(b)
        test.description = 'test_norm_triangle_inequality[{}]'.format(name)
        yield test, t1 <= t2 + t3
Beispiel #45
0
def test_list_runtime_paths():
    # Is this the default runtime path list?
    homedir = os.path.join(os.environ['HOME'], '.nvim')
    vimdir = vim.eval('$VIM')
    dflt_rtp = [
        homedir,
        os.path.join(vimdir, 'vimfiles'), vimdir,
        os.path.join(vimdir, 'vimfiles', 'after')
    ]
    # If the runtime is installed the default path
    # is nvim/runtime
    dflt_rtp2 = list(dflt_rtp)
    dflt_rtp2[2] = os.path.join(dflt_rtp2[2], 'runtime')

    rtp = vim.list_runtime_paths()
    ok(rtp == dflt_rtp or rtp == dflt_rtp2)
def test_clusterpolate():
    targets = np.array([(0, 0), (1.0, 0), (1.5, 0)])
    pred, member = cp.clusterpolate(points, values, targets, radius=1)
    eq(pred.shape, (3,))
    eq(member.shape, (3,))
    ok(pred.min() >= values.min())
    ok(pred.max() <= values.max())
    ok(member.min() >= 0)
    ok(member.max() <= 1)
Beispiel #47
0
def test_Application_exception():
    app = natrix.Application([
        ("/", lambda x: x.response("" + 1)),
    ])
    testapp = webtest.TestApp(app)

    def _error(*args, **kwargs):
        pass
    # endfold

    natrix_error = natrix.error
    natrix.error = _error
    response = testapp.get("/", status=500)
    eq(response.status_int, 500)
    ok(response.normal_body.startswith("Traceback (most recent call last)"))
    eq(response.content_type, "text/plain")
    natrix.error = natrix_error
Beispiel #48
0
def test_list_runtime_paths():
    # Is this the default runtime path list?
    homedir = os.path.join(os.environ['HOME'], '.nvim')
    vimdir = vim.eval('$VIM')
    dflt_rtp = [
        homedir,
        os.path.join(vimdir, 'vimfiles'),
        vimdir,
        os.path.join(vimdir, 'vimfiles', 'after')
    ]
    # If the runtime is installed the default path
    # is nvim/runtime
    dflt_rtp2 = list(dflt_rtp)
    dflt_rtp2[2] = os.path.join(dflt_rtp2[2], 'runtime')

    rtp = vim.list_runtime_paths()
    ok(rtp == dflt_rtp or rtp == dflt_rtp2)
Beispiel #49
0
def _website_expected_error_response(res, bucket_name, status, reason, code, content=None, body=None):
    if body is None:
        body = res.read()
        print(body)
    __website_expected_reponse_status(res, status, reason)

    # Argh, AmazonS3 is really inconsistent, so we have a conditional test!
    # This is most visible if you have an ErrorDoc present
    errorcode = res.getheader('x-amz-error-code', None)
    if errorcode is not None:
        if code is not IGNORE_FIELD:
            eq(errorcode, code)

    if not isinstance(content, collections.Container):
        content = set([content])
    for f in content:
        if f is not IGNORE_FIELD and f is not None:
            ok(f in body, 'HTML should contain "%s"' % (f, ))
Beispiel #50
0
def _website_expected_error_response(res, bucket_name, status, reason, code, content=None, body=None):
    if body is None:
        body = res.read()
        print(body)
    __website_expected_reponse_status(res, status, reason)

    # Argh, AmazonS3 is really inconsistent, so we have a conditional test!
    # This is most visible if you have an ErrorDoc present
    errorcode = res.getheader('x-amz-error-code', None)
    if errorcode is not None:
        if code is not IGNORE_FIELD:
            eq(errorcode, code)

    if not isinstance(content, collections.Container):
        content = set([content])
    for f in content:
        if f is not IGNORE_FIELD and f is not None:
            ok(f in body, 'HTML should contain "%s"' % (f, ))
Beispiel #51
0
def test_2DmultiRegion(verbose=0):
    """Test for loading gmsh mesh through PUMI with multiple-regions"""
    testDir=os.path.dirname(os.path.abspath(__file__))
    Model=testDir + '/TwoQuads.dmg'
    Mesh=testDir + '/TwoQuads.smb'
    domain = Domain.PUMIDomain(dim=2) #initialize the domain
    domain.PUMIMesh=MeshAdaptPUMI.MeshAdaptPUMI()
    domain.PUMIMesh.loadModelAndMesh(Model, Mesh)
    domain.faceList=[[14],[12],[11],[13],[15],[16]]
    domain.regList=[[41],[42]]

    mesh = MeshTools.TriangularMesh()
    mesh.cmesh = cmeshTools.CMesh()
    comm = Comm.init()

    mesh.convertFromPUMI(domain.PUMIMesh, domain.faceList,domain.regList, parallel = comm.size() > 1, dim = domain.nd)
    ok(mesh.elementMaterialTypes[0]==1)
    ok(mesh.elementMaterialTypes[-1]==2)
Beispiel #52
0
    def test_exception_in_run(self):
        """
        Test that exceptions in ``run`` are handled correctly.
        """
        log_file = tempfile.NamedTemporaryFile(dir=TEMP_DIR, delete=False)
        log_file.close()

        def run(service):
            time.sleep(DELAY)
            service.logger.addHandler(logging.FileHandler(log_file.name))
            raise Exception('FOOBAR')

        start(CallbackService(run))
        time.sleep(2 * DELAY)
        assert_not_running()
        ok(not pid_file_exists())
        with open(log_file.name) as f:
            ok('FOOBAR' in f.read())
Beispiel #53
0
    def test_files_preserve(self):
        """
        Test file handle preservation.
        """
        class FileHandleService(BasicService):
            def __init__(self):
                super(FileHandleService, self).__init__()
                self.f = tempfile.NamedTemporaryFile(mode='wt', delete=False)
                self.files_preserve = [self.f]
            def run(self):
                self.f.write('foobar')
                self.f.close()
                self.wait_for_sigterm()

        service = FileHandleService()
        start(service)
        service.stop(block=1)
        ok(os.path.isfile(service.f.name))
        with open(service.f.name, 'r') as f:
            eq(f.read(), 'foobar')
        os.unlink(f.name)
Beispiel #54
0
    def test_builtin_log_handlers_file_handles_are_preserved(self):
        """
        Test that file handles of built-in log handlers are preserved.
        """
        class LoggingService(BasicService):
            def __init__(self):
                super(LoggingService, self).__init__()
                self.f = tempfile.NamedTemporaryFile(delete=False)
                self.f.close()
                self.logger.addHandler(logging.FileHandler(self.f.name))
            def run(self):
                self.logger.warn('foobar')
                self.wait_for_sigterm()

        service = LoggingService()
        start(service)
        service.stop(block=1)
        ok(os.path.isfile(service.f.name))
        with open(service.f.name, 'r') as f:
            ok('foobar' in f.read())
        os.unlink(f.name)
Beispiel #55
0
def test_get_mirrors():
    cfg = get_config()
    cfg.add_section('mirror github')
    cfg.set('mirror github', 'repos', 'foo bar')
    cfg.set('mirror github', 'uri', '[email protected]:res0nat0r/%s.git')
    mirrors = list(mirror.get_mirrors(cfg, 'foo'))
    ok('/var/bar' in mirrors)
    ok('/var/baz' in mirrors)
    ok('[email protected]:res0nat0r/foo.git' in mirrors)
    eq(3, len(mirrors))
    
    mirrors = list(mirror.get_mirrors(cfg, 'bar'))
    ok('[email protected]:res0nat0r/bar.git' in mirrors)
    eq(1, len(mirrors))
Beispiel #56
0
def test_2DmultiRegion(verbose=0):
    """Test for loading gmsh mesh through PUMI with multiple-regions"""
    testDir = os.path.dirname(os.path.abspath(__file__))
    Model = testDir + '/TwoQuads.dmg'
    Mesh = testDir + '/TwoQuads.smb'
    domain = Domain.PUMIDomain(dim=2)  #initialize the domain
    domain.PUMIMesh = MeshAdaptPUMI.MeshAdaptPUMI()
    domain.PUMIMesh.loadModelAndMesh(Model, Mesh)
    domain.faceList = [[14], [12], [11], [13], [15], [16]]
    domain.regList = [[41], [42]]

    mesh = MeshTools.TriangularMesh()
    mesh.cmesh = cmeshTools.CMesh()
    comm = Comm.init()

    mesh.convertFromPUMI(domain.PUMIMesh,
                         domain.faceList,
                         domain.regList,
                         parallel=comm.size() > 1,
                         dim=domain.nd)
    ok(mesh.elementMaterialTypes[0] == 1)
    ok(mesh.elementMaterialTypes[-1] == 2)
Beispiel #57
0
    def test_builtin_log_handlers_file_handles_are_preserved(self):
        """
        Test that file handles of built-in log handlers are preserved.
        """
        class LoggingService(BasicService):
            def __init__(self):
                super(LoggingService, self).__init__()
                self.f = tempfile.NamedTemporaryFile(delete=False)
                self.f.close()
                self.logger.addHandler(logging.FileHandler(self.f.name))
            def run(self):
                self.logger.warn('foobar')
                self.wait_for_sigterm()

        service = LoggingService()
        start(service)
        try:
            service.stop(block=TIMEOUT)
            ok(os.path.isfile(service.f.name))
            with open(service.f.name, 'r') as f:
                ok('foobar' in f.read())
        finally:
            os.unlink(service.f.name)
Beispiel #58
0
    def test_files_preserve(self):
        """
        Test file handle preservation.
        """
        class FileHandleService(BasicService):
            def __init__(self):
                super(FileHandleService, self).__init__()
                self.f = tempfile.NamedTemporaryFile(mode='wt', delete=False)
                self.files_preserve = [self.f]
            def run(self):
                self.f.write('foobar')
                self.f.close()
                self.wait_for_sigterm()

        service = FileHandleService()
        start(service)
        try:
            service.stop(block=TIMEOUT)
            ok(os.path.isfile(service.f.name))
            with open(service.f.name, 'r') as f:
                eq(f.read(), 'foobar')
        finally:
            os.unlink(f.name)