コード例 #1
0
ファイル: tests.py プロジェクト: rogeriofalcone/anaf
 def test_model_category(self):
     """Test category model"""
     obj = Category(name='test')
     obj.save()
     self.assertEquals('test', obj.name)
     self.assertNotEquals(obj.id, None)
     obj.delete()
コード例 #2
0
ファイル: resources.py プロジェクト: protivofazza/Student_01
    def delete(self, cat_id=None):
        if not cat_id:
            return "Відсутній id в url"
        try:
            category_to_delete = Category.objects.get(id=cat_id)
            category_to_delete = CategorySchema().dump(category_to_delete)

            reference_list_child_cat = Category.objects.filter(
                parent_category=category_to_delete['id'])
            # При видаленні категорії в разі наявності в них підкатегорій наступний блок if/for видаляє всі їх також
            if reference_list_child_cat:
                for category in reference_list_child_cat:
                    # Продукти, що належать до підкатегорії видаляються в наступному циклі for
                    products_to_delete_list = Products.objects.filter(
                        category=category.id)
                    for product in products_to_delete_list:
                        product.delete()
                    category.delete()

            category = Category(id=cat_id)
            # Продукти, що належать до підкатегорії видаляються також разом із нею
            products_to_delete_list = Products.objects.filter(
                category=category.id)
            for product in products_to_delete_list:
                product.delete()
            category.delete()
            return category_to_delete
        except DoesNotExist as error:
            data = "За введеним ID наразі немає записів: " + str(error)
            return data
        except Val_error as error:
            data = "Введений ID у невірному форматі: " + str(error)
            return data
コード例 #3
0
ファイル: tests.py プロジェクト: tovmeod/anaf
 def test_model_category(self):
     """Test category model"""
     obj = Category(name='test')
     obj.save()
     self.assertEquals('test', obj.name)
     self.assertNotEquals(obj.id, None)
     obj.delete()
コード例 #4
0
    def test_generate_quiz_success(self):
        question_1 = Question(question='Q1?',
                              answer='A1',
                              difficulty=1,
                              category=1)
        question_2 = Question(question='Q2?',
                              answer='A2',
                              difficulty=2,
                              category=1)
        question_1.insert()
        question_2.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().post('/quizzes',
                                 json={
                                     'previous_questions': [],
                                     'quiz_category': {
                                         'type': "Science",
                                         'id': '0'
                                     }
                                 })
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['previous_questions'], [])
        self.assertTrue(data['current_question'])

        category.delete()
コード例 #5
0
    def test_generate_quiz_fail(self):
        question_1 = Question(question='Q1?',
                              answer='A1',
                              difficulty=1,
                              category=1)
        question_2 = Question(question='Q2?',
                              answer='A2',
                              difficulty=2,
                              category=1)
        question_1.insert()
        question_2.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().get('/quizzes',
                                json={
                                    'previous_questions': [],
                                    'quiz_category': {
                                        'type': "Science",
                                        'id': '0'
                                    }
                                })
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 405)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'method not allowed')

        category.delete()
コード例 #6
0
    def test_get_questions_by_category(self):
        category = Category(
            type='dummy_test_category',
        )
        category.insert()

        question = Question(
            question='dummy_test_question',
            answer='answer',
            category=str(category.id),
            difficulty='4'
        )
        question.insert()

        res = self.client().get(
            f'/categories/{category.id}/questions'
        )
        status_code = res.status_code
        data = json.loads(res.data)
        questions = data['questions']
        total_questions = data['total_questions']

        question.delete()
        category.delete()

        self.assertEqual(status_code, 200)
        self.assertEqual(len(questions), 1)
        self.assertEqual(total_questions, 1)
コード例 #7
0
ファイル: test_flaskr.py プロジェクト: zoom2ashish/trivia-api
    def test_add_question_invalid_question_data(self):
        category = Category('Dummy')
        category.insert()
        response = self.client().post('/api/questions', json={
            'question': '',
            'answer': 'Not Me!',
            'difficulty': 5,
            'category': category.id
        })
        self.assertEqual(response.status_code, 400)

        response = self.client().post('/api/questions', json={
            'question': 'Valid Question',
            'answer': '',
            'difficulty': 5,
            'category': category.id
        })
        self.assertEqual(response.status_code, 400)

        response = self.client().post('/api/questions', json={
            'question': 'Valid Question',
            'answer': 'Valid Answer',
            'difficulty': 0,
            'category': category.id
        })
        self.assertEqual(response.status_code, 400)

        category.delete()
コード例 #8
0
ファイル: tests.py プロジェクト: zejn/django_temporal
 def runTest(self):
     period = Period(lower=datetime.datetime(1996,10,1), upper=datetime.datetime(1997,1,1))
     i = Category(cat=120033, valid_time=period)
     i.save()
     
     for bad in [5, 2.0, 'foo', (10, 20)]:
         try:
             i.valid_time = bad
         except TypeError:
             pass
         else:
             self.fail('Should throw a TypeError')
     
     newstr = '[1996-01-01 00:00:00.000000+0000,1996-06-01 00:00:00.000000+0000)'
     new = Period(newstr)
     
     for good in (new, newstr):
         i.valid_time = good
     
     self.assertEqual(i.valid_time, new)
     i.save()
     self.assertNotEqual(i.pk, None)
     self.assertEqual(new, Category.objects.get(pk=i.pk).valid_time)
     
     i.delete()
コード例 #9
0
def admin_delete_category(cat_id):
    Category.delete(cat_id)
    posts = Post.query.filter_by(category_id=cat_id).all()
    if posts is not None:
        for p in posts:
            Post.update_category_id(p.post_id, 0)
    categories = Category.query.all()
    return render_template('admin_categories.html', title='Admin', user=current_user, categories=categories)
コード例 #10
0
ファイル: test_flaskr.py プロジェクト: zoom2ashish/trivia-api
    def test_get_questions_by_category_invalid_category(self):
        category = Category("Science")
        category.insert()
        questions = self.insert_questions_for_test(category, 15)

        response = self.client().get('/api/categories/{}/questions'.format(0))
        data = response.get_json()
        self.assertEqual(response.status_code, 400)

        self.delete_questions(questions)
        category.delete()
コード例 #11
0
    def test_get_questions_by_category_fail(self):
        category = Category(type="science")
        category.insert()

        res = self.client().get('/categories/1245/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'resource not found')

        category.delete()
コード例 #12
0
    def test_post_categories_fail(self):
        category = Category(type="science")
        category.insert()

        res = self.client().post('/categories', json={'type': 3})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 405)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'method not allowed')

        category.delete()
コード例 #13
0
    def test_get_categories_success(self):
        category = Category(type="science")
        category.insert()

        res = self.client().get('/categories')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['categories'])
        self.assertEqual(len(data['categories']), 1)

        category.delete()
コード例 #14
0
ファイル: test_flaskr.py プロジェクト: zoom2ashish/trivia-api
    def test_get_questions_handle_multiple_pages(self):
        # Insert Records for
        category = Category("Science")
        category.insert()
        questions = self.insert_questions_for_test(category)

        response = self.client().get('/api/questions?page=2')
        data = response.get_json()
        self.assertEqual(data['total_questions'], 15)
        self.assertEqual(len(data['questions']), 5)

        self.delete_questions(questions)
        category.delete()
コード例 #15
0
ファイル: test_flaskr.py プロジェクト: zoom2ashish/trivia-api
 def test_get_questions_one_record(self):
     category = Category("Science")
     category.insert()
     question = Question('Q1', 'A1', "1", category.id)
     question.category = category
     question.insert()
     response = self.client().get('/api/questions')
     data = response.get_json()
     print(data)
     # self.assertEqual(data['questions'], [])
     self.assertEqual(data['total_questions'], 1)
     self.assertEqual(response.status_code, 200)
     question.delete()
     category.delete()
コード例 #16
0
ファイル: test_flaskr.py プロジェクト: zoom2ashish/trivia-api
    def test_search_questions_non_matching_word(self):
        category = Category("Science")
        category.insert()
        question = Question('Who moved my cheese', 'Not Me!', "1", category.id)
        question.category = category
        question.insert()

        response = self.client().post('/api/questions/search',
                                      json={'searchTerm': 'happy'})
        data = response.get_json()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['total_questions'], 0)

        question.delete()
        category.delete()
コード例 #17
0
    def test_delete_question_success(self):
        question = Question(question=self.new_question_1['question'],
                            answer=self.new_question_1['answer'],
                            difficulty=self.new_question_1['difficulty'],
                            category=self.new_question_1['category'])
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().delete('/questions/' + str(question.id))
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['message'], 'question deleted')

        category.delete()
コード例 #18
0
ファイル: test_flaskr.py プロジェクト: zoom2ashish/trivia-api
    def test_get_random_question_for_last_question(self):
        category = Category("Science")
        category.insert()
        question = Question('Who moved my cheese', 'Not Me!', "1", category.id)
        question.category = category
        question.insert()

        response = self.client().post('/api/quizzes', json={
            'previous_questions': [question.id],
            'quiz_category': None
        })
        data = response.get_json()

        self.assertEqual(response.status_code, 200)
        self.assertEqual(data.get('question'), None)

        question.delete()
        category.delete()
コード例 #19
0
    def test_search_questions_fail(self):
        question = Question(question=self.new_question_3['question'],
                            answer=self.new_question_3['answer'],
                            difficulty=self.new_question_3['difficulty'],
                            category=4)
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().post('/questions', json={'searchTerm': None})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 400)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'bad request')

        category.delete()
コード例 #20
0
    def test_get_all_questions_fail(self):
        question = Question(question=self.new_question_1['question'],
                            answer=self.new_question_1['answer'],
                            difficulty=self.new_question_1['difficulty'],
                            category=self.new_question_1['category'])
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().get('/questions', json={'type': 3})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 400)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'bad request')

        question.delete()
        category.delete()
コード例 #21
0
    def test_get_questions_paginated_fail(self):
        question = Question(question=self.new_question_1['question'],
                            answer=self.new_question_1['answer'],
                            difficulty=self.new_question_1['difficulty'],
                            category=self.new_question_1['category'])
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().get('/questions?page=1000')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'resource not found')

        question.delete()
        category.delete()
コード例 #22
0
ファイル: views.py プロジェクト: KyubiSystems/Wisewolf
def delete_category(id):
    # Delete category #id
    # Reassign all feeds in category to 'unsorted' id 0?
    query = Feed.update(category_id=0).where(Category.id == id) 
    query.execute()

    query = Category.delete().where(Category.id == id)
    query.execute()

    # return JSON status OK
    return jsonify(**STATUS_OK)
コード例 #23
0
ファイル: tests.py プロジェクト: dsantosp12/NapAdmin
 def test_create_stock_no_duplicate(self):
     """Makes sure stock don't have the same stock_id when creating."""
     Category.create(category_id='001', description='Testing Stock')
     create_stock('001', 'Testing stock', 1, '001', 9.99)
     from peewee import IntegrityError
     with self.assertRaises(IntegrityError):
         create_stock('001', 'Testing stock', 1, '001', 9.99)
     q = Stock.delete().where(Stock.stock_id == '001')
     q.execute()
     t = Category.delete().where(Category.category_id == '001')
     t.execute()
コード例 #24
0
ファイル: views.py プロジェクト: KyubiSystems/Wisewolf
def delete_category(id):
    # Delete category #id
    # Reassign all feeds in category to 'unsorted' id 0?
    query = Feed.update(category_id=0).where(Category.id == id)
    query.execute()

    query = Category.delete().where(Category.id == id)
    query.execute()

    # return JSON status OK
    return jsonify(**STATUS_OK)
コード例 #25
0
    def test_search_questions_success(self):
        question = Question(question='Q4?',
                            answer=self.new_question_3['answer'],
                            difficulty=self.new_question_3['difficulty'],
                            category=self.new_question_3['category'])
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().post('/questions', json={'searchTerm': 'Q4?'})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['questions'][0]['question'], 'Q4?')
        self.assertEqual(data['total_questions'], 1)
        self.assertEqual(data['current_category'], ['3'])

        question.delete()
        category.delete()
コード例 #26
0
ファイル: test_flaskr.py プロジェクト: zoom2ashish/trivia-api
    def test_add_question_valid_payload(self):
        category = Category('Dummy')
        category.insert()
        response = self.client().post('/api/questions', json={
            'question': 'Who moved my cheese?',
            'answer': 'Not Me!',
            'difficulty': 5,
            'category': category.id
        })

        data = response.get_json()
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['question'], 'Who moved my cheese?')
        self.assertEqual(data['category_id'], category.id)

        question = Question.query.filter(Question.id == data['id']).first()
        self.assertEqual(question.question, data['question'])
        self.assertEqual(question.category_id, category.id)

        question.delete()
        category.delete()
コード例 #27
0
    def test_get_all_questions_success(self):
        question = Question(question=self.new_question_1['question'],
                            answer=self.new_question_1['answer'],
                            difficulty=self.new_question_1['difficulty'],
                            category=self.new_question_1['category'])
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().get('/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['questions'])
        self.assertTrue(data['total_questions'])
        self.assertEqual(len(data['categories']), 1)
        self.assertTrue(data['current_category'])

        question.delete()
        category.delete()
コード例 #28
0
    def test_get_questions_paginated_success(self):
        question = Question(question="question?",
                            answer="answer",
                            difficulty=1,
                            category=1)
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().get('/questions?page=1')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['questions'])
        self.assertEqual(data['success'], True)
        self.assertTrue(len(data['categories']), 1)
        self.assertEqual(data['current_category'][0], "1")

        question.delete()
        category.delete()
コード例 #29
0
ファイル: views.py プロジェクト: Tibodef/PythonBlog
    def delete(self, id):
        category = Category.get_by_id(id)
        if category is None:
            flash(gettext('The category was not found'), 'error')
            return redirect(url_for('CategoriesView:index'))
        if not category.can_edit():
            abort(401)

        try:
            if not Category.transfer_posts(category):
                return util.redirect_json_or_html(url_for('CategoriesView:index'),
                    'category',
                    gettext('Sorry, the last category can not be removed'))

            name = category.name
            Category.delete(category.id)
            flash(gettext('The category "%(name)s" was removed', name=name))
        except:
            return util.redirect_json_or_html(url_for('CategoriesView:index'),
                'category',
                gettext('Error while removing the category'))

        return util.redirect_json_or_html(url_for('CategoriesView:index'), 'category')
コード例 #30
0
ファイル: tests.py プロジェクト: dsantosp12/NapAdmin
 def test_create_stock(self):
     """Make sure it create a stock."""
     Category.create(category_id='001', description='Testing Stock')
     create_stock('001', 'Testing stock', 1, '001', 9.99)
     s = Stock.select().where(Stock.stock_id == '001')
     t = Stock.delete().where(Stock.stock_id == '001')
     t.execute()
     t = Category.delete().where(Category.category_id == '001')
     t.execute()
     self.assertEqual(str(s), ("<class 'models.Stock'> SELECT `t1`.`id`,"
                               " `t1`.`stock_id`, `t1`.`description`,"
                               " `t1`.`quantity`, `t1`.`category_id`,"
                               " `t1`.`price` FROM `stock` AS t1"
                               " WHERE (`t1`.`stock_id` = %s) ['001']"))
コード例 #31
0
    def test_get_questions_by_category_success(self):
        drop_create_tables()

        question = Question(question="question?",
                            answer="answer",
                            difficulty=1,
                            category=1)
        question.insert()

        category = Category(type="science")
        category.insert()

        res = self.client().get('/categories/' + '1' + '/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['questions'])
        self.assertEqual(data['total_questions'], 1)
        self.assertTrue(data['categories'])
        self.assertTrue(data['current_category'])

        question.delete()
        category.delete()
コード例 #32
0
ファイル: test.py プロジェクト: dsantosp12/NapAdmin
    def test_create_incoming(self):
        """Create an incoming record."""
        Category.create(category_id='001', description='Testing Stock')
        create_stock('001', 'Testing stock', 1, '001', 9.99)
        create_incoming_stock(stock="001", date="2015-07-22", quantity=13, price=13.99)
        p = IncomingStock.select().where(IncomingStock.stock == '001')
        q = IncomingStock.delete().where(IncomingStock.stock == '001')
        q.execute()
        s = Stock.select().where(Stock.stock_id == '001')
        t = Stock.delete().where(Stock.stock_id == '001')
        t.execute()
        t = Category.delete().where(Category.category_id == '001')
        t.execute()

        self.assertEqual(str(p), ("<class 'models.IncomingStock'> SELECT `t1`.`id`, `t1`.`stock_id`, "
                                  "`t1`.`date`, `t1`.`price`, `t1`.`cost` FROM `incomingstock` AS t1 WHERE "
                                  "(`t1`.`stock_id` = %s) ['001']"))
コード例 #33
0
ファイル: test_orm.py プロジェクト: vskavronsky/DevClub
 def tearDown(self):
     self.assertIsNone(Category.delete(self.category.id))
コード例 #34
0
ファイル: test_orm.py プロジェクト: vskavronsky/DevClub
 def doCleanups(self):
     Category.delete(self.category1.id)
     Category.delete(self.category2.id)
コード例 #35
0
class TriviaTestCase(unittest.TestCase):
    """This class represents the trivia test case"""
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.svr = "localhost:5432"
        self.dbname = "trivia_test"
        self.dbusr = "******"
        self.dbpass = "******"
        self.dbpath = \
            f"postgresql://{self.dbusr}:{self.dbpass}@{self.svr}/{self.dbname}"
        setup_db(self.app, self.database_path)

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()

        self.new_question = Question(question="new question",
                                     answer="new answer",
                                     category=1,
                                     difficulty=1)
        self.new_category = Category("Test")

        self.new_question.insert()
        self.new_category.add()

    def tearDown(self):
        """Executed after reach test"""
        self.new_question.delete()
        self.new_category.delete()
        pass

    """
    TODO
    Write at least one test for each test for successful operation
    and for expected errors.
    """

    def test_paginated_questions(self):
        res = self.client().get('/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        # test that pagination works
        self.assertLessEqual(data['total_questions'], 10)
        self.assertTrue(len(data['questions']))

    def test_categories(self):
        res = self.client().get('/categories')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(len(data['categories']))

    def test_get_category_questions(self):
        res = self.client().get(
            f'/categories/{self.new_question.category}/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(int(data['category']), self.new_question.category)
        self.assertTrue(len(data['questions']))
        self.assertTrue(data['total'])

    def test_get_category_questions_404(self):
        res = self.client().get(f'/categories/9999/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], "Sorry, resource unavailable")

    def test_unreachable_page_number(self):
        res = self.client().get('/questions?page=9999')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], "Sorry, resource unavailable")

    def test_unreachable_category_number(self):
        res = self.client().get('/categories/999')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], "Sorry, resource unavailable")

    def test_delete_question(self):
        # create question to be deleted
        question = Question("new question", "new answer", 1, 1)
        question.insert()
        question_id = question.id

        # delete question and get response
        res = self.client().delete(f"questions/{question_id}")
        data = json.loads(res.data)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)

        # check if deleted question no longer exists
        deleted_question = Question.query.get(question_id)
        self.assertEqual(deleted_question, None)

    def test_delete_question_404(self):
        res = self.client().delete("questions/askfueso")
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], "Sorry, resource unavailable")

    def test_add_question(self):
        new_question = {
            'question': 'Who is the first man?',
            'answer': 'Adam',
            'category': 1,
            'difficulty': 1
        }
        oldTotal = len(Question.query.all())

        # Add question
        res = self.client().post('questions', json=new_question)
        data = json.loads(res.data)
        newTotal = len(Question.query.all())

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)

        # test that the number of questions has increased by 1
        self.assertEqual(newTotal, oldTotal + 1)

    def test_add_question_failure(self):
        new_question = {
            'question': 'Who is the first man?',
            'answer': 'Adam',
            'category': 1
        }
        oldTotal = len(Question.query.all())

        # Add question
        res = self.client().post('questions', json=new_question)
        data = json.loads(res.data)
        newTotal = len(Question.query.all())

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], "Sorry, request cannot be processed")

        # test that the number of questions has not increased by 1
        self.assertEqual(newTotal, oldTotal)

    def test_question_search(self):
        query = {'searchTerm': 'e'}
        res = self.client().post('/questions/search', json=query)
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertIsNotNone(data['questions'])
        self.assertIsNotNone(data['total_questions'])

    def test_quiz(self):
        quiz = {
            'previous_questions': [],
            'quiz_category': {
                'type': 'Test',
                'id': 1
            }
        }

        res = self.client().post('/quizzes', json=quiz)
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)

    def test_quiz_404(self):
        quiz = {'quiz_category': {'type': 'Test', 'id': 1}}

        res = self.client().post('/quizzes', json=quiz)
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], "Sorry, request cannot be processed")
コード例 #36
0
class TriviaTestCase(unittest.TestCase):
    """This class represents the trivia test case"""
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "trivia_test"
        self.database_path = "postgres://*****:*****@{}/{}".format(
            'localhost:5432', self.database_name)
        setup_db(self.app, self.database_path)

        # binds the app to the current context
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            # create all tables
            self.db.create_all()

        self.category = Category(type="test")
        self.category.insert()

        self.question = Question(question="Who are you?",
                                 answer="I am I",
                                 difficulty=3,
                                 category=self.category.id)
        self.question.insert()

    def tearDown(self):
        """Executed after reach test"""
        Question.drop(Question)
        Category.drop(Category)

    def test_404_request(self):
        res = self.client().get('/questions?page=1000', json={'rating': 1})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Resource not found')

    def test_get_categories(self):
        res = self.client().get('/categories')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['categories'])

    def test_get_categories_404(self):
        self.category.delete()

        res = self.client().get('/categories')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Resource not found')

    def test_get_paginated_questions(self):
        res = self.client().get('/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['questions'])
        self.assertTrue(data['total_questions'])
        self.assertTrue(data['categories'])

    def test_get_paginated_questions_404(self):
        self.question.delete()

        res = self.client().get('/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Resource not found')

    def test_get_questions_by_category(self):
        res = self.client().get(f'/categories/{self.category.id}/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['questions'])
        self.assertTrue(data['total_questions'])

    def test_get_questions_by_category_404(self):
        res = self.client().get(f'/categories/1000/questions')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Resource not found')

    def test_search_question(self):
        res = self.client().post('/questions/search',
                                 json={
                                     'searchTerm': 'Who',
                                 })
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['questions'])
        self.assertTrue(data['total_questions'])

    def test_search_question_422(self):
        res = self.client().post('/questions/search', json={})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Unprocessable')

    def test_post_new_question(self):
        res = self.client().post('/questions',
                                 json={
                                     'question': 'Test question',
                                     'answer': 'Test answer',
                                     'difficulty': 1,
                                     'category': 1
                                 })
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['id'])

    def test_post_new_question_422_by_category(self):
        res = self.client().post('/questions',
                                 json={
                                     'question': 'Test question',
                                     'answer': 'Test answer',
                                     'difficulty': 1,
                                     'category': 1000
                                 })
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Unprocessable')

    def test_post_new_question_422_by_difficult(self):
        res = self.client().post('/questions',
                                 json={
                                     'question': 'Test question',
                                     'answer': 'Test answer',
                                     'difficulty': 1000,
                                     'category': 1
                                 })
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Unprocessable')

    def test_delete_question(self):
        res = self.client().delete(f'/questions/{self.question.id}')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertTrue(data['id'])

    def test_delete_question_404(self):
        res = self.client().delete(f'/questions/1000')
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 404)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Resource not found')

    def test_quiz(self):
        res = self.client().post('/quizzes',
                                 json={
                                     'previous_questions': [],
                                     'quiz_category': ["test", 1]
                                 })
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)

    def test_quiz_422(self):
        res = self.client().post('/quizzes', json={})
        data = json.loads(res.data)

        self.assertEqual(res.status_code, 422)
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Unprocessable')