Beispiel #1
0
class CategoryModelTestCase(TestCase):
    """
    This class defines the test cases for the Category model
    """
    def setUp(self):
        """
        Set up the test suite and some initial variables
        """
        self.user = User.objects.create(username="******")
        self.category_content = {
            "name": "Test",
            "description": "This is a test category"
        }
        self.category = Category(name="Test",
                                 description="This is a test category",
                                 owner=self.user)

    def test_category_can_be_created(self):
        """
        Test that a category can be created by providing the required 
        information.
        """
        old_count = Category.objects.count()
        self.category.save()
        new_count = Category.objects.count()
        self.assertEqual(new_count, old_count + 1)

        created_category = Category.objects.get()
        self.assertTrue(isinstance(created_category, Category))
Beispiel #2
0
def categories(app):
    categories = []
    for each in range(3):
        params = {'name': fake.alphanumeric()}
        category = Category(**params)
        categories.append(category.save())
    return categories
Beispiel #3
0
    def setUp(self):
        """
        Define the test client and initial variables for the test suite
        """
        self.user = User.objects.create(username="******")

        self.client = APIClient()
        self.client.force_authenticate(user=self.user)
        self.category = Category(name="Test",
                                 description="This is a test category",
                                 owner=self.user)
        self.category.save()
        self.article = Article(url="http://www.dummy.com",
                               title="Dummy title",
                               category=self.category,
                               owner=self.user)
        self.article_data = {
            "url": "http://www.dummy.com",
            "title": "Dummy Title",
            "description": "A sample description",
            "read_status": False,
            "owner": self.user.id
        }
        article_url = '/api/v2/categories/{}/articles/'.format(
            self.category.id)
        self.response = self.client.post(article_url,
                                         self.article_data,
                                         format="json")
    def put(current_user, self, id):
        """
                      Edit a category with the specified id
                      ---
                      tags:
                        - categories
                      parameters:
                        - in: path
                          name: id
                          required: true
                          description: The ID of the category to retrieve
                          type: string
                        - in: body
                          name: category
                          required: true
                          description: The name of the category
                          type: string
                          schema:
                            id: category
                            properties:
                                name:
                                    type: string
                                    default: soup
                      security:
                         - TokenHeader: []
                      responses:
                        200:
                          description: A single category successfully deleted
                          schema:
                            id: category
                            properties:
                                name:
                                    type: string
                                    default: soup
                      """

        category = Category.query.filter_by(id=id,
                                            user_id=current_user.id).first()
        if not category:
            return {"Error": "A category with that Id does not exist"}, 404
        category_dict = request.get_json(force=True)
        if 'name' in category_dict:
            category_name = category_dict['name'].strip()
            errors = category_schema.validate(category_dict)
            if errors:
                abort(status.HTTP_400_BAD_REQUEST, errors)
            error, validated_name = Category.validate_data(ctx=category_name)
            if validated_name:
                if Category.is_unique(id=id,
                                      name=category_name,
                                      user_id=current_user.id):
                    category.name = category_name
                else:
                    abort(status.HTTP_409_CONFLICT,
                          'A category with the same name already exists')
            else:
                return {"errors": error}
        category.update()
        return {'message': 'Category successfully edited!'}, 201
def test_delete_a_category(client):
    category = Category(name='Test category')
    category.save()

    response = client.delete('/api/v1/categories/{}/'.format(str(category.id)),
                             content_type='application/json')

    assert response.status_code == 204
Beispiel #6
0
def load_category(path, delete_all=False):
    if delete_all:
        Category.objects.all().delete()
    with open(path) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            category = Category(category=row['category'])
            category.save()
Beispiel #7
0
 def handle(self, *args, **options):
     with open('data/category.csv', encoding='utf-8') as csvfile:
         spamreader = csv.reader(csvfile)
         for id, row in enumerate(spamreader):
             if id == 0:
                 continue
             category = Category(id=row[0], name=row[1], slug=row[2])
             category.save()
Beispiel #8
0
 def create(name, description, words):
     """ Create a new category """
     words_obj = []
     if words:
         for word in words:
             words_obj.append(Word(word=word))
     category = Category(name=name,
                         description=description,
                         words=words_obj)
     return category.save()
def test_get_a_category(client):
    category = Category(name='Test category')
    category.save()

    response = client.get('/api/v1/categories/{}/'.format(str(category.id)),
                          format='json')

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 200
    assert content['id'] == str(category.id)
Beispiel #10
0
 def test_save(self, init_db):
     """Test for creating a new company
     
         Args:
             init_db(SQLAlchemy): fixture to initialize the test database
     """
     params = {
         'name': fake.alphanumeric(15)
     }
     category = Category(**params)
     assert category == category.save()
Beispiel #11
0
 def setUp(self):
     """
     Set up the test suite and some initial variables
     """
     self.user = User.objects.create(username="******")
     self.category_content = {
         "name": "Test",
         "description": "This is a test category"
     }
     self.category = Category(name="Test",
                              description="This is a test category",
                              owner=self.user)
Beispiel #12
0
def crawl_categories(url):
    url_html = requests.get(url)
    index_soup = BeautifulSoup(url_html.content, 'html.parser')
    categories = index_soup.select('[href*="catalogue/category/books/"]')
    for c in categories:
        name = c.getText().strip()
        cur_category = Category.objects.filter(name=name)
        if cur_category:
            pass
        else:
            new_category = Category(name=name)
            new_category.save()
def test_update_a_category(client):
    category = Category(name='Test category')
    category.save()

    response = client.patch('/api/v1/categories/{}/'.format(str(category.id)),
                            json.dumps({'name': 'Updated Name'}),
                            content_type='application/json')

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 200
    assert content['name'] == 'Updated Name'
Beispiel #14
0
def create_entry(category_data):
    from api.models import Category, Favorite
    
    try:
        category = Category(name=category_data['name'])
        category.save()

        for each in category_data.get('favorites', []):
            favorite = Favorite(**dict(**each, category_id=category.id))
            favorite.save()
    except Exception as e:
        print(e)
        pass
def test_get_categories(client):
    category = Category(name='Test category')
    category.save()

    response = client.get('/api/v1/categories/', format='json')

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 200
    assert content['count'] == 1
    assert content['next'] == None
    assert content['previous'] == None
    assert any(
        str(category.id) == result['id'] for result in content['results'])
Beispiel #16
0
def test_update_favorite_thing_validation(client):
    category = Category(name="Food")
    category.save()

    favorite_thing = FavoriteThing(title="Rice", category=category, ranking=1)
    favorite_thing.save()

    response = client.patch('/api/v1/favorite-things/{}/'.format(
        str(favorite_thing.id)), {'ranking': {}},
                            content_type='application/json')

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 400
    assert content == {'ranking': ['A valid integer is required.']}
Beispiel #17
0
def test_update_favorite_thing(client):
    category = Category(name="Food")
    category.save()

    favorite_thing = FavoriteThing(title="Rice", category=category, ranking=1)
    favorite_thing.save()

    response = client.patch('/api/v1/favorite-things/{}/'.format(
        str(favorite_thing.id)), {'title': 'Koko'},
                            content_type='application/json')

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 200
    assert content['title'] == 'Koko'
def get_pages_from_json(json) -> Dict[str, Page]:
    categorizer = Categorizer()
    pages_to_return = {}
    response_pages = get_hits(json)
    for page in response_pages:
        page_info = page.get("_source")
        url = page_info.get("raw_url")
        if is_url_valid(url):
            page_id = page.get("_id")
            title = page_info.get("title")
            response_links = page_info.get("links")
            last_updated = page_info.get("updated_on")
            links = get_links_from_json(response_links)
            content = page_info.get("content")
            category_name = categorizer.categorize(bytes(content, 'utf-8').decode('utf-8', 'ignore'))
            category = Category(
                    name=category_name,
                    occurrence=1,
            )
            pages_to_return[url] = Page(
                id=page_id,
                url=url,
                title=title,
                last_updated=last_updated,
                links=links,
                content=content,
                categories=[category]
            )
        else:
            print("cannot find url for source: {}".format(page_info))
    return pages_to_return
Beispiel #19
0
    def test_tags(self):
        category = Category(name="Test category")
        db.session.add(category)

        media = Media(path="/foo/bar",
                      mediainfo={"width": 100,
                                 "height": 100,
                                 "acodec": "aac",
                                 "vcodec": "h.265"},
                      category=category,
                      mimetype="video",
                      lastModified=int(time.time()),
                      timeLastIndexed=int(time.time()),
                      sha=b'\x00'*32)

        db.session.add(media)
        db.session.commit()

        tag1 = Tag(name="tag1")
        tag2 = Tag(name="tag2")
        db.session.add(tag1)
        db.session.add(tag2)

        media.tags.append(tag1)
        media.tags.append(tag2)

        medias = Media.query.all()

        assert media in medias
        assert medias[0].tags == [tag1, tag2]
Beispiel #20
0
    def create(self, request):
        '''
		:method:POST:
		creates a new category.
		'''
        user = request.user
        print(user)
        print(request.data)
        print("here")
        title = request.data["title"]
        description = request.data["description"]
        category = Category(title=title, description=description, user=user)
        category.save()

        category = CategorySerializer(category)
        return Response(category.data)
 def test_create_category_fails_when_already_existing(self):
     new_category = {'name': 'Friends'}
     Category(**new_category).save()
     response = self.client.post('/categories', new_category, format='json')
     self.assertEqual(response.status_code, 400)
     self.assertEqual(response.data['name'][0],
                      'category with this name already exists.')
Beispiel #22
0
def test_update_favorite_thing_ranking_without_category(client):
    category = Category(name="Food")
    category.save()

    favorite_thing = FavoriteThing(title="Rice", category=category, ranking=1)
    favorite_thing.save()
    second_favorite_thing = FavoriteThing(title="Beans",
                                          category=category,
                                          ranking=2)
    second_favorite_thing.save()
    third_favorite_thing = FavoriteThing(title="soup",
                                         category=category,
                                         ranking=3)
    third_favorite_thing.save()

    response = client.patch('/api/v1/favorite-things/{}/'.format(
        str(favorite_thing.id)), {'ranking': 5},
                            content_type='application/json')

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 400
    assert content == {'ranking': ['number is out of ranking range']}

    response = client.patch('/api/v1/favorite-things/{}/'.format(
        str(second_favorite_thing.id)), {'ranking': 3},
                            content_type='application/json')

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 200
    assert content['ranking'] == 3

    third_favorite_thing.refresh_from_db()
    assert third_favorite_thing.ranking == 2

    response = client.patch('/api/v1/favorite-things/{}/'.format(
        str(third_favorite_thing.id)), {'ranking': 1},
                            content_type='application/json')

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 200
    assert content['ranking'] == 1

    third_favorite_thing.refresh_from_db()
    assert third_favorite_thing.ranking == 1
Beispiel #23
0
 def test_get(self, init_db, category):
     """Test for get method
     
         Args:
             init_db(SQLAlchemy): fixture to initialize the test database
             category (Category): Fixture to create a new category
     """
     assert Category.get(category.id) == category
Beispiel #24
0
def make_custom_page(url: str,
                     links: List[str] = [],
                     category: str = 'Social',
                     content: str = 'Social page content') -> Page:
    return Page(url=url,
                categories=[Category(name=category, occurrence=1)],
                content=content,
                links=[Link(link=lin, occurrences=1) for lin in links])
Beispiel #25
0
    def test_get_linked_groups_from_ids(self):
        """Returns groups with links pages"""
        url_zero = 'zero.onion'
        url_one = 'one.onion'
        url_two = 'two.onion'
        url_three = 'three.onion'
        links_zero = [url_zero, url_one, url_two, url_three]
        links_one = [url_zero, url_three]
        links_two = [url_two]
        links_three = []
        page_one = make_custom_page(url=url_one, links=links_one)
        page_zero = make_custom_page(url=url_zero, links=links_zero)
        page_two = make_custom_page(url=url_two, links=links_two)
        page_three = make_custom_page(url=url_three, links=links_three)
        pages = {url_zero: page_zero, url_one: page_one, url_two: page_two, url_three: page_three}
        group_id_one = 1
        group_id_two = 2
        partition = {url_zero: group_id_one, url_one: group_id_one, url_two: group_id_two, url_three: group_id_one}
        parent_group_id = '0.2'
        expected = [
            make_custom_group(
                group_id=parent_group_id + '.' + str(group_id_one),
                links=[Link(link='0.2.2', name='')],
                categories=[Category(name='Social', occurrence=3)],
                pages={url_zero: page_zero, url_one: page_one, url_three: page_three}
            ),
            make_custom_group(
                group_id=parent_group_id + '.' + str(group_id_two),
                links=[],
                categories=[Category(name='Social', occurrence=1)],
                pages={url_two: page_two}
            )]

        actual = get_linked_groups_from_ids(pages, partition, parent_group_id)

        self.assertEqual(len(expected), len(actual))
        self.assertEqual(expected[0].id, actual[0].id)
        self.assertEqual(expected[0].categories[0].name, actual[0].categories[0].name)
        self.assertEqual(expected[0].categories[0].occurrence, actual[0].categories[0].occurrence)
        self.assertEqual(len(expected[0].links), len(actual[0].links))
        self.assertEqual(len(expected[1].members), len(actual[1].members))
        self.assertEqual(expected[1].id, actual[1].id)
        self.assertEqual(expected[1].categories[0].name, actual[1].categories[0].name)
        self.assertEqual(expected[1].categories[0].occurrence, actual[1].categories[0].occurrence)
        self.assertEqual(len(expected[1].links), len(actual[1].links))
        self.assertEqual(len(expected[1].members), len(actual[1].members))
Beispiel #26
0
def make_group(group_id: str) -> Group:
    return Group(id=group_id,
                 links=[Link(link='0.3', occurrences=2)],
                 members={
                     oneUrl: make_page(oneUrl),
                     twoUrl: make_page(twoUrl)
                 },
                 categories=[Category(name='Social', occurrence=2)])
Beispiel #27
0
def make_meta_group(group_id: str) -> MetaGroup:
    return MetaGroup(
        id=group_id,
        links=[Link(link='0.3', occurrences=2)],
        first_members=[make_page(oneUrl), make_page(twoUrl)],
        categories=[Category(name='Social', occurrence=2)],
        members_count=2,
        domains_count=2,
    )
def test_create_favorite_thing_with_out_of_range_ranking_number(client):
    category = Category(name="Food")
    category.save()

    response = client.post(
        '/api/v1/favorite-things/',
        {
            'title': 'Rice',
            'category': str(category.id),
            'ranking': 4
        },
        content_type='application/json'
    )

    content = json.loads(response.content.decode("utf-8"))

    assert response.status_code == 400
    assert content == { 'ranking': ['number is out of ranking range'] }
def addCategory():
    request_body = request.get_json()
    category = Category(
        name_Category=request_body["name_Category"],
        description_Category=request_body["description_Category"],
        active_Product=request_body["active_Product"])
    print(request_body)
    db.session.add(category)
    db.session.commit()
    return jsonify("All good"), 200
Beispiel #30
0
def setCategories(request):
    if request.method == 'POST':
        categories = request.data.get('categories', None)
        for category in categories:
            id = category.get('id', None)
            name = category.get('name', None)
            print("{}, {}".format(id, name))
            Category(id=id, name=name).save()

        return Response(status=status.HTTP_200_OK)