示例#1
0
文件: test_user.py 项目: 6779660/ckan
    def test_upgrade_from_pbkdf2_with_less_rounds(self):
        '''set up a pbkdf key with less than the default rounds

        If the number of default_rounds is increased in a later version of
        passlib, ckan should upgrade the password hashes for people without
        involvement from users'''
        user = factories.User()
        password = u'testpassword'
        user_obj = model.User.by_name(user['name'])

        # setup hash with salt/rounds less than the default
        old_hash = pbkdf2_sha512.encrypt(password, salt_size=2, rounds=10)
        user_obj._password = old_hash
        user_obj.save()

        nt.assert_true(user_obj.validate_password(password.encode('utf-8')))
        # check that the hash has been updated
        nt.assert_not_equals(old_hash, user_obj.password)
        new_hash = pbkdf2_sha512.from_string(user_obj.password)

        nt.assert_true(pbkdf2_sha512.default_rounds > 10)
        nt.assert_equals(pbkdf2_sha512.default_rounds, new_hash.rounds)

        nt.assert_true(pbkdf2_sha512.default_salt_size, 2)
        nt.assert_equals(pbkdf2_sha512.default_salt_size,
                         len(new_hash.salt))
        nt.assert_true(pbkdf2_sha512.verify(password, user_obj.password))
    def test_without_ax(self):
        fig, ax = validate.mpl_ax(None)
        nt.assert_not_equals(self.fig, fig)
        nt.assert_not_equals(self.ax, ax)

        nt.assert_true(isinstance(fig, plt.Figure))
        nt.assert_true(isinstance(ax, plt.Axes))
示例#3
0
def test_caching_is_per_instance():
    # Test that values cached for one instance do not appear on another
    class FieldTester(object):
        """Toy class for ModelMetaclass and field access testing"""
        __metaclass__ = ModelMetaclass

        field_a = List(scope=Scope.settings)

        def __init__(self, model_data):
            self._model_data = model_data
            self._dirty_fields = set()

    model_data = MagicMock(spec=dict)
    model_data.__getitem__ = lambda self, name: [name]

    # Same model_data used in different objects should result
    # in separately-cached values, so that changing a value
    # in one instance doesn't affect values stored in others.
    field_tester_a = FieldTester(model_data)
    field_tester_b = FieldTester(model_data)
    value = field_tester_a.field_a
    assert_equals(value, field_tester_a.field_a)
    field_tester_a.field_a.append(1)
    assert_equals(value, field_tester_a.field_a)
    assert_not_equals(value, field_tester_b.field_a)
示例#4
0
    def test_security_comparisons(self):
        assert_equals(Security("USD"), USD)
        assert_equals(Security("USD"), Security("USD"))
        assert_equals(Security("BTC"), Security("BTC"))

        assert_not_equals(Security("INR"), USD)
        assert_not_equals(Security("INR"), Security("BTC"))
 def test_inequality(self):
     layer_a = TransportAddress()
     layer_b = TransportAddress(high=2)
     assert_not_equals(layer_a, layer_b)
     layer_a.low = 2
     layer_b.high = 65535
     assert_not_equals(layer_a, layer_b)
示例#6
0
    def test_gen_minhash(self):
        actual = self.bbmh.gen_minhash(['love', 'me'])
        assert_equals(len(actual), self.bbmh.num_hashes)
        assert_true(isinstance(actual, np.ndarray))

        other_hash = self.bbmh.gen_minhash(['tokyo', 'sushi'])
        assert_not_equals(actual.tostring(), other_hash.tostring())
    def test_active_dois(self, test_data):

        (doi, fulltext_url, license, color) = test_data

        # because cookies breaks the cache pickling
        # for doi_start in ["10.1109", "10.1161", "10.1093", "10.1007", "10.1039"]:
        #     if doi.startswith(doi_start):
        # requests_cache.uninstall_cache()

        my_pub = pub.lookup_product_by_doi(doi)
        my_pub.refresh()

        logger.info(u"\n\nwas looking for {}, got {}".format(fulltext_url, my_pub.fulltext_url))
        logger.info(u"https://api.unpaywall.org/v2/{}?email=me".format(doi))
        logger.info(u"doi: https://doi.org/{}".format(doi))
        logger.info(u"license: {}".format(my_pub.license))
        logger.info(u"oa_color: {}".format(my_pub.oa_color))
        logger.info(u"evidence: {}".format(my_pub.evidence))
        if my_pub.error:
            logger.info(my_pub.error)

        assert_equals(my_pub.error, "")
        assert_equals(my_pub.fulltext_url, fulltext_url)
        assert_not_equals(my_pub.fulltext_url, None)
        # assert_equals(my_pub.license, license)
        assert_equals(my_pub.error, "")
def test_create_periodic_report_with_group():
    collection = get_mongo_collection()
    collection.remove()
    collection.insert({
        'event': "statistc",
        'timestamp': datetime(2011, 4, 7),
        'params': {"url": "www.centrum.cz"}
    })
    collection.insert({
        'event': "statistc",
        'timestamp': datetime(2011, 4, 1),
        'params': {"url": "www.centrum.cz"}
    })
    collection.insert({
        'event': "statistc",
        'timestamp': datetime(2011, 3, 7),
        'params': {"url": "www.centrum.cz"}
    })
    collection.insert({
        'event': "statistc",
        'timestamp': datetime(2011, 3, 21),
        'params': {"url": "www.centrum.cz"}
    })
    report = Report(title="report group", description="test", db_query='db.%s.group({ key : { "params.url" : true }, condition : { event : "statistic", timestamp : {$gt : ${{d1}}, $lt: ${{d2}}} }, reduce : function( obj, prev ) { prev.total++; }, initial : { total : 0 } })' % (STATISTICS_MONGODB_COLLECTION,), interval='m')
    report.save()
    tools.assert_equals(True, create_reports())
    tools.assert_not_equals(ReportResult.objects.all().count(), 0)
    tools.assert_not_equals(Report.objects.all()[0].last_report, None)
    collection.remove()
示例#9
0
 def test_inequality(self):
     group01 = NetworkGroup()
     group02 = NetworkGroup()
     group01.add(self.address01)
     assert_not_equals(group01, group02)
     group02.add(self.address01)
     assert_not_equals(group01, group02)
示例#10
0
文件: test_core.py 项目: qvin/XBlock
def test_caching_is_per_instance():
    # Test that values cached for one instance do not appear on another
    class FieldTester(object):
        """Toy class for ModelMetaclass and field access testing"""
        __metaclass__ = ModelMetaclass

        field_a = List(scope=Scope.settings)

        def __init__(self, field_data):
            self._field_data = field_data
            self._dirty_fields = {}

    field_data = MagicMock(spec=FieldData)
    field_data.get = lambda block, name, default=None: [name]  # pylint: disable=C0322

    # Same field_data used in different objects should result
    # in separately-cached values, so that changing a value
    # in one instance doesn't affect values stored in others.
    field_tester_a = FieldTester(field_data)
    field_tester_b = FieldTester(field_data)
    value = field_tester_a.field_a
    assert_equals(value, field_tester_a.field_a)
    field_tester_a.field_a.append(1)
    assert_equals(value, field_tester_a.field_a)
    assert_not_equals(value, field_tester_b.field_a)
def test_create_aperiodic_report_with_mapreduce():
    collection = get_mongo_collection()
    collection.remove()
    collection.insert({
        'event': "statistic",
        'timestamp': datetime(2010, 4, 1),
        'params': {"url": "www.atlas.cz"}
    })
    collection.insert({
        'event': "statistic",
        'timestamp': datetime(2011, 3, 7),
        'params': {"url": "www.centrum.cz"}
    })
    collection.insert({
        'event': "statistic",
        'timestamp': datetime(2011, 3, 21),
        'params': {"url": "www.centrum.cz"}
    })
    report = Report(title="report mapreduce", description="test", db_query='m = function() { if (this.event == "statistic") { emit(this.params.url, 1); }};r = function(url, nums) { var total=0; for (var i=0; i<nums.length; i++) { total += nums[i]; } return total; };res = db.%s.mapReduce(m, r);res.find().forEach(printjson);' % (STATISTICS_MONGODB_COLLECTION,), interval='n')
    report.save()
    tools.assert_equals(True, create_reports())
    tools.assert_not_equals(ReportResult.objects.all().count(), 0)
    tools.assert_not_equals(Report.objects.all()[0].last_report, None)
    tools.assert_equals(ReportResult.objects.all()[0].output, '{ "_id" : "www.atlas.cz", "value" : 1 }\n{ "_id" : "www.centrum.cz", "value" : 2 }\n')
    collection.remove()
示例#12
0
  def test_chown(self):
    # Create a test directory with
    # a subdirectory and a few files.
    dir1 = '/test'
    subdir1 = dir1 + '/test1'
    file1 = subdir1 + '/test1.txt'
    fs = self.cluster.fs
    try:
      fs.mkdir(subdir1)
      f = fs.open(file1, "w")
      f.write("hello")
      f.close()

      # Check currrent owners are not user test
      LOG.info(str(fs.stats(dir1).__dict__))
      assert_not_equals('test', fs.stats(dir1).user)
      assert_not_equals('test', fs.stats(subdir1).user)
      assert_not_equals('test', fs.stats(file1).user)

      # Chown non-recursive
      fs.chown(dir1, 'test', recursive=False)
      assert_equals('test', fs.stats(dir1).user)
      assert_not_equals('test', fs.stats(subdir1).user)
      assert_not_equals('test', fs.stats(file1).user)

      # Chown recursive
      fs.chown(dir1, 'test', recursive=True)
      assert_equals('test', fs.stats(dir1).user)
      assert_equals('test', fs.stats(subdir1).user)
      assert_equals('test', fs.stats(file1).user)
    finally:
      try:
        fs.rmtree(dir1)
      finally:
        pass
示例#13
0
    def test_result_does_not_reflect_changes(self):
        model = Question
        for i in range(1, 5):
            create_question(self, question_text="question %s" % i)

        all_questions = list(model.objects.all().order_by('pk'))

        with self.assertNumQueries(1):
            cached_questions = get_cached_all_guestions()
        tools.assert_equals(cached_questions, all_questions)

        with self.assertNumQueries(0):
            cached_questions = get_cached_all_guestions()
        tools.assert_equals(cached_questions, all_questions)

        create_question(self, question_text="question 7")
        all_questions_old = all_questions
        all_questions = list(model.objects.all().order_by('pk'))

        with self.assertNumQueries(0):
            cached_questions = get_cached_all_guestions()
        tools.assert_equals(cached_questions, all_questions_old)
        tools.assert_not_equals(cached_questions, all_questions)
        tools.assert_true(len(cached_questions), 6)
        tools.assert_true(len(all_questions), 7)
def test_create_aperiodic_report_with_count():
    collection = get_mongo_collection()
    collection.remove()
    collection.insert({
        'event': "statistc",
        'timestamp': datetime(2010, 3, 1),
        'params': {"url": "www.centrum.cz"}
    })
    collection.insert({
        'event': "statistc",
        'timestamp': datetime(2011, 2, 12),
        'params': {"url": "www.centrum.cz"}
    })
    collection.insert({
        'event': "content_link",
        'timestamp': datetime(2011, 2, 12),
        'params': {"url": "www.atlas.cz"}
    })
    report = Report(title="report count", description="test", db_query='db.%s.find({event: "statistc"}).count()' % (STATISTICS_MONGODB_COLLECTION,), interval='n')
    report.save()
    report = Report(title="report now", description="test", db_query='db.%s.count()' % (STATISTICS_MONGODB_COLLECTION,), interval='n')
    report.save()
    tools.assert_equals(True, create_reports())
    tools.assert_equals(ReportResult.objects.all().count(), 2)
    tools.assert_not_equals(Report.objects.all()[0].last_report, None)
    tools.assert_equals(ReportResult.objects.all()[0].output, '{"count" : 2}')
    tools.assert_equals(ReportResult.objects.all()[1].output, '{"count" : 3}')
    collection.remove()
示例#15
0
def test_step_description():
    "Step description takes a line and filename, " "and keeps the relative path for filename"

    description = core.StepDescription(10, __file__)
    assert_equals(description.file, core.fs.relpath(__file__))
    assert_not_equals(description.file, __file__)
    assert_equals(description.line, 10)
示例#16
0
 def test_ineqaulity(self):
     acl01 = Acl()
     acl01.add(Ace(logging=2))
     acl02 = Acl()
     assert_not_equals(acl01, acl02)
     acl02.add(Ace())
     assert_not_equals(acl01, acl02)
示例#17
0
 def test_equality(self):
     ctx01 = DeviceContext('ctx01')
     ctx02 = DeviceContext('ctx02')
     ctx03 = DeviceContext('ctx03')
     assert_equals(self.ctx01, ctx01)
     assert_not_equals(self.ctx01, ctx03)
     assert_not_equals(ctx02, ctx03)
示例#18
0
    def test_inheritable_attribute(self):
        # days_early_for_beta isn't a basic attribute of Sequence
        assert_false(hasattr(SequenceDescriptor, 'days_early_for_beta'))

        # days_early_for_beta is added by InheritanceMixin
        assert_true(hasattr(InheritanceMixin, 'days_early_for_beta'))

        root = SequenceFactory.build(policy={'days_early_for_beta': '2'})
        ProblemFactory.build(parent=root)

        # InheritanceMixin will be used when processing the XML
        assert_in(InheritanceMixin, root.xblock_mixins)

        seq = self.process_xml(root)

        assert_equals(seq.unmixed_class, SequenceDescriptor)
        assert_not_equals(type(seq), SequenceDescriptor)

        # days_early_for_beta is added to the constructed sequence, because
        # it's in the InheritanceMixin
        assert_equals(2, seq.days_early_for_beta)

        # days_early_for_beta is a known attribute, so we shouldn't include it
        # in xml_attributes
        assert_not_in('days_early_for_beta', seq.xml_attributes)
    def test_create_showif(self):
        page = factories.PageFactory()
        element = factories.ElementFactory()

        conditions = json.dumps({
            'node_type': 'NOT',
            'children': [
                {
                    'node_type': 'AND',
                    'children': [
                        {
                            'criteria_element': element.pk,
                            'node_type': 'EQUALS',
                            'value': 'foo'
                        },
                        {
                            'criteria_element': element.pk,
                            'node_type': 'LESS',
                            'value': 'bar'
                        }
                    ]
                }
            ]
        })
        ShowIf.objects.create(page=page, conditions=conditions)

        show_if = ShowIf.objects.get(page=page)

        assert_equals(show_if.page, page)
        assert_equals(show_if.conditions, conditions)
        assert_not_equals(show_if.last_modified, None)
        assert_not_equals(show_if.created, None)
示例#20
0
def test_configuration_decorator():
    def test_f():
        return 0
    conf.override_all({test_f.__name__: -1})
    test_f_decorated = conf._override(test_f)
    assert_not_equals(test_f_decorated(), test_f())
    assert_equals(test_f_decorated(), -1)
示例#21
0
    def check_inheritable_attribute(self, attribute, value):
        # `attribute` isn't a basic attribute of Sequence
        assert_false(hasattr(SequenceDescriptor, attribute))

        # `attribute` is added by InheritanceMixin
        assert_true(hasattr(InheritanceMixin, attribute))

        root = SequenceFactory.build(policy={attribute: str(value)})
        ProblemFactory.build(parent=root)

        # InheritanceMixin will be used when processing the XML
        assert_in(InheritanceMixin, root.xblock_mixins)

        seq = self.process_xml(root)

        assert_equals(seq.unmixed_class, SequenceDescriptor)
        assert_not_equals(type(seq), SequenceDescriptor)

        # `attribute` is added to the constructed sequence, because
        # it's in the InheritanceMixin
        assert_equals(value, getattr(seq, attribute))

        # `attribute` is a known attribute, so we shouldn't include it
        # in xml_attributes
        assert_not_in(attribute, seq.xml_attributes)
示例#22
0
 def test_clean_data_content_stripping(self):
     # html, url and date stripping
     data = {
             "data": "<script>hello</script>",
             "url": "javascript:alert('invalid')",
             "pub_date": "invalid",
             "nested": {
                 "url": "http://totallyvalid.com",
                 "data1": "<b>strong</b>",
                 "pub_date": "2014-01-01",
                 "data2": [
                     "<em>emphasis</em>",
                     {
                         "data3": "<span>span</span>",
                         "url": "javascript:alert('invalid')",
                     }
                 ]
             }
     }
     cleaned = self.most_popular.clean_data(data, aggressive=False)
     assert_not_equals(cleaned, data)
     assert_equals(cleaned["data"], "hello")
     assert_equals(cleaned["url"], "")
     assert_equals(cleaned["pub_date"], "")
     assert_equals(cleaned["nested"]["data1"], "strong")
     assert_equals(cleaned["nested"]["pub_date"], "2014-01-01")
     assert_equals(cleaned["nested"]["url"], "http://totallyvalid.com")
     assert_equals(cleaned["nested"]["data2"][0], "emphasis")
     assert_equals(cleaned["nested"]["data2"][1]["data3"], "span")
     assert_equals(cleaned["nested"]["data2"][1]["url"], "")
示例#23
0
def test_encoding(uint_val, separator):
    quint = uint2quint(uint_val, separator)
    assert_not_equals(quint, uint_val)
    assert_equals(11, len(quint))

    uint_val1 = quint2uint(quint)
    assert_equals(uint_val, uint_val1)
示例#24
0
def test_good_error_match():
    conf = {'user': '******', 'password': '******', 'api_id': '1234'}
    clickatell = ClickatellBackend(name="clickatell", router=router, **conf)
    error = clickatell.error_check('ERR: 114, Cannot route message')
    assert_not_equals(error, None)
    code, message = error
    assert_equals(code, 114)
    assert_equals(message, 'Cannot route message')
示例#25
0
def test_mxlookup():
    """Test that mxlookup returns preference numbers
    and domains.

    """
    for (pref, server) in ayst.mxlookup('raynes.me'):
        nt.assert_is_instance(pref, int)
        nt.assert_not_equals(server.find('GOOGLE'), -1)
示例#26
0
    def test_return_none_if_image_does_not_changed(self):
        image_path = get_full_file_path(os.path.join('data', 'small_image.jpg'))

        with open(image_path, 'rb') as f:
            image_field = ResizedImageField()
            new_image = image_field.clean(None, initial=f)

            tools.assert_not_equals(None, new_image)
示例#27
0
    def test_saving_base_publishable_does_not_update_content_type(self):
        publishable_ct = ContentType.objects.get_for_model(Publishable)
        current_ct = self.publishable.content_type
        tools.assert_not_equals(publishable_ct, current_ct)

        p = Publishable.objects.get(pk=self.publishable.pk)
        p.save()
        tools.assert_equals(current_ct, p.content_type)
示例#28
0
 def test_inequality(self):
     layer01 = TransportLayer()
     layer02 = TransportLayer()
     layer01.source.add('1-2')
     assert_not_equals(layer01, layer02)
     layer02.source.add('1-2')
     layer01.destination.add('1-2')
     assert_not_equals(layer01, layer02)
示例#29
0
 def test_on_the_fly_creation(self):
     """Création d'une instance de ConfFile à la volée."""
     # On ne doit pas créer de nouvelle instance s'il en existe déjà une.
     instance = self.klass.get_or_create(self.attrs['name'])
     assert_equals(instance, self.obj)
     # On doit par contre en créer une nouvelle sinon.
     instance2 = self.klass.get_or_create('copy-' + self.attrs['name'])
     assert_not_equals(instance, instance2)
     assert_equals(instance2.name, 'copy-' + self.attrs['name'])
示例#30
0
def test_mail_content_html():
    """Test steps for checking HTML email content."""

    status, out = run_scenario('leaves', 'content', 3)
    assert_equals(status, 0, out)

    status, out = run_scenario('leaves', 'content', 6)
    assert_not_equals(status, 0)
    assert_in("No email contained the HTML", out)
示例#31
0
def test_model_existence_check():
    'Model existence is checked through Lettuce steps'

    def run_scenario(scenario):
        return commands.getstatusoutput(
            "python manage.py harvest -v 3 -T " +
            "leaves/features/existence.feature -s %d" % scenario)

    FileSystem.pushd(current_directory, "django", "dill")

    status, out = run_scenario(1)
    assert_equals(status, 0, out)

    status, out = run_scenario(2)
    assert_not_equals(status, 0)
    assert "Garden does not exist: {u'name': u'Botanic Gardens'}" in out
    gardens = "\n".join([
        "Rows in DB are:",
        "id=1, name=Secret Garden, area=45, raining=False,",
        "id=2, name=Octopus's Garden, area=120, raining=True,",
        "id=3, name=Covent Garden, area=200, raining=True,",
    ])
    assert gardens in out
    assert "AssertionError: 1 rows missing" in out

    status, out = run_scenario(3)
    assert_not_equals(status, 0)
    assert "Garden does not exist: {u'name': u'Secret Garden', " \
        "u'@howbig': u'huge'}" in out
    gardens = "\n".join([
        "Rows in DB are:",
        "id=1, name=Secret Garden, area=45, raining=False, howbig=small,",
        "id=2, name=Octopus's Garden, area=120, raining=True, howbig=medium,",
        "id=3, name=Covent Garden, area=200, raining=True, howbig=big,",
    ])
    assert gardens in out
    assert "AssertionError: 1 rows missing" in out

    status, out = run_scenario(4)
    assert_not_equals(status, 0)
    assert "Expected 2 geese, found 1" in out

    FileSystem.popd()
示例#32
0
def test_multi_roster_nfl():
    players = salary_download.generate_players_from_csvs(
        salary_file_location=salary_file,
        projection_file_location=projection_file,
        game=rules.DRAFT_KINGS,
    )
    roster = run(
        rule_set=rules.DK_NFL_RULE_SET,
        player_pool=players,
    )
    second_roster = run(
        rule_set=rules.DK_NFL_RULE_SET,
        player_pool=players,
        optimizer_settings=OptimizerSettings(existing_rosters=[roster], ),
    )

    ntools.assert_not_equals(roster, None)
    ntools.assert_not_equals(second_roster, None)
    ntools.assert_not_equals(roster == second_roster, True)
def test_timeout(connpath):
    vehicle = connect(connpath, wait_ready=True)

    # NOTE these are *very inappropriate settings*
    # to make on a real vehicle. They are leveraged
    # exclusively for simulation. Take heed!!!
    vehicle.parameters['ARMING_CHECK'] = 0

    # ARM
    vehicle.armed = True
    i = 60
    while not vehicle.armed and i > 0:
        time.sleep(1)
        i = i - 1

    # Await attributes
    time.sleep(3)
    
    # .north, .east, and .down are initialized to None.
    # Any other value suggests that a LOCAL_POSITION_NED was received and parsed.
    assert_not_equals(vehicle.location.local_frame.north, None)
    assert_not_equals(vehicle.location.local_frame.east, None)
    assert_not_equals(vehicle.location.local_frame.down, None)
示例#34
0
from nose.tools import assert_equals, assert_not_equals, assert_false, assert_true
import lean

lk1 = lean.level_kind.Zero
lk2 = lean.level_kind.Succ

assert_not_equals(lk1, lk2)

l0 = lean.mk_level_zero()
l1 = lean.mk_level_one()
l2 = lean.mk_succ(l1)
l3 = lean.mk_param_univ(lean.name("hello"))
l4 = lean.mk_max(l2, l3)

assert_true(l4.is_max())

assert_false(l4.is_imax())

assert_equals(str(l4.max_lhs()), "2")

assert_equals(str(l4.max_rhs()), "hello")

ln1 = lean.list_level()
ln2 = lean.list_level(lean.mk_param_univ(lean.name("head-of-list")), ln1)

assert_equals(str(ln2.head()), "head-of-list")
assert_true(ln2.tail().is_nil())
示例#35
0
def test_section_2():

    b = [[True, False], [False, True]]
    p = LightsOutPuzzle(b)
    assert_equals(p.get_board(), [[True, False], [False, True]])
    b = [[True, True], [True, True]]
    p = LightsOutPuzzle(b)
    assert_equals(p.get_board(), [[True, True], [True, True]])

    p = create_puzzle(2, 2)
    assert_equals(p.get_board(), [[False, False], [False, False]])
    p = create_puzzle(2, 3)
    assert_equals(p.get_board(),
                  [[False, False, False], [False, False, False]])

    p = create_puzzle(3, 3)
    p.perform_move(1, 1)
    assert_equals(
        p.get_board(),
        [[False, True, False], [True, True, True], [False, True, False]])
    p = create_puzzle(3, 3)
    p.perform_move(0, 0)
    assert_equals(
        p.get_board(),
        [[True, True, False], [True, False, False], [False, False, False]])

    b = [[True, False], [False, True]]
    p = LightsOutPuzzle(b)
    assert_equals(p.is_solved(), False)
    b = [[False, False], [False, False]]
    p = LightsOutPuzzle(b)
    assert_equals(p.is_solved(), True)

    p = create_puzzle(3, 3)
    p2 = p.copy()
    assert_equals(p.get_board(), p2.get_board())
    p = create_puzzle(3, 3)
    p2 = p.copy()
    p.perform_move(1, 1)
    assert_not_equals(p.get_board(), p2.get_board())

    p = create_puzzle(2, 2)
    for move, new_p in p.successors():
        print move, new_p.get_board()
    for i in range(2, 6):
        p = create_puzzle(i, i + 1)
        print len(list(p.successors()))

    p = create_puzzle(2, 3)
    for row in range(2):
        for col in range(3):
            p.perform_move(row, col)
    print(p.find_solution())
    b = [[False, False, False], [False, False, False]]
    b[0][0] = True
    p = LightsOutPuzzle(b)
    print p.find_solution() is None

    p = create_puzzle(3, 3)
    for row in range(3):
        for col in range(3):
            p.perform_move(row, col)
    print(p.find_solution())
示例#36
0
文件: steps.py 项目: menalabib/Ripe
def step_impl(context):
    user = user_collection.find_one(USER_INFO)
    assert_not_equals(user, None)
示例#37
0
def test_timeout(connpath):
    vehicle = connect(connpath, wait_ready=True)

    # NOTE these are *very inappropriate settings*
    # to make on a real vehicle. They are leveraged
    # exclusively for simulation. Take heed!!!
    vehicle.parameters['FS_GCS_ENABLE'] = 0
    vehicle.parameters['FS_EKF_THRESH'] = 100

    def arm_and_takeoff(aTargetAltitude):
        """
        Arms vehicle and fly to aTargetAltitude.
        """

        # Don't let the user try to fly autopilot is booting
        wait_for(lambda: vehicle.is_armable, 60)
        assert_equals(vehicle.is_armable, True)

        # Copter should arm in GUIDED mode
        vehicle.mode = VehicleMode("GUIDED")
        wait_for(lambda: vehicle.mode.name == 'GUIDED', 60)
        assert_equals(vehicle.mode.name, 'GUIDED')

        # Arm copter.
        vehicle.armed = True
        wait_for(lambda: vehicle.armed, 60)
        assert_equals(vehicle.armed, True)

        # Take off to target altitude
        vehicle.simple_takeoff(aTargetAltitude)

        # Wait until the vehicle reaches a safe height before
        # processing the goto (otherwise the command after
        # Vehicle.simple_takeoff will execute immediately).
        while True:
            # print " Altitude: ", vehicle.location.alt
            # Test for altitude just below target, in case of undershoot.
            if vehicle.location.global_frame.alt >= aTargetAltitude * 0.95:
                # print "Reached target altitude"
                break

            assert_equals(vehicle.mode.name, 'GUIDED')
            time.sleep(1)

    arm_and_takeoff(10)
    vehicle.wait_ready('location.local_frame', timeout=60)

    # .north, .east, and .down are initialized to None.
    # Any other value suggests that a LOCAL_POSITION_NED was received and parsed.
    assert_not_equals(vehicle.location.local_frame.north, None)
    assert_not_equals(vehicle.location.local_frame.east, None)
    assert_not_equals(vehicle.location.local_frame.down, None)

    # global_frame
    assert_not_equals(vehicle.location.global_frame.lat, None)
    assert_not_equals(vehicle.location.global_frame.lon, None)
    assert_not_equals(vehicle.location.global_frame.alt, None)
    assert_equals(type(vehicle.location.global_frame.lat), float)
    assert_equals(type(vehicle.location.global_frame.lon), float)
    assert_equals(type(vehicle.location.global_frame.alt), float)

    vehicle.close()
示例#38
0
def test_grid_inequality():
    g1 = Grid(4, 4)
    g2 = Grid(3, 4)
    assert_not_equals(g1, g2)
示例#39
0
 def assert_inode_not_equal(self, a, b):
     nt.assert_not_equals(
         os.stat(a).st_ino,
         os.stat(b).st_ino,
         "%r and %r do reference the same indoes" % (a, b))
示例#40
0
 def test_create(self):
     efd = eventfd.EventFD()
     tools.assert_not_equals(efd, None)
def test_section_4():

    # Getter
    b = [[False, False], [False, False]]
    g = DominoesGame(b)
    assert_equals(g.get_board(), [[False, False], [False, False]])
    b = [[True, False], [True, False]]
    g = DominoesGame(b)
    assert_equals(g.get_board(), [[True, False], [True, False]])

    # Create game
    g = create_dominoes_game(2, 2)
    assert_equals(g.get_board(), [[False, False], [False, False]])
    g = create_dominoes_game(2, 3)
    assert_equals(g.get_board(),
                  [[False, False, False], [False, False, False]])

    # Reset
    b = [[False, False], [False, False]]
    g = DominoesGame(b)
    g.reset()
    assert_equals(g.get_board(), [[False, False], [False, False]])
    b = [[True, False], [True, False]]
    g = DominoesGame(b)
    g.reset()
    assert_equals(g.get_board(), [[False, False], [False, False]])

    # Legal move
    b = [[False, False], [False, False]]
    g = DominoesGame(b)
    assert_equals(g.is_legal_move(0, 0, True), True)
    assert_equals(g.is_legal_move(0, 0, False), True)
    b = [[True, False], [True, False]]
    g = DominoesGame(b)
    assert_equals(g.is_legal_move(0, 0, False), False)
    assert_equals(g.is_legal_move(0, 1, True), True)
    assert_equals(g.is_legal_move(1, 1, True), False)

    # Legal moves
    g = create_dominoes_game(3, 3)
    assert_equals(list(g.legal_moves(True)), [(0, 0), (0, 1), (0, 2), (1, 0),
                                              (1, 1), (1, 2)])
    assert_equals(list(g.legal_moves(False)), [(0, 0), (0, 1), (1, 0), (1, 1),
                                               (2, 0), (2, 1)])
    b = [[True, False], [True, False]]
    g = DominoesGame(b)
    assert_equals(list(g.legal_moves(True)), [(0, 1)])
    assert_equals(list(g.legal_moves(False)), [])

    # Perform move
    g = create_dominoes_game(3, 3)
    g.perform_move(0, 1, True)
    assert_equals(
        g.get_board(),
        [[False, True, False], [False, True, False], [False, False, False]])
    g = create_dominoes_game(3, 3)
    g.perform_move(1, 0, False)
    assert_equals(
        g.get_board(),
        [[False, False, False], [True, True, False], [False, False, False]])

    # Game over
    b = [[False, False], [False, False]]
    g = DominoesGame(b)
    assert_equals(g.game_over(True), False)
    assert_equals(g.game_over(False), False)
    b = [[True, False], [True, False]]
    g = DominoesGame(b)
    assert_equals(g.game_over(True), False)
    assert_equals(g.game_over(False), True)

    # Copy
    g = create_dominoes_game(4, 4)
    g2 = g.copy()
    assert_equals(g.get_board(), g2.get_board())
    g = create_dominoes_game(4, 4)
    g2 = g.copy()
    g.perform_move(0, 0, True)
    assert_not_equals(g.get_board(), g2.get_board())

    # Successors
    b = [[False, False], [False, False]]
    g = DominoesGame(b)
    for m, new_g in g.successors(True):
        print m, new_g.get_board()
    print("#############################")
    b = [[True, False], [True, False]]
    g = DominoesGame(b)
    for m, new_g in g.successors(True):
        print m, new_g.get_board()

    b = [[False] * 3 for i in range(3)]
    g = DominoesGame(b)
    assert_equals(g.get_best_move(True, 1), ((0, 1), 2, 6))
    assert_equals(g.get_best_move(True, 2), ((0, 1), 3, 10))
    b = [[False] * 3 for i in range(3)]
    g = DominoesGame(b)
    g.perform_move(0, 1, True)
    assert_equals(g.get_best_move(False, 1), ((2, 0), -3, 2))
    assert_equals(g.get_best_move(False, 2), ((2, 0), -2, 5))
 def test_multiple_connections(self):
     pool = self.get_pool()
     c1 = pool.get_connection('_')
     c2 = pool.get_connection('_')
     c3 = pool.get_connection('_')
     c4 = pool.get_connection('_')
     assert_not_equals(c1, c2)
     assert_not_equals(c1, c3)
     assert_not_equals(c1, c4)
     assert_not_equals(c2, c3)
     assert_not_equals(c2, c4)
     assert_not_equals(c3, c4)
示例#43
0
import lean

n0 = lean.name()
n1 = lean.name("hello")
n2 = lean.name(n1, "goodbye")
n3 = lean.name(n2, 5)

assert_equals(str(n3), "hello.goodbye.5")

d = {n3 : 4, n2 : 7}

assert_equals(d[n3], 4)

assert_equals(d[n2], 7)

assert_not_equals(n2, n3)

assert_equals(lean.name(n2, 5), n3)

def name_to_list(n):
    l = []
    while not n.is_anonymous():
        if n.is_string():
            l.insert(0, n.get_string())
        elif n.is_numeral():
            l.insert(0, n.get_numeral())
        n = n.get_prefix()
    return l

assert_equals(name_to_list(n3), ["hello", "goodbye", 5])
def test_multi_roster():
    args = Namespace(**args_dict)
    roster = run(NFL, args)
    second_roster = run(NFL, args, [roster])
    ntools.assert_not_equals(roster == second_roster, True)
示例#45
0
def test_equality():
    assert_equals(Location('tag', 'org', 'course', 'category', 'name'),
                  Location('tag', 'org', 'course', 'category', 'name'))

    assert_not_equals(Location('tag', 'org', 'course', 'category', 'name1'),
                      Location('tag', 'org', 'course', 'category', 'name'))
示例#46
0
 def should_be_succesfull(self):
     assert_not_equals(0, self.exit_code)
示例#47
0
def test_model_existence_check():
    'Model existence is checked through Lettuce steps'

    status, out = run_scenario('leaves', 'existence', 1)
    assert_equals(status, 0, out)

    # One of the gardens has a non-ASCII name. On Python 2 under Django >= 1.9,
    # it gets output by Nose using the escapes.
    garden4 = '颐和园'
    if not PY3 and django.VERSION >= (1, 9):
        garden4 = garden4.encode('unicode_escape')

    status, out = run_scenario('leaves', 'existence', 2)
    assert_not_equals(status, 0)
    assert_in(
        "Garden does not exist: {0}".format(
            {'name': 'Botanic Gardens'}
        ),
        out
    )
    gardens = "\n".join([
        "Rows in DB are:",
        "id=1, name=Secret Garden, area=45, raining=False",
        "id=2, name=Octopus's Garden, area=120, raining=True",
        "id=3, name=Covent Garden, area=200, raining=True",
        "id=4, name={}, area=500, raining=False".format(garden4),
    ])

    assert_in(gardens, out)
    assert_in("AssertionError: 1 rows missing", out)

    status, out = run_scenario('leaves', 'existence', 3)
    assert_not_equals(status, 0)
    # Cannot check exact string because the order isn't stable
    assert_in("Garden does not exist: ", out)
    assert_in(str({'name': 'Secret Garden'})[1:-1], out)
    assert_in(str({'@howbig': 'huge'})[1:-1], out)
    gardens = "\n".join([
        "Rows in DB are:",
        "id=1, name=Secret Garden, area=45, raining=False, howbig=small",
        "id=2, name=Octopus's Garden, area=120, raining=True, howbig=medium",
        "id=3, name=Covent Garden, area=200, raining=True, howbig=big",
        "id=4, name={}, area=500, raining=False, howbig=big".format(garden4),
    ])
    assert_in(gardens, out)
    assert_in("AssertionError: 1 rows missing", out)

    status, out = run_scenario('leaves', 'existence', 4)
    assert_not_equals(status, 0)
    assert_in("Expected 2 geese, found 1", out)

    status, out = run_scenario('leaves', 'existence', 5)
    assert_not_equals(status, 0)
    # Cannot check exact string because the order isn't stable
    assert_in("Garden exists: ", out)
    assert_in(str({'name': 'Secret Garden'})[1:-1], out)
    assert_in(str({'@howbig': 'small'})[1:-1], out)
    assert_in("AssertionError: 1 rows found", out)
    gardens = "\n".join([
        "Rows in DB are:",
        "id=1, name=Secret Garden, area=45, raining=False, howbig=small",
        "id=2, name=Octopus's Garden, area=120, raining=True, howbig=medium",
        "id=3, name=Covent Garden, area=200, raining=True, howbig=big",
        "id=4, name={}, area=500, raining=False, howbig=big".format(garden4),
    ])
    assert_in(gardens, out)
示例#48
0
文件: asserts.py 项目: altai/bunch
def assert_matches(text, regexp, msg=None):
    regexp = re.compile(regexp)
    msg = msg or "Regexp didn't match"
    msg = '%s: %r not found in %r' % (msg, regexp.pattern, text)
    assert_not_equals(regexp.search(text), None, msg)
示例#49
0
 def test_pin_assignment_iffy_values(self):
     self.pin.value = 0.9
     assert_not_equals(self.pin.value, 0.9)
     self.pin.value = 1.1
     assert_not_equals(self.pin.value, 1.1)
示例#50
0
def test_nba_fd():
    roster = run(
        rule_set=rules.FD_NBA_RULE_SET,
        player_pool=mock_player_pool,
    )
    ntools.assert_not_equals(roster, None)
def test_section_1():

    # Getter
    p = TilePuzzle([[1, 2], [3, 0]])
    assert_equals(p.get_board(), [[1, 2], [3, 0]])
    assert_equals(p.empty_space, [1, 1])
    p = TilePuzzle([[0, 1], [3, 2]])
    assert_equals(p.get_board(), [[0, 1], [3, 2]])
    assert_equals(p.empty_space, [0, 0])

    # Create puzzles
    p = create_tile_puzzle(3, 3)
    assert_equals(p.get_board(), [[1, 2, 3], [4, 5, 6], [7, 8, 0]])
    assert_equals(p.empty_space, [2, 2])
    p = create_tile_puzzle(2, 4)
    assert_equals(p.get_board(), [[1, 2, 3, 4], [5, 6, 7, 0]])
    assert_equals(p.empty_space, [1, 3])

    # Perform move
    p = create_tile_puzzle(3, 3)
    assert_equals(p.perform_move("up"), True)
    assert_equals(p.get_board(), [[1, 2, 3], [4, 5, 0], [7, 8, 6]])
    p = create_tile_puzzle(3, 3)
    assert_equals(p.perform_move("down"), False)
    assert_equals(p.get_board(), [[1, 2, 3], [4, 5, 6], [7, 8, 0]])

    # Is solved
    p = TilePuzzle([[1, 2], [3, 0]])
    assert_equals(p.is_solved(), True)
    p = TilePuzzle([[0, 1], [3, 2]])
    assert_equals(p.is_solved(), False)

    # Copy
    p = create_tile_puzzle(3, 3)
    p2 = p.copy()
    assert_equals(p.get_board(), p2.get_board())
    p = create_tile_puzzle(3, 3)
    p2 = p.copy()
    p.perform_move("left")
    assert_not_equals(p.get_board(), p2.get_board())

    # Successors
    print("\n ### Successors ### \n")
    p = create_tile_puzzle(3, 3)
    for move, new_p in p.successors():
        print move, new_p.get_board()

    print("\n ################## \n")

    b = [[1, 2, 3], [4, 0, 5], [6, 7, 8]]
    p = TilePuzzle(b)
    for move, new_p in p.successors():
        print move, new_p.get_board()

    print("\n ################## \n")

    # Iterative Deepening Search
    p = create_tile_puzzle(3, 3)
    solutions = p.find_solutions_iddfs()
    assert_equals(list(solutions), [[]])

    b = [[4, 1, 2], [0, 5, 3], [7, 8, 6]]
    p = TilePuzzle(b)
    solutions = p.find_solutions_iddfs()
    assert_equals(next(solutions), ['up', 'right', 'right', 'down', 'down'])

    b = [[1, 2, 3], [4, 0, 8], [7, 6, 5]]
    p = TilePuzzle(b)
    solutions = p.find_solutions_iddfs()
    assert_equals(list(p.find_solutions_iddfs()),
                  [['down', 'right', 'up', 'left', 'down', 'right'],
                   ['right', 'down', 'left', 'up', 'right', 'down']])

    # A Star Search
    b = [[4, 1, 2], [0, 5, 3], [7, 8, 6]]
    p = TilePuzzle(b)
    assert_equals(p.find_solution_a_star(),
                  ['up', 'right', 'right', 'down', 'down'])
    b = [[1, 2, 3], [4, 0, 5], [6, 7, 8]]
    p = TilePuzzle(b)
    assert_equals(p.find_solution_a_star(), [
        'right', 'down', 'left', 'left', 'up', 'right', 'down', 'right', 'up',
        'left', 'left', 'down', 'right', 'right'
    ])
def test_osx():
    nt.assert_not_equals(sys.platform, 'darwin',
                         "This test can't run under osx")
示例#53
0
def test_timestamp_position_type():
    assert_equals(timestamp_position_type("north"), TimestampPosition.north)

    assert_not_equals(timestamp_position_type("south"), TimestampPosition.north)

    assert_raises(ArgumentTypeError, timestamp_position_type, "whatever")
示例#54
0
 def callback(*args):
     assert_not_equals(args[2].alt, 0)
     ret['success'] = True
def test_win32():
    nt.assert_not_equals(sys.platform, 'win32',
                         "This test can't run under windows")
示例#56
0
def test_parameter(connpath):
    vehicle = connect(connpath, wait_ready=True)

    # Home should be None at first.
    assert_equals(vehicle.home_location, None)

    # Wait for home position to be real and not 0, 0, 0
    # once we request it via cmds.download()
    time.sleep(10)

    # Initial
    vehicle.commands.download()
    vehicle.commands.wait_ready()
    assert_equals(len(vehicle.commands), 0)
    assert_not_equals(vehicle.home_location, None)

    # Save home for comparison.
    home = vehicle.home_location

    # After clearing
    vehicle.commands.clear()
    vehicle.commands.upload()
    vehicle.commands.download()
    vehicle.commands.wait_ready()
    assert_equals(len(vehicle.commands), 0)

    # Upload
    for command in [
            Command(0, 0, 0, 0, 16, 1, 1, 0.0, 0.0, 0.0, 0.0, -35.3605,
                    149.172363, 747.0),
            Command(0, 0, 0, 3, 22, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.359831,
                    149.166334, 100.0),
            Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.363489,
                    149.167213, 100.0),
            Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.355491,
                    149.169595, 100.0),
            Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.355071,
                    149.175839, 100.0),
            Command(0, 0, 0, 3, 113, 0, 1, 0.0, 0.0, 0.0, 0.0, -35.362666,
                    149.178715, 22222.0),
            Command(0, 0, 0, 3, 115, 0, 1, 2.0, 22.0, 1.0, 3.0, 0.0, 0.0, 0.0),
            Command(0, 0, 0, 3, 16, 0, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
    ]:
        vehicle.commands.add(command)
    vehicle.commands.upload()

    # After upload
    vehicle.commands.download()
    vehicle.commands.wait_ready()
    assert_equals(len(vehicle.commands), 8)

    # Test iteration.
    count = 0
    for cmd in vehicle.commands:
        assert_not_equals(cmd, None)
        count += 1
    assert_equals(count, 8)

    # Test slicing
    count = 3
    for cmd in vehicle.commands[2:5]:
        assert_not_equals(cmd, None)
        assert_equals(cmd.seq, count)
        count += 1
    assert_equals(count, 6)

    # Test next property
    assert_equals(vehicle.commands.next, 0)
    vehicle.commands.next = 3
    while vehicle.commands.next != 3:
        time.sleep(0.1)
    assert_equals(vehicle.commands.next, 3)

    # Home should be preserved
    assert_equals(home.lat, vehicle.home_location.lat)
    assert_equals(home.lon, vehicle.home_location.lon)
    assert_equals(home.alt, vehicle.home_location.alt)

    vehicle.close()
示例#57
0
 def test_xlinter(self):
     '''
     Run through the xlinter, we know the 'toy' course has violations, but the
     number will continue to grow over time, so just check > 0
     '''
     assert_not_equals(perform_xlint(DATA_DIR, ['toy']), 0)
示例#58
0
def test_vehicle_mode_neq():
    assert_not_equals(VehicleMode('AUTO'), VehicleMode('GUIDED'))
示例#59
0
 def test_actually_stored(self):
     m = self.m
     m.store()
     m[0].A.map['values'][0] += 13.33
     m1 = m.spectrum.models.a.restore()
     nt.assert_not_equals(m[0].A.map['values'], m1[0].A.map['values'])
示例#60
0
def test_linux():
    nt.assert_not_equals(sys.platform,'linux2',"This test can't run under linux")