Ejemplo n.º 1
0
    def test_ballot_measures_extra(self):
        with test_database(test_db, [Race,]):
            data.load_races('data/tests/init_races.json')
            data.load_ballot_measures_extra('data/ballot-measures-extra.csv', quiet=True)

            race = Race.get(Race.race_id == '27456-MO')
            self.assertEqual(race.ballot_measure_description, 'Teacher performance evaluation (Amendment 3)')
Ejemplo n.º 2
0
    def test_handle(self, bot, test_db, tguser, updater, update, gratitude_states):
        """Test the handle that collects records from the user."""
        with test_database(test_db, [User, Record, Job], fail_silently=True):
            user, created = User.tg_get_or_create(tguser)
            user.active_coach = Gratitude.NAME
            user.state = gratitude_states[0]

            if user.state == Gratitude.AWAITING_REASONS:
                # If no gratitude exists, no reaction can be recorded
                if len(gratitude_states[1]) == 0:
                    return

                # Last gratitude must always miss the reaction in 2nd state
                gratitude_states[1][-1].reaction = None

            with test_db.transaction():
                for g in gratitude_states[1]:
                    g.save()
                user.save()

            g = Gratitude(bot, test_db, tguser, updater.job_queue)
            g.handle(update)

            # Reload from disk
            g = Gratitude(bot, test_db, tguser, updater.job_queue)
            user = User.get(User.id == g.user.id)

            if user.state == Gratitude.AWAITING_GRATITUDE:
                if len(gratitude_states[1]) < 3:
                    assert len(g.collector) == len(gratitude_states[1]) + 1
 def test_logout_page(self):
     """Test for a 200 status code from our logout route"""
     with test_database(self.TEST_DB, (User,)):
         rv = self.app.get('/logout')
         self.assertEqual(rv.status_code, 302)
         with self.app.session_transaction() as sess:
             assert 'user_id' not in sess
Ejemplo n.º 4
0
 def test_change_password(self):
     with test_database(TEST_DB, (Users,)):
         self.create_user()
         self.login('root', 'password')
         rv = self.change_password('password', 'Pa55_WorD2', 'Pa55_WorD2')
         self.assertEqual(rv.status_code, 302)
         self.assertEqual(rv.location, 'http://localhost/my-profile')
Ejemplo n.º 5
0
    def test_senate_extra(self):
        with test_database(test_db, [Race,]):
            data.load_races('data/tests/init_races.json')
            data.load_senate_extra('data/senate-extra.csv', quiet=True)

            race = Race.get(Race.race_id == '38145-OK')
            self.assertEqual(race.previous_party, 'gop')
Ejemplo n.º 6
0
    def test_update_results(self):
        with test_database(test_db, [Race, Candidate]):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')
            data.load_updates('data/tests/update.json')
            race = Race.get(Race.race_id == '38529-OR')

            candidate_4848 = Candidate.get(Candidate.candidate_id == '4848-OR')
            candidate_4642 = Candidate.get(Candidate.candidate_id == '4642-OR')
            candidate_4979 = Candidate.get(Candidate.candidate_id == '4979-OR')

            self.assertEqual(race.precincts_reporting, 1970)
            self.assertEqual(race.precincts_total, 2288)
            self.assertTrue(race.is_reporting())

            self.assertEqual(candidate_4848.vote_count, 150000)
            self.assertEqual(candidate_4642.vote_count, 200000)
            self.assertEqual(candidate_4979.vote_count, 250000)
            self.assertEqual(race.count_votes(), 600000)

            self.assertEqual(candidate_4848.vote_percent(), Decimal('25.0')) 
            self.assertAlmostEqual(candidate_4642.vote_percent(), Decimal('33.333'), 3) 
            self.assertAlmostEqual(candidate_4979.vote_percent(), Decimal('41.667'), 3) 

            # Results does not call races
            self.assertFalse(candidate_4848.ap_winner)
            self.assertFalse(candidate_4642.ap_winner)
            self.assertFalse(candidate_4979.ap_winner)
Ejemplo n.º 7
0
 def test_admin_required(self):
     with test_database(TEST_DB, (Users,)):
         self.create_user(admin=False)
         self.login('root', 'password')
         self.register_user()
         rv = self.check_admin()
         self.assertEqual(rv.status_code, 401)
Ejemplo n.º 8
0
    def test_check_file_size_needed(self):
        """test that the file size returned from the archive is parsed right"""
        with test_database(SqliteDatabase(':memory:'), (Cart, File)):
            response = """{
                            "bytes_per_level": "(24L, 0L, 0L, 0L, 0L)", 
                            "ctime": "1444938166", 
                            "file": "/myemsl-dev/bundle/file.1", 
                            "file_storage_media": "disk", 
                            "filesize": "24", 
                            "message": "File was found", 
                            "mtime": "1444938166"
                            }"""
            test_cart = Cart.create(cart_uid='1', status="staging")
            test_file = File.create(cart=test_cart, file_name="1.txt",
                                    bundle_path="/tmp/1/1.txt")
            cart_utils = Cartutils()
            file_size = cart_utils.check_file_size_needed(response, test_file,
                                                          test_cart)
            self.assertEqual(file_size, 24)
            self.assertNotEqual(test_file.status, "error")

            #now check for an error by sending a bad response
            file_size = cart_utils.check_file_size_needed("", test_file,
                                                          test_cart)
            self.assertEqual(file_size, -1)
            self.assertEqual(test_file.status, "error")
Ejemplo n.º 9
0
 def test_rendering(self):
     """レンダリングが正常に完了していること
     """
     index = self.getOne()
     with test_database(test_db, (Greeting,)):
         html = index()
     self.assertTrue(len(html) > 0)
Ejemplo n.º 10
0
 def test_load_success(self):
     """呼び出しが正常に完了して、結果が空になること
     """
     with test_database(test_db, (Greeting,)):
         load_data = self.getOne()
         greeting_list = list(load_data())
         self.assertEqual(greeting_list, [])
Ejemplo n.º 11
0
 def test_my_profile(self):
     with test_database(TEST_DB, (Users,)):
         self.create_user()
         self.login('root', 'password')
         rv = self.app.get('/my-profile')
         self.assertEqual(rv.status_code, 200)
         self.assertIn("update profile" , rv.get_data(as_text=True).lower())
Ejemplo n.º 12
0
 def raise_exc():
     with test_database(db2, (Data, DataItem), create_tables=False):
         self.assertUsing('db2')
         Data.create_table()
         c = Data.create(key='c')
         # This will raise Data.DoesNotExist.
         Data.get(Data.key == 'a')
Ejemplo n.º 13
0
 def test_logged_in_menu(self):
     with test_database(TEST_DB, (User,)):
         UserModelTestCase.create_users(1)
         self.app.post('/login', data=USER_DATA)
         rv = self.app.get('/')
         self.assertIn("add a new taco", rv.get_data(as_text=True).lower())
         self.assertIn("log out", rv.get_data(as_text=True).lower())
Ejemplo n.º 14
0
 def test_registration(self):
     with test_database(TEST_DB, (Users,)):
         self.create_user()
         self.login('root', 'password')
         rv = self.register_user()
         self.assertEqual(rv.status_code, 200)
         self.assertIn("user has been created.", rv.get_data(as_text=True).lower())
 def test_bad_username(self):
     """Test username error through our POST route"""
     self.data['username'] = '******'
     with test_database(self.TEST_DB, (User,)):
         rv = self.app.post('/register', data=self.data)
         self.assertEqual(User.select().count(), 0)
         self.assertEqual(rv.status_code, 200)
 def test_bad_email(self):
     """Test email error through our POST route"""
     self.data['email'] = 'noatsymbolordomain'
     with test_database(self.TEST_DB, (User,)):
         rv = self.app.post('/register', data=self.data)
         self.assertEqual(User.select().count(), 0)
         self.assertEqual(rv.status_code, 200)
Ejemplo n.º 17
0
 def test_logout(self):
     with test_database(TEST_DB, (Users,)):
         self.create_user()
         self.login('root', 'password')
         rv = self.app.get('/logout')
         self.assertEqual(rv.status_code, 302)
         self.assertEqual(rv.location, 'http://localhost/login')
Ejemplo n.º 18
0
 def test_post_todo_unauthorized(self):
     data = {
         'name': 'Feed the dog',
     }
     with test_database(TEST_DB, (models.User, models.Todo)):
         rv = self.app.post('/api/v1/todos', data=data)
         self.assertEqual(rv.status_code, 401)
 def test_login_page(self):
     """Test for a 200 status code from our registration's GET route"""
     with test_database(self.TEST_DB, (User,)):
         rv = self.app.get('/login')
         self.assertIn("username", rv.get_data(as_text=True).lower())
         self.assertIn("password", rv.get_data(as_text=True).lower())
         self.assertEqual(rv.status_code, 200)   
Ejemplo n.º 20
0
 def test_set_admin(self):
     with test_database(TEST_DB, (Users,)):
         self.create_user()
         self.login('root', 'password')
         self.register_user()
         rv = self.set_user_admin(id=2)
         self.assertIn("user is now an admin." , rv.get_data(as_text=True).lower())
Ejemplo n.º 21
0
 def test_get_counters_returns_correct_values(self):
     """Correct counter values are returned from the database."""
     with test_database(self.db, [Counter], create_tables=True):
         for k, v in self.test_counters.items():
             Counter.create(name=k, count=v)
         mh = self.message_handler.get_counters()
         self.assertDictEqual(mh['counters'], self.test_counters)
 def test_bad_password_confirmation(self):
     """Test password confirmation error through our POST route"""
     self.data['password2'] = 'notpassword1'
     with test_database(self.TEST_DB, (User,)):
         rv = self.app.post('/register', data=self.data)
         self.assertEqual(User.select().count(), 0)
         self.assertEqual(rv.status_code, 200)
Ejemplo n.º 23
0
def test_user_automatic_join_date():
    with test_database(TEST_DB, [User, Question, Answer]):
        create_data()
        users = User.select().where(User.join_date == datetime.date.today())
        user = users.get()
        assert_equal(users.count(), 2)
        assert_equal(user.join_date, datetime.date.today())
Ejemplo n.º 24
0
    def test_taco_create(self):
        taco_data = {
            'protein': 'chicken',
            'shell': 'flour',
            'cheese': False,
            'extras': 'Gimme some guac.'
        }
        with test_database(TEST_DB, (User, Taco)):
            UserModelTestCase.create_users(1)
            self.app.post('/login', data=USER_DATA)

            taco_data['user'] = User.select().get()
            rv = self.app.post('/taco', data=taco_data)
            self.assertEqual(rv.status_code, 302)
            self.assertEqual(rv.location, 'http://localhost/')
            self.assertEqual(Taco.select().count(), 1)

        def test_taco_list(self):
            taco_data = {
                'protein': 'chicken',
                'shell': 'flour',
                'cheese': False,
                'extras': 'Gimme some guac.'
            }
            with test_database(TEST_DB, (User, Taco)):
                UserModelTestCase.create_users(1)
                taco_data['user'] = User.select().get()
                Taco.create(**taco_data)

                rv = self.app.get('/')
                self.assertNotIn('no tacos yet', rv.get_data(as_text=True))
                self.assertIn(taco_data['extras'], rv.get_data(as_text=True))
Ejemplo n.º 25
0
 def test_edit_entry(self):
     with test_database(TEST_DB, (work_log.Entry,)):
         entry = work_log.Entry.create(**ENTRIES[0])
         with unittest.mock.patch('builtins.input',
                                  side_effect=["u", "Tatiana"]):
             work_log.edit_entry(entry=entry)
             self.assertEqual(entry.name, "Tatiana")
         with unittest.mock.patch('builtins.input',
                                  side_effect=["t", "10 m"]):
             work_log.edit_entry(entry=entry)
             self.assertEqual(entry.time_spent, 10)
         with unittest.mock.patch('builtins.input',
                                  side_effect=["o"]):
             with unittest.mock.patch('sys.stdin.read',
                                      return_value="hard work"):
                 work_log.edit_entry(entry=entry)
                 self.assertEqual(entry.notes, "hard work")
         with unittest.mock.patch('builtins.input',
                                  side_effect=["d", "22.06.2016"]):
             work_log.edit_entry(entry=entry)
             self.assertEqual(entry.date, datetime.date(2016, 6, 22))
         with unittest.mock.patch('builtins.input',
                                  side_effect=["p", "Project"]):
             work_log.edit_entry(entry=entry)
             self.assertEqual(entry.project, "Project")
         with unittest.mock.patch('builtins.input',
                                  side_effect=["n", "Task"]):
             work_log.edit_entry(entry=entry)
             self.assertEqual(entry.task_name, "Task")
    def test_index_update(self):
        """
        test return and update of unique index
        """
        with test_database(SqliteDatabase(':memory:'), [UniqueIndex]):
            test_object = UniqueIndex.create(idid='file', index=892)
            self.assertEqual(test_object.idid, 'file')

            index, index_range = update_index(10, 'file')
            self.assertEqual(index, 892)
            self.assertEqual(index_range, 10)

            index, index_range = update_index(10, 'file')
            self.assertEqual(index, 902)
            self.assertEqual(index_range, 10)

            index, index_range = update_index(10, 'new')
            self.assertEqual(index, 0)
            self.assertEqual(index_range, 10)

            index, index_range = update_index(10, 'new')
            self.assertEqual(index, 10)
            self.assertEqual(index_range, 10)

            index, index_range = update_index(None, 'new')
            self.assertEqual(index, -1)
            self.assertEqual(index_range, -1)

            index, index_range = update_index(2, None)
            self.assertEqual(index, -1)
            self.assertEqual(index_range, -1)

            index, index_range = update_index(-5, 'new')
            self.assertEqual(index, -1)
            self.assertEqual(index_range, -1)
Ejemplo n.º 27
0
def test_question_creation():
    with test_database(TEST_DB, [User, Question, Answer]):
        create_data()
        questions = Question.select()
        question = questions.where(Question.text == 'text_0_0').get()
        assert_equal(questions.count(), 4)
        assert_equal(question.user.email, '*****@*****.**')
Ejemplo n.º 28
0
    def test_creating_article(self):

        with test_database(db, (Users, Articles)):
            user1 = Users.create_user(username = "******", password = "******")
            article = Articles.create_article(title = "test",\
                                    body = "test",\
                                    draft = True,\
                                    author = user1)

            self.assertEquals("test", article.title)
            self.assertEquals("konrad",article.author.username)

            Articles.create_article(title = "test2",\
                                   body = "test",\
                                   draft = False, \
                                   author = user1)

            self.assertRaises(IntegrityError,\
                              lambda: Articles.create_article(title = "test",\
                                                              body = "test",\
                                                              author = user1))

            articles = Articles.get_user_articles("konrad")

            self.assertEquals(2,len(tuple(articles)))

            user2 = Users.create_user(username = "******", password = "******")
            Articles.create_article(title = "test3", \
                                   body = "test",\
                                   author = user2)

            articles = Articles.get_user_articles("konrad")
            self.assertEquals(2,len(tuple(articles)))
            articles2 = Articles.get_user_articles("malgosia")
            self.assertEquals(1,len(tuple(articles2)))
Ejemplo n.º 29
0
 def test_get_todos(self):
     with test_database(TEST_DB, (Todo,)):
         self.create_todos()
         rv = self.app.get('/api/v1/todos')
         self.assertEqual(rv.status_code, 200)
         self.assertEqual(Todo.select().count(), 3)
         self.assertIn('Study', rv.get_data(as_text=True))
Ejemplo n.º 30
0
 def test_create_student(self):
     with test_database(TEST_DB, (Student,)):
         self.create_students(),
         self.assertEqual(Student.select().count(), 2)
         self.assertNotEqual(
             Student.select().get().password, 'password'
         )
    def test_search_entries(self):
        with test_database(TEST_DB, (Entry,)):
            self.create_entries()
            with mock.patch('builtins.input', side_effect=["a", "Mike", "e"]):
                self.assertTrue(worklog_db.search_entries())

            with mock.patch('builtins.input', side_effect=["b", "2017-07-12", "e"]):
                self.assertTrue(worklog_db.search_entries())

            with mock.patch('builtins.input', side_effect=["c", 13, "e"]):
                self.assertTrue(worklog_db.search_entries())

            with mock.patch('builtins.input',side_effect=["a", ".", "y", "e"]):
                self.assertEqual(worklog_db.search_entries(), None)

            with mock.patch('builtins.input', side_effect=["d", "Servicing Bikes", "e"]):
                self.assertTrue(worklog_db.search_entries())
 def test_sort_locations_by_datetime(self):
     """
     Test that position numbers are re-assigned according to datetime sort order.
     Updates not written to test database.
     """
     n_expected = len(self.expected_position_assignments)
     with test_database(self.test_db, self.test_tables):
         self._load_up_test_location_data()
         locations = FishingLocations.select()
         self.assertEqual(n_expected, len(locations))
         # ----
         sorted_locations = ObserverFishingLocations._resequence_orm_location_positions(locations)
         # ----
         self.assertEqual(n_expected, len(sorted_locations))
         for sloc in sorted_locations:
             print("{0} {1} ({2:0>5})".format(sloc.position, sloc.location_date, sloc.fishing_location))
             self.assertEqual(self.expected_position_assignments[sloc.fishing_location], sloc.position)
Ejemplo n.º 33
0
    def test_diary_entry(self, bot, test_db, tguser, updater):
        """Test diary entry from main menu."""
        diary_entry = "My secret diary."

        with test_database(test_db, [User, Record], fail_silently=True):
            with db.transaction():
                user, created = User.tg_get_or_create(tguser)
                user.state = Menu.AWAITING_DIARY_ENTRY
                user.save()

            coach = Menu(bot, db, tguser, updater.job_queue)
            msgs = coach.handle(custom_update(msg=diary_entry))

            assert len(msgs) == 1

            rec = Record.get(Record.content == diary_entry)
            assert isinstance(rec, Record)
Ejemplo n.º 34
0
 def test_job_subcommand(self):
     """Test the job subcommand for updating job state."""
     rwfd, fname = mkstemp()
     os.close(rwfd)
     with test_database(SqliteDatabase(fname), (BaseModel, IngestState)):
         IngestState.create(job_id=999,
                            state='ERROR',
                            task='unbundling',
                            task_percent=42.3)
         IngestState.database_close()
         cmd([
             'job', '--task=unbundling', '--job-id=999', '--state=OK',
             '--task-percent=100.0', '--exception=Badness'
         ])
         record = read_state(999)
         self.assertEqual(record.state, 'OK')
         self.assertEqual(record.task_percent, 100.0)
Ejemplo n.º 35
0
    def base_where_clause(self, obj_hash):
        """
        Base where clause checking.

        create a new object from the obj_hash
        save it to the database
        check all keys in obj_hash separately
        query a new object using that key and value in obj_hash
        compare the pulled object hash with obj_hash
        """
        with test_database(SqliteDatabase(':memory:'), self.dependent_cls()):
            obj = self.base_create_obj(self.obj_cls, obj_hash)
            for (key, val) in obj_hash.iteritems():
                chk_obj = self.base_where_clause_search(obj, {key: val})[0]
                chk_obj_hash = chk_obj.to_hash()
                for chkkey in obj_hash.keys():
                    self.assertEqual(chk_obj_hash[chkkey], obj_hash[chkkey])
Ejemplo n.º 36
0
    def test_list_view(self):
        """The list view contains a list of journal entries, which displays Title and Date for Entry."""
        journal_entry_data_1 = {
            'title':
            'testing 1',
            'date':
            datetime.datetime.now().strftime('%Y-%m-%d'),
            'time_spent':
            '4',
            'what_i_learned':
            'how to test flask views',
            'resources_to_remember':
            'teamtreehouse.com, stackoverflow.com, flask.pocoo.org'
        }
        journal_entry_data_2 = {
            'title':
            'testing 123',
            'date':
            datetime.datetime.now().strftime('%Y-%m-%d'),
            'time_spent':
            '8',
            'what_i_learned':
            'how to test flask views',
            'resources_to_remember':
            'teamtreehouse.com, stackoverflow.com, flask.pocoo.org'
        }
        with test_database(TEST_DB, (User, JournalEntry)):
            UserModelTestCase.create_users(1)
            user = User.select().get()
            journal_entry_data_1['user'] = user
            journal_entry_data_2['user'] = user
            JournalEntry.create(**journal_entry_data_1)
            JournalEntry.create(**journal_entry_data_2)

            self.app.post('/login', data=USER_DATA)
            rv = self.app.get('/entries')
            self.assertNotIn('No Entries...', rv.get_data(as_text=True))
            self.assertIn(journal_entry_data_1['title'],
                          rv.get_data(as_text=True))
            self.assertIn(journal_entry_data_1['date'],
                          rv.get_data(as_text=True))
            self.assertIn(journal_entry_data_2['title'],
                          rv.get_data(as_text=True))
            self.assertIn(journal_entry_data_2['date'],
                          rv.get_data(as_text=True))
Ejemplo n.º 37
0
    def test_is_winner(self):
        with test_database(test_db, [Race, Candidate], create_tables=True):
            data.load_races('data/tests/init_races.json')
            data.load_candidates('data/tests/init_candidates.json')

            race = Race.get(Race.race_id == '38529-OR')

            candidate = race.candidates.get() 
            candidate.ap_winner = True
            candidate.save()

            self.assertFalse(race.is_called())
            self.assertFalse(candidate.is_winner())

            race.ap_called = True
            race.npr_called = False
            race.accept_ap_call = True
            race.save()

            # Hack so the race updates override the cached FK
            candidate.race = race

            self.assertTrue(race.is_called())
            self.assertTrue(candidate.is_winner())

            candidate.ap_winner = False
            candidate.save()

            self.assertTrue(race.is_called())
            self.assertFalse(candidate.is_winner())

            race.accept_ap_call = False
            race.save()

            self.assertFalse(race.is_called())

            race.npr_called = True
            race.save()

            self.assertTrue(race.is_called())
            self.assertFalse(candidate.is_winner())

            candidate.npr_winner = True

            self.assertTrue(candidate.is_winner())
Ejemplo n.º 38
0
    def test_get_episodes_returns_highest_quality_first(self):
        with test_database(database, (Show, Episode)):
            show = self._get_new_dummy_show()
            show.save()

            episode_one = self._get_new_dummy_episode(show)
            episode_one.save()

            episode_two = self._get_new_dummy_episode(show)
            episode_two.quality = 1080
            episode_two.save()

            episodedownloadtask = EpisodeDownloadTask()
            episodes = episodedownloadtask._get_episodes()

            # Second episode has highest quality and should be first
            self.assertEqual(episodes[0].id, episode_two.id)
            self.assertEqual(episodes[1].id, episode_one.id)
Ejemplo n.º 39
0
    def test_handle(self, bot, setup_update, test_db, updater):
        """Test setup handler."""
        with test_database(test_db, [User], fail_silently=True):
            with db.transaction():
                user, created = User.tg_get_or_create(
                    setup_update.message.from_user)
                user.state = setup_update.states[0]
                user.save()

            coach = Setup(bot, test_db, setup_update.message.from_user,
                          updater.job_queue)
            messages = coach.handle(setup_update)

            user, created = User.tg_get_or_create(
                setup_update.message.from_user)

            assert len(messages) > 0
            assert user.state == setup_update.states[1]
Ejemplo n.º 40
0
    def test_misc_article_methods(self):

        with test_database(db, (Users, Articles)):
            user1 = Users.create_user(username="******", password="******")
            article = Articles.create_article(title="test article",
                                              body="test",
                                              draft=True,
                                              author=user1)

            Articles.update_article(article, title="changed", body="changed")
            self.assertEquals("changed", article.title)
            self.assertEquals("changed", article.body)

            Articles.publish_article(article)
            self.assertFalse(article.draft)

            Articles.delete_article(article)
            self.assertEquals(0, Articles.get_count(True))
Ejemplo n.º 41
0
    def test_checksum_peewee_model_exception_not_possible_with_peewee(self):
        clean_test_db = APSWDatabase(':memory:')
        with test_database(clean_test_db, [NoPrimaryKeyTable]):
            self.assertTrue(NoPrimaryKeyTable.table_exists())

            ObserverDBUtil.checksum_peewee_model(NoPrimaryKeyTable, logging)

            """
            No exception. That's because:
            
            "Because we have not specified a primary key, peewee will automatically add
            an auto-incrementing integer primary key field named id."
            (http://docs.peewee-orm.com/en/latest/peewee/models.html)
            """
            peewee_default_primary_key_field_name = 'id'
            primary_key_field = NoPrimaryKeyTable._meta.primary_key
            self.assertIsNotNone(primary_key_field)
            self.assertEqual(peewee_default_primary_key_field_name, primary_key_field.name)
Ejemplo n.º 42
0
 def test_update_state(self):
     """Test return and update of unique index."""
     with test_database(TEST_DB, (BaseModel, IngestState)):
         test_object = IngestState.create(job_id=999,
                                          state='ERROR',
                                          task='unbundling',
                                          task_percent=42.3)
         self.assertEqual(test_object.job_id, 999)
         IngestState.database_close()
         update_state(999, 'WORKING', 'validating', 33.2)
         record = read_state(999)
         self.assertEqual(record.state, 'WORKING')
         self.assertEqual(record.task, 'validating')
         self.assertEqual(float(record.task_percent), 33.2)
         record = read_state(None)
         self.assertEqual(record.state, 'DATA_ACCESS_ERROR')
         self.assertEqual(record.task, 'read_state')
         self.assertEqual(record.task_percent, 0)
Ejemplo n.º 43
0
    def base_test_hash(self, obj_hash):
        """
        Base hash test.

        create a new object out of the hash
        save the object to the DB
        pull the object out of the DB using the obj_id column
        create a new hash from the new object
        check all keys in the new hash from the obj_hash passed
        """
        with test_database(SqliteDatabase(':memory:'), self.dependent_cls()):
            obj = self.base_create_obj(self.obj_cls, obj_hash)
            new_obj = self.obj_cls.get(
                self.obj_id == getattr(obj, self.obj_id.db_column))
            chk_obj_hash = new_obj.to_hash()
            self.assertTrue('_id' in chk_obj_hash)
            for key in obj_hash.keys():
                self.assertEqual(chk_obj_hash[key], obj_hash[key])
Ejemplo n.º 44
0
    def test_taco_creation(self):
        with test_database(TEST_DB, (User, Taco)):
            UserModelTestCase.create_users()
            user = User.select().get()
            Taco.create(
                user=user,
                protein='chicken',
                shell='flour',
                cheese=False,
                extras='Gimme some guac.'
            )
            taco = Taco.select().get()

            self.assertEqual(
                Taco.select().count(),
                1
            )
            self.assertEqual(taco.user, user)
Ejemplo n.º 45
0
 def test_single_date_search(self, mock_input,
                             mock_display_results, mock_stdout):
     with test_database(test_db, [Task]):
         Task.create(
             employee='Richard',
             name='Xeroxing',
             date=datetime.date(2017, 8, 18),
             time='60',
             notes='Richmeister at the copy machine'
         )
         work_db.date_find()
         self.assertIn('Not a valid selection', mock_stdout.getvalue())
         self.assertIn('Pick one of the following dates ' +
                       'to view entries from', mock_stdout.getvalue())
         self.assertIn('1: 2017-08-18 (1 entry)', mock_stdout.getvalue())
         self.assertIn('Please enter a valid number',
                       mock_stdout.getvalue())
         self.assertTrue(mock_display_results.called)
Ejemplo n.º 46
0
def test_insert():
    lockdown_context.role = None
    lockdown_context.user = None
    lockdown_context.group = None

    rest_api = Role('rest_api')

    rest_api.lockdown(BigWheel) \
        .writeable_by(BigWheel.owner == ContextParam('user'))\
        .validate(BigWheel.owner, BigWheel.owner == ContextParam('user')) \
        .field_writeable_by(BigWheel.serial, BigWheel.owner == ContextParam('user'))

    with test_database(test_db, [User, Group, BigWheel]):
        u1 = User.create(username='******')
        u2 = User.create(username='******')
        g = Group.create(name='test')

        # set the role/user before inserting
        lockdown_context.role = rest_api
        lockdown_context.user = u1.id

        try:
            bwheel = BigWheel()
            bwheel.owner = u2
            bwheel.group = g
            bwheel.serial = '1'
            assert False, 'should have failed'
        except LockdownException:
            pass

        # insert should work fine since object validates
        bwheel = BigWheel()
        bwheel.owner = u1
        bwheel.group = g
        bwheel.serial = '1'
        bwheel.save()

        b = BigWheel.get()
        assert b.modified is not None
        assert b.created is not None
        assert b.serial == '1'
        assert b.owner == u1
        assert b.group == g
Ejemplo n.º 47
0
    def test_not_ready_cart(self):
        """Testing the cart interface get against not ready cart"""
        def start_response(*args):
            """stub for start_response to do some checking"""
            self.assertEqual(args[0], '202 Accepted')
            self.assertEqual(args[1][0][0], 'Content-Type')
            self.assertEqual(args[1][0][1], 'application/json')

        env = {'PATH_INFO': '/123', 'QUERY_STRING': ''}
        with test_database(self.sqlite_db, (Cart, File)):
            sample_cart = Cart()
            sample_cart.cart_uid = 123
            sample_cart.bundle_path = mkdtemp()
            sample_cart.save(force_insert=True)
            self.sqlite_db.close()
            cgen = CartGenerator()
            data = cgen.get(env, start_response)
            self.assertEqual(
                loads(data)['message'], 'The cart is not ready for download')
Ejemplo n.º 48
0
    def test_on_message_remove_topic(self):
        with test_database(test_db, (Log, Topic), create_tables=True):
            self.client.subscribed_topics = []
            self.client.subscribe('/test/topic/test1')
            self.client.subscribe('/test/topic/test2')
            self.client.subscribe('/test/topic/test3')
            Topic.create(name='/test/topic/test1')
            Topic.create(name='/test/topic/test2')
            Topic.create(name='/test/topic/test3')

            self.payload['options'] = None
            self.payload['topic'] = '/test/topic/test3'
            self.payload['password'] = Settings.MANAGEMENT_PASSWORD
            self.msg = msg(topic=Settings.ROOT_TOPIC + 'topic/remove',
                           payload=json.dumps(self.payload))
            mqtt_controller = MqttController()
            result = mqtt_controller.on_message(self.client, self.msg)
            self.assertEqual(2, len(self.client.subscribed_topics))
            self.assertEqual(2, Topic.select().count())
Ejemplo n.º 49
0
def test_db():
    """Peewee Test DB context.

    Example:

    def test_NAME(test_db):
        u = models.User(email="*****@*****.**", name="TESTER TESTERON")
        u.save()
        asser modls.User.count() == 1
    """
    _db = SqliteDatabase(":memory:")
    with test_database(_db, (
            Organisation,
            User,
            UserOrg,
    )) as _test_db:
        yield _test_db

    return
Ejemplo n.º 50
0
    def test_search_entry(self):
        with test_database(test_db, (work_log.Entry, )):
            self.create_entries()
            with unittest.mock.patch('builtins.input',
                                     side_effect=["n", "test name", "", "m"]):
                assert work_log.search_entry().count() == 1

            with unittest.mock.patch(
                    'builtins.input',
                    side_effect=["d", "2000-01-01", "2000-01-01", "", "m"]):
                assert work_log.search_entry().count() == 1

            with unittest.mock.patch('builtins.input',
                                     side_effect=["t", 200, "", "m"]):
                assert work_log.search_entry().count() == 1

            with unittest.mock.patch('builtins.input',
                                     side_effect=["s", "test", "", "m"]):
                assert work_log.search_entry().count() == 1
Ejemplo n.º 51
0
    def test_checksum_peewee_model(self):
        expected_sha1 = "689327755da6658627c0f015c25796a5cdc98c0c"
        with test_database(self.test_db, [Settings]):
            # Use Settings as test data table. Seed with two rows.
            self.assertTrue(ObserverDBUtil.db_save_setting('TestSettingParam1', '1234'))
            self.assertTrue(ObserverDBUtil.db_save_setting('TestSettingParam2', '4321'))

            actual_sha1 = ObserverDBUtil.checksum_peewee_model(Settings, logging)
            self.assertEqual(expected_sha1, actual_sha1)

            # Change a digit: SHA1 should change.
            self.assertTrue(ObserverDBUtil.db_save_setting('TestSettingParam2', '4221'))
            actual_sha1 = ObserverDBUtil.checksum_peewee_model(Settings, logging)
            self.assertNotEquals(expected_sha1, actual_sha1)

            # Restore the original digit: SHA1's should match.
            self.assertTrue(ObserverDBUtil.db_save_setting('TestSettingParam2', '4321'))
            actual_sha1 = ObserverDBUtil.checksum_peewee_model(Settings, logging)
            self.assertEqual(expected_sha1, actual_sha1)
Ejemplo n.º 52
0
    def test_upload_upate(self):
        with test_database(
                test_db,
            [model.Attachment, model.AttachmentRevision, model.Page]):
            self.app.post('/index/attach',
                          data={'file': (StringIO('FOOBAR'), 'foo.bar')})
            self.app.post('/index/attach',
                          data={'file': (StringIO('BARFOO'), 'foo.bar')})
            sha = hashlib.sha256()
            sha.update('BARFOO')
            emptySha = sha.hexdigest()
            uploadedFile = os.path.join(
                self._app.config['UPLOAD_PATH'],
                model.Attachment.hashPath(emptySha, 'foo.bar'))

            self.assertTrue(os.path.exists(uploadedFile))
            resp = self.app.get('/index/file/foo.bar')
            self.assertEqual(resp.status_code, 200)
            self.assertEqual(resp.data, 'BARFOO')
Ejemplo n.º 53
0
    def base_test_json(self, json_str):
        """
        Base test json.

        pass the json string to the objects from_json method
        save the object to the DB
        get the new object using column in obj_id
        convert the object to json
        """
        with test_database(SqliteDatabase(':memory:'), self.dependent_cls()):
            self.assertEqual(type(json_str), str)
            self.base_create_dep_objs()
            obj = self.obj_cls()
            obj.from_json(json_str)
            obj.save(force_insert=True)
            new_obj = self.obj_cls.get(
                self.obj_id == getattr(obj, self.obj_id.db_column))
            chk_obj_json = new_obj.to_json()
            self.assertEqual(type(chk_obj_json), str)
Ejemplo n.º 54
0
 def test_can_post_a_todo_and_get_it_back(self):
     with test_database(self.db_fd, models=(models.User, models.Todo)):
         user = models.User.create_user(
             'test_user',
             '*****@*****.**',
             'password',
         )
         user.save()
         path = self.root_url + '/todos'
         auth_payload = '{0}:{1}'.format(self.user_data['username'],
                                         self.user_data['password'])
         headers = {
             'Authorization':
             'Basic {}'.format(
                 b64encode(bytes(auth_payload,
                                 encoding='ascii')).decode('ascii')),
         }
         resp = self.app.post(
             path,
             headers=headers,
             data={
                 'name': 'test the application',
             },
         )
         returned_creating_user_data = json.loads(
             resp.data.decode())['new_todo']['creating_user']
         self.assertEqual(resp.status, '201 CREATED')
         self.assertEqual(returned_creating_user_data, user.username)
         resp = self.app.get(
             path,
             headers=headers,
         )
         self.assertEqual(resp.status_code, 200)
         self.assertEqual(
             json.loads(resp.data.decode())['todos'][0]['name'],
             'test the application',
         )
         resp = self.app.delete(
             path + '/1',
             headers=headers,
         )
         self.assertEqual(resp.status_code, 204)
Ejemplo n.º 55
0
def test_is_readable_writable_field():
    lockdown_context.role = None
    lockdown_context.user = None
    lockdown_context.group = None

    rest_api = Role('rest_api')

    rest_api.lockdown(BaseModel)\
        .field_writeable_by(BaseModel.created, NO_ONE)\
        .field_writeable_by(BaseModel.modified, NO_ONE)

    rest_api.lockdown(Bicycle) \
        .field_readable_by(Bicycle.serial, Bicycle.group == ContextParam('group')) \
        .field_writeable_by(Bicycle.serial, Bicycle.owner == ContextParam('user'))

    with test_database(test_db, [User, Group, Bicycle]):
        u = User.create(username='******')
        g = Group.create(name='test')
        b = Bicycle.create(owner=u, group=g)

        lockdown_context.role = rest_api

        assert b.is_field_readable(Bicycle.serial) is False
        assert b.is_field_writeable(Bicycle.serial) is False
        assert b.is_field_writeable(Bicycle.modified) is False
        assert b.is_field_writeable(Bicycle.created) is False

        lockdown_context.group = 10
        lockdown_context.user = 10

        assert b.is_field_readable(Bicycle.serial) is False
        assert b.is_field_writeable(Bicycle.serial) is False

        lockdown_context.group = g.id

        assert b.is_field_readable(Bicycle.serial) is True
        assert b.is_field_writeable(Bicycle.serial) is False

        lockdown_context.user = u.id

        assert b.is_field_readable(Bicycle.serial) is True
        assert b.is_field_writeable(Bicycle.serial) is True
Ejemplo n.º 56
0
def test_combined_roles():
    server_api = Role('server_api')
    server_api.lockdown(Bicycle) \
        .writeable_by((Bicycle.group == ContextParam('group')) &
                      (ContextParam('custom_role') == 'admin'))

    rest_api = server_api.extend('rest_api')
    rest_api.lockdown(BaseModel)\
        .field_writeable_by(BaseModel.created, NO_ONE)\
        .field_writeable_by(BaseModel.modified, NO_ONE)

    with test_database(test_db, [Group, Bicycle]):
        g1 = Group.create(name='test1')
        g2 = Group.create(name='test2')
        b = Bicycle.create(group=g1)

        lockdown_context.role = rest_api
        lockdown_context.group = g1.id
        lockdown_context.custom_role = 'admin'

        b.serial = '1'

        # make sure the group rule was inherited from server_api
        lockdown_context.group = g2.id
        try:
            b.serial = '1'
            assert False, 'should have failed'
        except:
            pass

        # set group to the correct group, but shouldn't be able to set created
        # since this is still the rest_api role
        lockdown_context.group = g1.id
        try:
            b.created = datetime.utcnow()
            assert False, 'should have failed'
        except:
            pass

        # server_api can set created
        lockdown_context.role = server_api
        b.created = datetime.utcnow()
Ejemplo n.º 57
0
    def test_stage_bad_file_id(self):
        """test a error return from a file not ready to pull"""
        with test_database(SqliteDatabase(':memory:'), (Cart, File)):

            def fake_database_connect(cls):
                """dont error with connect"""
                return cls

            def fake_database_close(cls):
                """dont actually close"""
                return cls

            cart.cart_orm.CartBase.database_connect = MethodType(
                fake_database_connect, cart.cart_orm.CartBase)
            cart.cart_orm.CartBase.database_close = MethodType(
                fake_database_close, cart.cart_orm.CartBase)
            cart.cart_orm.CartBase.throw_error = False
            file_id = 9999999
            stage_file_task(file_id)
            self.assertEqual(True, True)
 def test_hash_list_with_keys(self):
     """Test method to check the results of available hash list."""
     sample_key1 = {'_id': 127, 'key': 'proposal', 'encoding': 'UTF8'}
     sample_key2 = {'_id': 128, 'key': 'proposal', 'encoding': 'UTF8'}
     sample_key3 = {'_id': 130, 'key': 'proposal', 'encoding': 'UTF8'}
     with test_database(SqliteDatabase(':memory:'), [Keys]):
         self.base_create_obj(Keys, sample_key1)
         self.base_create_obj(Keys, sample_key2)
         self.base_create_obj(Keys, sample_key3)
         third_obj = Keys()
         hash_list, hash_dict = third_obj.available_hash_list()
         self.assertTrue(len(hash_list) == 3)
         # some sanity checking for the layout of the two objects
         for hashed_key in hash_list:
             self.assertTrue(hashed_key in hash_dict)
             obj_key_meta = hash_dict[hashed_key]
             self.assertTrue('index_hash' in obj_key_meta)
             self.assertTrue('key_list' in obj_key_meta)
             self.assertTrue('id' in obj_key_meta['key_list'])
             self.assertTrue(hashed_key == obj_key_meta['index_hash'])
    def test_locations_updated_in_database(self):
        """
        Test that position numbers are re-assigned according to datetime sort order.
        Updates tested are those written to test database.
        """
        n_expected = len(self.expected_position_assignments)

        with test_database(self.test_db, self.test_tables):
            self._load_up_test_location_data()
            fishing_locations = ObserverFishingLocations()
            fishing_locations.load_fishing_locations(self.test_activity_num)
            # ----
            fishing_locations._update_location_positions()
            # ----
            sorted_locations = FishingLocations.select().where(
                FishingLocations.fishing_activity == self.test_activity_num)
            self.assertEqual(n_expected, len(sorted_locations))
            for sloc in sorted_locations:
                print("{0} {1} ({2:0>5})".format(sloc.position, sloc.location_date, sloc.fishing_location))
                self.assertEqual(self.expected_position_assignments[sloc.fishing_location], sloc.position)
Ejemplo n.º 60
0
    def test_cart_int_get_no_file_fd(self):
        """Testing the cart interface get method w/o file_wrapper"""
        def start_response(*args):
            """stub for start_response to do some checking"""
            self.assertEqual(args[0], '200 OK')
            self.assertEqual(args[1][0][0], 'Content-Type')
            self.assertEqual(args[1][0][1], 'application/octet-stream')

        env = {'PATH_INFO': '/123', 'QUERY_STRING': ''}
        with test_database(self.sqlite_db, (Cart, File)):
            sample_cart = Cart()
            sample_cart.cart_uid = 123
            sample_cart.bundle_path = mkdtemp()
            sample_cart.status = 'ready'
            sample_cart.save(force_insert=True)
            self.sqlite_db.close()
            cgen = CartGenerator()
            tarfile_read = cgen.get(env, start_response)
            for buf in tarfile_read:
                self.assertTrue(len(buf) > 0)