def update_authors_author_table():
    # make a backup before deleting everything
    authors_backup = list(Author.objects.all())
    try:
        Author.objects.all().delete()
        authors_temp = AuthorTemp.objects.all()
        authors = [Author(
            nicname=item.nicname,
            profile_url=item.profile_url,
            avatar=item.avatar,
            number_of_followers=item.number_of_followers,
            workshop_submissions=item.workshop_submissions,
            coop_maps=item.coop_maps
        ) for item in authors_temp]
        Author.objects.bulk_create(authors)
        UpdateDate.objects.update_or_create(model_name='Author', defaults={
            'model_name': 'Author',
            'timestamp': datetime.utcnow()
        })
        print('All the authors have been successfully updated!')
    except:
        # in case something goes wrong restore the Author model from backup
        objects = [Author(
            nicname=item.nicname,
            profile_url=item.profile_url,
            avatar=item.avatar,
            number_of_followers=item.number_of_followers,
            workshop_submissions=item.workshop_submissions,
            coop_maps=item.coop_maps
        ) for item in authors_backup]
        Author.objects.bulk_create(objects)
        print('All authors have been restored from backup!')
    purge_steamids()
Esempio n. 2
0
    def mutate(self, info, first_name, last_name, bio=None):
        author = Author(first_name=first_name, last_name=last_name, bio=bio)
        author.save()

        return CreateAuthor(id=author.id,
                            first_name=author.first_name,
                            last_name=author.last_name,
                            bio=author.bio)
Esempio n. 3
0
    def test_get_book_page(self):
        author = Author(name="Test author name", photo="test.jpg")
        author.save()
        book = Books(title="Test for book", price=9.99,
                     author_id=author.id, photo_main="test.jpg")
        book.save()

        response = self.client.get("/books/book/1")
        self.assertEqual(response.status_code, 200)
Esempio n. 4
0
    def test_create_author(self):
        """It is possible to create an author inserting it into the db"""

        self.assertEqual(Author.objects.count(), 0)

        author_name = "John Doe"
        author = Author(name=author_name)
        author.save()

        self.assertEqual(Author.objects.count(), 1)
        self.assertEqual(Author.objects.first().name, author_name)
Esempio n. 5
0
 def get_or_create_author(self, author_name):
     """
     For convenience, creates an author if one with this name doesn't exist.
     """
     # TODO: make sure that this method doesn't add repeated authors
     try:
         author = Author.objects.get(name=author_name)
     except :
         author = Author(name=author_name)
         author.save()
     return author
Esempio n. 6
0
def add(request):

	if request.method == 'GET':
		form = AuthorAddForm()
	else:
		form = AuthorAddForm(request.POST)
		if form.is_valid():
			author=Author()
			author.name = form.cleaned_data['name']
			author.email = form.cleaned_data['email']
			author.save()
			return HttpResponseRedirect('/landingpage/')
	return render(request, 'authors/addauthor.html', {'addauthorform':form})
Esempio n. 7
0
    def mutate_and_get_payload(cls, root, info, **input):
        # проверяет токен
        token = input.get('token', None)
        if token != '******************':
            return "Invalid token"

        author = Author(
            name=input.get('name'),
            description=input.get('description'),
            photo=input.get('photo'),
            rating=input.get('rating', 0),
            show_counter=input.get('show_counter', 0),
            date_create=input.get('date_create', 0),
            book_count=input.get('book_count', 0),
            nationality_id=input.get('nationality', 0),
        )
        if input.get('pk'):
            author.pk = input.get('pk')
        if input.get('birthday'):
            author.birthday = input.get('birthday')
        if input.get('death'):
            author.death = input.get('death')
        if input.get('name_original'):
            author.name_original = input.get('name_original')

        author.save()

        return AddAuthor(author=author)
Esempio n. 8
0
    def test_get_book_page(self):
        """
        Tests that the book page view renders the book template
        """
        author = Author(name="Test Author Name", photo="test.jpg")
        author.save()
        book = Books(title="Test Book Title",
                     price=10.00,
                     author_id=author.id,
                     book_image="test.jpg")
        book.save()

        response = self.client.get("/books/book/1")
        self.assertEqual(response.status_code, 200)
Esempio n. 9
0
 def test_create(self):
     author = Author.create(name="testName", surname="s1", patronymic="p1")
     author = Author.objects.get(id=author.id)
     self.assertIsInstance(author, Author)
     self.assertEqual(author.name, "testName")
     self.assertEqual(author.surname, "s1")
     self.assertEqual(author.patronymic, "p1")
Esempio n. 10
0
 def test_get_by_id_positive(self):
     """Positive test of the CustomUser.get_by_id() method"""
     author = Author.get_by_id(101)
     self.assertEqual(author.id, 101)
     self.assertEqual(author.name, 'author1')
     self.assertEqual(author.surname, "s1")
     self.assertEqual(author.patronymic, "p1")
Esempio n. 11
0
    def handle(self, *args, **options):
        if options['authors'][0]:
            fpath = options['authors'][0]
            if not os.path.exists(fpath):
                raise CommandError("file doesn't exist")
            with open(fpath, 'r') as fp:
                line = fp.readline()
                if line.strip() == "name":
                    line = fp.readline()
                else:
                    raise CommandError("Wrong format file")
                cont = 0
                contp = 0
                authors_list = []
                self.stdout.write("Import started. This can take a while...")
                # Read every line in the file and bulk create on every 10000 registers
                while line:
                    author = Author(name=line.strip())
                    authors_list.append(author)
                    cont += 1
                    contp += 1
                    if contp == 10000:
                        contp = 0
                        Author.objects.bulk_create(authors_list)
                        authors_list = []
                        self.stdout.write("Imported " + str(cont) +
                                          " authors. Still running....")
                    line = fp.readline()
                if authors_list:
                    Author.objects.bulk_create(authors_list)
                self.stdout.write("Imported " + str(cont) + " authors from " +
                                  str(fpath))

        else:
            self.stdout.write("Fail")
Esempio n. 12
0
    def test_duplicated_author_error(self):
        """Trying to create authors with the same name raises an IntegrityError"""

        author_name = "John Doe"
        expected_message = (f"duplicate key value violates unique constraint "
                            f'"authors_author_name_key"\nDETAIL:  Key (name)='
                            f"({author_name}) already exists.\n")

        Author.objects.create(name=author_name)
        self.assertEqual(Author.objects.count(), 1)
        author = Author(name=author_name)

        with self.assertRaises(IntegrityError) as raised:
            with transaction.atomic():
                author.save()
        self.assertEqual(str(raised.exception), expected_message)
        self.assertEqual(Author.objects.count(), 1)
Esempio n. 13
0
 def save(self, request):
     adapter = get_adapter()
     user = Author()
     self.cleaned_data = self.get_cleaned_data()
     adapter.save_user(request, user, self)
     self.custom_signup(request, user)
     setup_user_email(request, user, [])
     return user
Esempio n. 14
0
def create_author(request):
    form_author = AuthorForm()
    context = {'form_author': form_author}
    if request.method == 'POST':
        form_author = AuthorForm(request.POST)

        if form_author.is_valid():
            name = request.POST.get('name', )
            surname = request.POST.get('surname', )
            birthYear = request.POST.get('birthYear', )
            facePhoto = request.POST.get('facePhoto', )
            author_obj = Author(name=name,
                                surname=surname,
                                birthYear=birthYear,
                                facePhoto=facePhoto)
            author_obj.save()
            all_authors = Author.objects.all()
            context = {
                'all_authors': all_authors,
            }
        return render(request, 'authors/index.html', context)
    return render(request, 'authors/create_author.html', context)
Esempio n. 15
0
 def create_author(self, data):
     """
         Functionality:
         Params:
         Response:
     """
     try:
         author = Author.objects.filter(
             profile_id=data["profile"])[:1].get()
     except:
         author = None
     try:
         if author is None:
             profile = Profile.objects.get(pk=data["profile"])
             setattr(profile, "is_authorized", True)
             profile.save()
             author = Author(profile=profile, anonym=data["anonym"])
             author.save()
             serializer = AuthorSerializer(author)
             return serializer.data
         else:
             return {"message": "Already Exists"}
     except:
         return {"error_code": 404}
Esempio n. 16
0
 def handle(self, *args, **options):
     filename = options['file']
     if not filename:
         raise CommandError('Not filename')
     errors = False
     with open(filename, 'r', newline='', encoding='utf-8') as file:
         reader = csv.DictReader(file, delimiter=';')
         try:
             authors = [Author(name=row['name']) for row in reader]
         except KeyError:
             errors = True
     if errors:
         self.stdout.write(self.style.ERROR('Please, insert "name" column in CSV file'))
         return
     created = Author.objects.bulk_create(authors, ignore_conflicts=True)
     count = len(created)
     if not count:
         self.stdout.write(self.style.WARNING('Author not inserted in the base, check registers'))
     self.stdout.write(
         self.style.SUCCESS(
             f'Imported CSV file {count} '
             f'author{"s" if count != 1 else ""}. '
         )
     )
Esempio n. 17
0
class TestAuthorModel(TestCase):
    """Class for CustomUser Model test"""
    def setUp(self):
        """ Create a user object to be used by the tests """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            self.user = CustomUser(id=111,
                                   email='*****@*****.**',
                                   password='******',
                                   first_name='fname',
                                   middle_name='mname',
                                   last_name='lname')
            self.user.save()
            self.user_free = CustomUser(id=222,
                                        email='*****@*****.**',
                                        password='******',
                                        first_name='2fname',
                                        middle_name='2mname',
                                        last_name='2lname')
            self.user_free.save()

            self.author1 = Author(id=101,
                                  name="author1",
                                  surname="s1",
                                  patronymic="p1")
            self.author1.save()

            self.author2 = Author(id=102,
                                  name="author2",
                                  surname="s2",
                                  patronymic="p2")
            self.author2.save()

            self.book1 = Book(id=101,
                              name="book1",
                              description="description1",
                              count=1)
            self.book1.save()
            self.book1.authors.add(self.author1)
            self.book1.save()

            self.book2 = Book(id=102, name="book2", description="description2")
            self.book2.save()
            self.book2.authors.add(self.author2)
            self.book2.save()

            self.book3 = Book(id=103, name="book3", description="description3")
            self.book3.save()
            self.book3.authors.add(self.author1)
            self.book3.authors.add(self.author2)
            self.book3.save()

            self.order1 = Order(id=101,
                                user=self.user,
                                book=self.book1,
                                plated_end_at=TEST_DATE)
            self.order1.save()
            self.order2 = Order(id=102,
                                user=self.user,
                                book=self.book2,
                                plated_end_at=TEST_DATE)
            self.order2.save()
            self.order3 = Order(id=103,
                                user=self.user,
                                book=self.book3,
                                end_at=TEST_DATE_END,
                                plated_end_at=TEST_DATE)
            self.order3.save()

    def test__str__(self):
        """Test of the CustomUser.__str__() method"""
        author_returned = str(Author.objects.get(id=101))
        author_to_expect = "'id': 101, 'name': 'author1', 'surname': 's1', 'patronymic': 'p1'"

        self.assertEqual(author_returned, author_to_expect)

    def test__repr__(self):
        """Test of the CustomUser.__repr__() method"""
        author_returned = repr(Author.objects.get(id=102))
        author_to_expect = "Author(id=102)"

        self.assertEqual(author_returned, author_to_expect)

    def test_get_by_id_positive(self):
        """Positive test of the CustomUser.get_by_id() method"""
        author = Author.get_by_id(101)
        self.assertEqual(author.id, 101)
        self.assertEqual(author.name, 'author1')
        self.assertEqual(author.surname, "s1")
        self.assertEqual(author.patronymic, "p1")

    def test_get_by_id_negative(self):
        """Negative test of the CustomUser.get_by_id() method"""
        author = Author.get_by_id(999)
        self.assertIsNone(author)

    def test_delete_by_id_positive(self):
        """ Test of the CustomUser.delete_by_id() method """
        self.assertTrue(Author.delete_by_id(101))
        self.assertRaises(Author.DoesNotExist, Author.objects.get, pk=101)

    def test_delete_by_id_negative(self):
        """ Test of the CustomUser.delete_by_id() method """
        self.assertFalse(Author.delete_by_id(999))

    def test_get_all(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        authors = list(Author.get_all())
        authors.sort(key=lambda author: author.id)
        self.assertListEqual(authors, [self.author1, self.author2])

    def test_update(self):
        author = Author.objects.get(id=101)
        author.update(name="testName",
                      surname="testSurname",
                      patronymic="testPatronymic")

        author = Author.objects.get(id=101)
        self.assertIsInstance(author, Author)
        self.assertEqual(author.name, "testName")
        self.assertEqual(author.surname, "testSurname")
        self.assertEqual(author.patronymic, "testPatronymic")

    def test_update_only_name(self):
        author = Author.objects.get(id=101)
        author.update(name="testName")

        author = Author.objects.get(id=101)
        self.assertIsInstance(author, Author)
        self.assertEqual(author.name, "testName")
        self.assertEqual(author.surname, "s1")
        self.assertEqual(author.patronymic, "p1")

    def test_update_not_valid_name(self):
        author = Author.objects.get(id=101)
        author.update(name="testName" * 5)

        author = Author.objects.get(id=101)
        self.assertIsInstance(author, Author)
        self.assertEqual(author.name, "author1")
        self.assertEqual(author.surname, "s1")
        self.assertEqual(author.patronymic, "p1")

    def test_create(self):
        author = Author.create(name="testName", surname="s1", patronymic="p1")
        author = Author.objects.get(id=author.id)
        self.assertIsInstance(author, Author)
        self.assertEqual(author.name, "testName")
        self.assertEqual(author.surname, "s1")
        self.assertEqual(author.patronymic, "p1")

    def test_createnot_valid_surname(self):
        author = Author.create(name="testName",
                               surname="s1" * 20,
                               patronymic="p1")
        self.assertIsNone(author)
Esempio n. 18
0
 def test_get_all(self):
     """ Positive Test of the CustomUser.create method TEST_DATE_END"""
     authors = list(Author.get_all())
     authors.sort(key=lambda author: author.id)
     self.assertListEqual(authors, [self.author1, self.author2])
Esempio n. 19
0
 def test_delete_by_id_negative(self):
     """ Test of the CustomUser.delete_by_id() method """
     self.assertFalse(Author.delete_by_id(999))
Esempio n. 20
0
 def test_delete_by_id_positive(self):
     """ Test of the CustomUser.delete_by_id() method """
     self.assertTrue(Author.delete_by_id(101))
     self.assertRaises(Author.DoesNotExist, Author.objects.get, pk=101)
Esempio n. 21
0
 def test_get_by_id_negative(self):
     """Negative test of the CustomUser.get_by_id() method"""
     author = Author.get_by_id(999)
     self.assertIsNone(author)
Esempio n. 22
0
 def test_author_of_month_defaults_to_False(self):
   author = Author(name="Test author name")
   author.save()
   self.assertEqual(author.name, "Test author name")
   self.assertFalse(author.is_author_of_month)
Esempio n. 23
0
def add_video_task(id=None,
                   active=False,
                   category_ids=None,
                   description=None,
                   file_url=None,
                   frame_time=3.0,
                   rating_avg=None,
                   title=None,
                   rating_count=0,
                   slug=None,
                   tags=None,
                   user_id=None,
                   add_date=None,
                   hits=0,
                   author_names=None,
                   highlighted=False,
                   imported=False,
                   id_se=None,
                   process=False):
    from .models import Video
    from categories.models import Category
    from cms_local.models import SEImportedVideo

    files_to_delete = []

    video = Video()
    if id:
        video.id = id
        if Video.objects.filter(id=id).exists():
            raise VideoAlreadyExists('film o id %d juz istnieje' % id)
    video.active = active
    video.description = description
    video.frame_time = frame_time
    if slug is None:
        from murator_common.util.slughifi import slughifi
        slug = slughifi(title)
    video.slug = slug
    video.title = title
    video.tags = tags
    video.user_id = user_id
    video.hits = hits
    video.highlighted = highlighted
    video.imported = imported
    video.add_date = add_date
    video.pub_date = add_date

    # pobieram plik do tempa
    tmpdir = os.path.join(settings.VIDEO_TMP,
                          hashlib.md5(file_url).hexdigest())
    if not os.path.exists(tmpdir):
        os.makedirs(tmpdir)
    from urllib import urlopen
    response = urlopen(file_url)
    video_file_content = response.read()
    tmp_src_path = os.path.join(tmpdir, os.path.basename(file_url))
    tmp_src = open(tmp_src_path, 'wb')
    tmp_src.write(video_file_content)
    tmp_src.close()
    video.file.save(os.path.basename(tmp_src_path),
                    ContentFile(video_file_content))

    video_filename = tmp_src_path

    files_to_delete.append(video_filename)

    video.save()

    if id_se:
        seiv = SEImportedVideo(id_se=id_se, video=video)
        seiv.save()

    for category_id in category_ids:
        try:
            category = Category.objects.get(id=category_id)
        except Category.DoesNotExist:
            # TODO: moze logowac?
            pass
        else:
            video.categories.add(category)

    for author_name in author_names:
        from authors.models import Author
        try:
            author = Author.objects.get(name=author_name)
        except Author.DoesNotExist:
            author = Author(name=author_name, real_name=author_name)
            author.save()
        finally:
            video.authors.add(author)

    for i in range(rating_count):
        video.rating.add(score=rating_avg, user=None, ip_address='127.0.0.1')

    video.save()

    if process:
        # TODO: przekopiowac pare rzeczy z process_video_task

        # pobieram info o pliku
        codec, width, height, duration = retrieve_info(video_filename)
        video.codec = codec
        video.width = width
        video.height = height
        video.aspect_ratio = video._calculate_ratio()

        # generowanie screena
        frame_filename = save_frame(video_filename, video)
        files_to_delete.append(frame_filename)

        # zapisanie całości zmian
        video.save()

        # generowanie formatów video
        formats = (settings.DEFAULT_VIDEO_FORMAT, )
        format_filenames = save_formats(formats, video_filename, video)
        files_to_delete += format_filenames

    # sprzątnięcie zbędnych plików w tempie
    clean_files(*files_to_delete)
Esempio n. 24
0
class TestOrderModel(TestCase):
    """Class for CustomUser Model test"""
    def setUp(self):
        """ Create a user object to be used by the tests """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            self.user = CustomUser(id=111,
                                   email='*****@*****.**',
                                   password='******',
                                   first_name='fname',
                                   middle_name='mname',
                                   last_name='lname')
            self.user.save()
            self.user_free = CustomUser(id=222,
                                        email='*****@*****.**',
                                        password='******',
                                        first_name='2fname',
                                        middle_name='2mname',
                                        last_name='2lname')
            self.user_free.save()

            self.author1 = Author(id=101,
                                  name="author1",
                                  surname="s1",
                                  patronymic="p1")
            self.author1.save()

            self.author2 = Author(id=102,
                                  name="author2",
                                  surname="s2",
                                  patronymic="p2")
            self.author2.save()

            self.book1 = Book(id=101,
                              name="book1",
                              description="description1",
                              count=1)
            self.book1.save()
            self.book1.authors.add(self.author1)
            self.book1.save()

            self.book2 = Book(id=102, name="book2", description="description2")
            self.book2.save()
            self.book2.authors.add(self.author2)
            self.book2.save()

            self.book3 = Book(id=103, name="book3", description="description3")
            self.book3.save()
            self.book3.authors.add(self.author1)
            self.book3.authors.add(self.author2)
            self.book3.save()

            self.order1 = Order(id=101,
                                user=self.user,
                                book=self.book1,
                                plated_end_at=TEST_DATE)
            self.order1.save()
            self.order2 = Order(id=102,
                                user=self.user,
                                book=self.book2,
                                plated_end_at=TEST_DATE)
            self.order2.save()
            self.order3 = Order(id=103,
                                user=self.user,
                                book=self.book3,
                                end_at=TEST_DATE_END,
                                plated_end_at=TEST_DATE)
            self.order3.save()

    def test__str__end_at_is_None(self):
        """Test of the CustomUser.__str__() method"""
        order_returned = str(Order.objects.get(id=101))
        order_to_expect = "'id': 101, " \
                          "'user': CustomUser(id=111), " \
                          "'book': Book(id=101), " \
                          "'created_at': '2017-04-10 12:00:00+00:00', " \
                          "'end_at': None, " \
                          "'plated_end_at': '2017-04-10 12:00:00+00:00'"

        self.assertEqual(order_returned, order_to_expect)

    def test__str__end_at_is_not_None(self):
        """Test of the CustomUser.__str__() method"""
        order = str(Order.objects.get(id=103))
        order_to_expect = "'id': 103, " \
                          "'user': CustomUser(id=111), " \
                          "'book': Book(id=103), " \
                          "'created_at': '2017-04-10 12:00:00+00:00', " \
                          "'end_at': '2017-04-25 12:00:00+00:00', " \
                          "'plated_end_at': '2017-04-10 12:00:00+00:00'"

        self.assertEqual(order, order_to_expect)

    def test__repr__(self):
        """Test of the CustomUser.__repr__() method"""
        user_returned = repr(Order.objects.get(id=102))
        user_to_expect = "Order(id=102)"

        self.assertEqual(user_returned, user_to_expect)

    def test_get_by_id_positive(self):
        """Positive test of the CustomUser.get_by_id() method"""
        order = Order.get_by_id(101)
        self.assertEqual(order.id, 101)
        self.assertEqual(order.user, self.user)
        self.assertEqual(order.book, self.book1)
        self.assertEqual(order.created_at, TEST_DATE)
        self.assertEqual(order.end_at, None)
        self.assertEqual(order.plated_end_at, TEST_DATE)

    def test_get_by_id_negative(self):
        """Negative test of the CustomUser.get_by_id() method"""
        order = Order.get_by_id(55)
        self.assertIsNone(order)

    def test_delete_by_id_positive(self):
        """ Test of the CustomUser.delete_by_id() method """
        self.assertTrue(Order.delete_by_id(103))
        self.assertRaises(Order.DoesNotExist, Order.objects.get, pk=103)
        self.assertEqual(self.book3, Book.objects.get(id=103))
        self.assertEqual(self.user, CustomUser.objects.get(id=111))

    def test_delete_by_id_negative(self):
        """ Test of the CustomUser.delete_by_id() method """
        self.assertFalse(Order.delete_by_id(999))

    def test_create_positive(self):
        """ Positive Test of the CustomUser.create method """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            order = Order.create(self.user_free, self.book2, TEST_DATE_END)
            self.assertIsInstance(order, Order)
            self.assertEqual(order.user, self.user_free)
            self.assertEqual(order.book, self.book2)
            self.assertEqual(order.created_at, TEST_DATE)
            self.assertIsNone(order.end_at)
            self.assertEqual(order.plated_end_at, TEST_DATE_END)

    def test_create_negative_not_saved_user(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        user = CustomUser()
        order = Order.create(user, self.book2, TEST_DATE_END)
        self.assertIsNone(order)

    def test_create_negative_limit_book(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""

        order = Order.create(self.user_free, self.book1, TEST_DATE_END)
        self.assertIsNone(order)

    def test_get_all(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        orders = Order.get_all()
        self.assertListEqual(orders, [self.order1, self.order2, self.order3])

    def test_get_not_returned_books(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        orders = Order.get_not_returned_books()
        self.assertListEqual(orders, [self.order1, self.order2])

    def test_update_plated_end_at(self):
        order = Order.objects.get(id=101)
        new_date = TEST_DATE_END + datetime.timedelta(days=4)
        order.update(plated_end_at=new_date)

        order = Order.objects.get(id=101)
        self.assertEqual(order.id, 101)
        self.assertEqual(order.user, self.user)
        self.assertEqual(order.book, self.book1)
        self.assertEqual(order.created_at, TEST_DATE)
        self.assertEqual(order.end_at, None)
        self.assertEqual(order.plated_end_at, new_date)

    def test_update_end_at(self):
        order = Order.objects.get(id=101)
        new_date = TEST_DATE_END + datetime.timedelta(days=4)
        order.update(end_at=new_date)

        order = Order.objects.get(id=101)
        self.assertEqual(order.id, 101)
        self.assertEqual(order.user, self.user)
        self.assertEqual(order.book, self.book1)
        self.assertEqual(order.created_at, TEST_DATE)
        self.assertEqual(order.end_at, new_date)
        self.assertEqual(order.plated_end_at, TEST_DATE)
Esempio n. 25
0
class TestBookModel(TestCase):
    """Class for CustomUser Model test"""
    def setUp(self):
        """ Create a user object to be used by the tests """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            self.user = CustomUser(id=111,
                                   email='*****@*****.**',
                                   password='******',
                                   first_name='fname',
                                   middle_name='mname',
                                   last_name='lname')
            self.user.save()
            self.user_free = CustomUser(id=222,
                                        email='*****@*****.**',
                                        password='******',
                                        first_name='2fname',
                                        middle_name='2mname',
                                        last_name='2lname')
            self.user_free.save()

            self.author1 = Author(id=101,
                                  name="author1",
                                  surname="s1",
                                  patronymic="p1")
            self.author1.save()

            self.author2 = Author(id=102,
                                  name="author2",
                                  surname="s2",
                                  patronymic="p2")
            self.author2.save()

            self.book1 = Book(id=101,
                              name="book1",
                              description="description1",
                              count=1)
            self.book1.save()
            self.book1.authors.add(self.author1)
            self.book1.save()

            self.book2 = Book(id=102, name="book2", description="description2")
            self.book2.save()
            self.book2.authors.add(self.author2)
            self.book2.save()

            self.book3 = Book(id=103, name="book3", description="description3")
            self.book3.save()
            self.book3.authors.add(self.author1)
            self.book3.authors.add(self.author2)
            self.book3.save()

            self.order1 = Order(id=101,
                                user=self.user,
                                book=self.book1,
                                plated_end_at=TEST_DATE)
            self.order1.save()
            self.order2 = Order(id=102,
                                user=self.user,
                                book=self.book2,
                                plated_end_at=TEST_DATE)
            self.order2.save()
            self.order3 = Order(id=103,
                                user=self.user,
                                book=self.book3,
                                end_at=TEST_DATE_END,
                                plated_end_at=TEST_DATE)
            self.order3.save()

    def test__str__(self):
        """Test of the CustomUser.__str__() method"""
        book_returned = str(Book.objects.get(id=101))
        book_to_expect = "'id': 101, 'name': 'book1', 'description': 'description1', 'count': 1, 'authors': [101]"

        self.assertEqual(book_returned, book_to_expect)

    def test__repr__(self):
        """Test of the CustomUser.__repr__() method"""
        book_returned = repr(Book.objects.get(id=102))
        book_to_expect = "Book(id=102)"

        self.assertEqual(book_returned, book_to_expect)

    def test_get_by_id_positive(self):
        """Positive test of the CustomUser.get_by_id() method"""
        book = Book.get_by_id(101)
        self.assertEqual(book.id, 101)
        self.assertEqual(book.name, 'book1')
        self.assertEqual(book.description, "description1")
        self.assertEqual(book.count, 1)
        self.assertListEqual(list(book.authors.all()), [self.author1])

    def test_get_by_id_negative(self):
        """Negative test of the CustomUser.get_by_id() method"""
        book = Book.get_by_id(999)
        self.assertIsNone(book)

    def test_delete_by_id_positive(self):
        """ Test of the CustomUser.delete_by_id() method """
        self.assertTrue(Book.delete_by_id(103))
        self.assertRaises(Book.DoesNotExist, Book.objects.get, pk=103)
        self.assertRaises(Order.DoesNotExist, Order.objects.get, pk=103)
        self.assertEqual(self.author1, Author.objects.get(id=101))
        self.assertEqual(self.author2, Author.objects.get(id=102))

    def test_delete_by_id_negative(self):
        """ Test of the CustomUser.delete_by_id() method """
        self.assertFalse(Book.delete_by_id(999))

    def test_create_positive_name_description(self):
        """ Positive Test of the CustomUser.create method """

        book = Book.create(name="testBook", description="testDescription")
        self.assertIsInstance(book, Book)
        self.assertEqual(book.name, "testBook")
        self.assertEqual(book.description, "testDescription")
        self.assertEqual(book.count, 10)
        self.assertListEqual(list(book.authors.all()), [])

    def test_create_positive_name_description_empty(self):
        """ Positive Test of the CustomUser.create method """

        book = Book.create(name="testBook", description="")
        self.assertIsInstance(book, Book)
        self.assertEqual(book.name, "testBook")
        self.assertEqual(book.description, "")
        self.assertEqual(book.count, 10)
        self.assertListEqual(list(book.authors.all()), [])

    def test_create_positive_name_description_count(self):
        """ Positive Test of the CustomUser.create method """

        book = Book.create(name="testBook",
                           description="testDescription",
                           count=5)
        self.assertIsInstance(book, Book)
        self.assertEqual(book.name, "testBook")
        self.assertEqual(book.description, "testDescription")
        self.assertEqual(book.count, 5)
        self.assertListEqual(list(book.authors.all()), [])

    def test_create_positive_name_description_count_a(self):
        """ Positive Test of the CustomUser.create method """

        book = Book.create(name="testBook",
                           description="testDescription",
                           count=5,
                           authors=[self.author1, self.author2])
        self.assertIsInstance(book, Book)
        self.assertEqual(book.name, "testBook")
        self.assertEqual(book.description, "testDescription")
        self.assertEqual(book.count, 5)
        self.assertListEqual(list(book.authors.all()),
                             [self.author1, self.author2])

    def test_create_negative_len_name(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        book = Book.create(name="1" * 128, description="12")
        self.assertIsInstance(book, Book)
        book = Book.create(name="1" * 129, description="12")
        self.assertIsNone(book)

    def test_get_all(self):
        """ Positive Test of the CustomUser.create method TEST_DATE_END"""
        books = Book.get_all()
        books.sort(key=lambda book: book.id)
        self.assertListEqual(books, [self.book1, self.book2, self.book3])

    def test_add_authors(self):
        book = Book.objects.get(id=103)
        book.add_authors([self.author2])

        book = Book.objects.get(id=103)
        self.assertListEqual(list(book.authors.all()),
                             [self.author1, self.author2])

    def test_add_authors_duplicate(self):
        book = Book.objects.get(id=103)
        book.add_authors([self.author1, self.author2])

        book = Book.objects.get(id=103)
        self.assertListEqual(list(book.authors.all()),
                             [self.author1, self.author2])

    def test_remove_authors(self):
        book = Book.objects.get(id=103)
        book.remove_authors([self.author1, self.author2])

        book = Book.objects.get(id=103)
        self.assertListEqual(list(book.authors.all()), [])

    def test_update(self):
        book = Book.objects.get(id=101)
        book.update(name="testName", description="testDescription", count=5)
        book = Book.objects.get(id=101)
        self.assertIsInstance(book, Book)
        self.assertEqual(book.name, "testName")
        self.assertEqual(book.description, "testDescription")
        self.assertEqual(book.count, 5)
        self.assertListEqual(list(book.authors.all()), [self.author1])

    def test_update_name(self):
        book = Book.objects.get(id=101)
        book.update(name="testName")
        book = Book.objects.get(id=101)
        self.assertIsInstance(book, Book)
        self.assertEqual(book.name, "testName")
        self.assertEqual(book.description, "description1")
        self.assertEqual(book.count, 1)
        self.assertListEqual(list(book.authors.all()), [self.author1])
Esempio n. 26
0
 def test_createnot_valid_surname(self):
     author = Author.create(name="testName",
                            surname="s1" * 20,
                            patronymic="p1")
     self.assertIsNone(author)
Esempio n. 27
0
from random import randint

from faker import Faker

from authors.models import Author
from books.models import Book
from genres.models import Genre
from publishers.models import Publisher

fake = Faker()

# Add Authors
for x in range(0, 20):
    author = Author(
        first_name=fake.first_name(),
        last_name=fake.last_name(),
        about=fake.paragraphs(nb=2),
    )
    author.save()

# Add Genre
genre_list = ['Action', 'Literary', 'Romance', 'Humor', 'Science', 'History',
              'Cooking', 'Graphic Novel']

for word in genre_list:
    genre = Genre(name=word, about=fake.paragraphs(nb=1))
    genre.save()

# Add Publisher
for x in range(0, 11):
    publisher = Publisher(name=fake.company(),
Esempio n. 28
0
def import_from_litres(hour=23, minutes=59):
    image_template = 'https://partnersdnld.litres.ru/static/bookimages/{0}/{1}/{2}/{3}.bin.dir/{3}.cover.{4}'
    d = datetime.date.today()
    api = LitresApi(secret_key='D7psdo2s*Xjsoq3WdsoSWWvoo', partner_id='YABK')
    lazy_books = api.get_fresh_book(
        start_date=datetime.datetime(d.year, d.month, d.day - 1, 0, 0),
        end_date=datetime.datetime(d.year, d.month, d.day - 1, hour, minutes))

    for lazy_book in lazy_books:
        if lazy_book.get('@lang') == 'ru':
            litres_id = lazy_book.get('@id')
            litres_file_id = lazy_book.get('@file_id')
            litres_book = lazy_book.get('title-info')
            litres_authors = litres_book.get('author')
            litres_genres = lazy_book.get('genres')
            litres_series = lazy_book.get('sequences')
            title = litres_book.get('book-title')
            description = litres_book.get('annotation')
            age = lazy_book.get('@adult')

            try:
                publish_info = lazy_book.get('publish-info')
                if publish_info:
                    year = publish_info.get('year', 0)
                    isbn = publish_info.get('isbn', '').replace('-', '')
                else:
                    date = litres_book.get('date', 0)
                    if type(date) is str:
                        year = date
                    elif type(date) is list:
                        if date.get('#text'):
                            year = date.get('#text', 0)

                    if lazy_book.get('@isbn'):
                        isbn = lazy_book.get('@isbn', '').replace('-', '')
                    else:
                        isbn = lazy_book.get('@litres_isbn',
                                             '').replace('-', '')
            except Exception as e:
                print('Exception {}'.format(e))
                print(json.dumps(lazy_book, indent=4, ensure_ascii=False))

            ext = lazy_book.get('@cover')
            rating = decimal.Decimal(lazy_book.get('@rating', 0))

            # Импорт автора
            libs_authors = []
            for litres_author in litres_authors:
                try:
                    author = Author.objects.get(
                        litres_id=litres_author.get('id'))
                    libs_authors.append(author.id)
                except Author.DoesNotExist:
                    fi = "{} {}".format(litres_author.get('last-name'),
                                        litres_author.get('first-name'))
                    fi = fi.replace('None', '').strip()
                    authors = Author.objects.filter(name__icontains=fi)
                    if len(authors) == 1:
                        author = authors[0]
                        libs_authors.append(author.id)
                        author.litres_id = litres_author.get('id')
                        author.save(update_fields=['litres_id'])
                        print("Обновил litres_id для автора {} {}".format(
                            author.id, author.name))
                    elif len(authors) > 1:
                        print("Множество совпадений авторов {} для книги {}".
                              format(litres_authors, litres_book))
                    else:
                        fi = "{} {}".format(litres_author.get('first-name'),
                                            litres_author.get('last-name'))
                        fi = fi.replace('None', '').strip()
                        authors = Author.objects.filter(name__icontains=fi)
                        if len(authors) == 1:
                            author = authors[0]
                            libs_authors.append(author.id)
                            author.litres_id = litres_author.get('id')
                            author.save(update_fields=['litres_id'])
                            print("Обновил litres_id для автора {} {}".format(
                                author.id, author.name))
                        elif len(authors) > 1:
                            print(
                                "Множество совпадений авторов {} для книги {}".
                                format(litres_authors, litres_book))
                        else:
                            # Добавляет нового автора

                            fi = "{} {}".format(
                                litres_author.get('last-name'),
                                litres_author.get('first-name'))
                            fio = "{} {} {}".format(
                                litres_author.get('last-name', ''),
                                litres_author.get('first-name', ''),
                                litres_author.get('middle-name', ''))

                            author = Author(
                                name=fi.replace('None', '').strip(),
                                litres_name=fio.replace('None', '').strip(),
                            )
                            author.save()
                            libs_authors.append(author.id)

            # Опрееление жанра
            libs_genres = []
            if litres_genres:
                litres_genres = litres_genres['genre']
                for litres_genre in litres_genres:
                    genres_new = GenreNew.objects.filter(
                        genre_litres__icontains=litres_genre['@id'])

                    for genre_new in genres_new:
                        libs_genres.append(genre_new.id)

                    if not len(genres_new):
                        print("Жанр {} {} не найден".format(
                            litres_genre['@title'], litres_genre['@id']))

            # Если есть серия
            libs_series = None
            if litres_series:
                litres_series = litres_series.get('sequence')[0]
                try:
                    # Проверяет по id
                    libs_series = Series.objects.get(
                        litres_id=litres_series['@uuid'])
                except Series.DoesNotExist:
                    try:
                        # проверяет по названию
                        libs_series = Series.objects.get(
                            title=litres_series['@name'])
                        libs_series.litres_id = litres_series['@uuid']
                        libs_series.save(update_fields=['litres_id'])
                        print("Обновил litres_id для серии {} {}".format(
                            libs_series.id, libs_series.title))
                    except Series.MultipleObjectsReturned:
                        print("Задвоилась серия {} {}".format(
                            libs_series.id, libs_series.title))
                    except Series.DoesNotExist:
                        # Добавляет новую серию
                        libs_series = Series(title=litres_series['@name'],
                                             litres_id=litres_series['@uuid'])
                        libs_series.save()

            # Ипорт книги
            try:
                book = Book.objects.get(litres_id=litres_id)
            except Book.MultipleObjectsReturned:
                print("Затроило книги litres_id {} isbn {}".format(
                    litres_id, isbn))
            except Book.DoesNotExist:
                # Проверяет по isbn
                try:
                    if len(isbn):
                        book = Book.objects.get(isbn=isbn)
                        book.litres_id = litres_id
                        book.save(update_fields=['litres_id'])
                        print("Обновил litres_id для книги {} {}".format(
                            book.id, book.title))
                    else:
                        print("Пустой isbn litres_id {} isbn {}".format(
                            litres_id, isbn))
                except Book.MultipleObjectsReturned:
                    print("Затроило книги litres_id {} isbn {}".format(
                        litres_id, isbn))
                except Book.DoesNotExist:
                    # Проверяет совпадение по назанию
                    if title and litres_author.get('last-name'):
                        book = Book.objects.filter(
                            title__icontains=title,
                            author__name__icontains=litres_author.get(
                                'last-name'))
                        if len(book) == 1:
                            b = book[0]
                            b.litres_id = litres_id
                            b.isbn = isbn
                            b.save(update_fields=['litres_id', 'isbn'])
                            print("Обновил litres_id и isbn для книги {} {}".
                                  format(b.id, b.title))
                        elif len(book) > 1:
                            print("Множество совпадений c книгой {}".format(
                                litres_book))
                        else:
                            litres_file_id_str = "{0:08d}".format(
                                int(litres_file_id))
                            xx = litres_file_id_str[0:2]
                            yy = litres_file_id_str[2:4]
                            zz = litres_file_id_str[4:6]

                            image = image_template.format(
                                xx, yy, zz, litres_file_id, ext)

                            if rating >= 4:
                                rating = 4

                            book = Book(title=title,
                                        description=description,
                                        age=age,
                                        year=year,
                                        isbn=isbn,
                                        litres_id=litres_id,
                                        image=image,
                                        rating=rating)

                            if decimal.Decimal(rating) > 0:
                                book.rating_partner_votes = 1

                            if libs_series:
                                book.series = libs_series
                            try:
                                book.save()
                            except decimal.InvalidOperation:
                                book.rating = 0
                                book.save()

                            book.genre_new.set(libs_genres)
                            book.author.set(libs_authors)
Esempio n. 29
0
 def test_can_create_an_author_with_a_name_and_status(self):
   author = Author(name="Test author name", is_author_of_month=True)
   author.save()
   self.assertEqual(author.name, "Test author name")
   self.assertTrue(author.is_author_of_month)
def getPosts(request):

	# Page num and size, default if not given
	page_num = request.GET.get('page', DEFAULT_PAGE_NUM)	
	page_size = request.GET.get('size', DEFAULT_PAGE_SIZE)

	# Author id as a query parameter
	queryID = request.GET.get('id', False)
	if queryID:
		try:
		# Get the local author
			author = Author.objects.get(author_id=queryID)
			print author
			# Get all of the authors friends
			local_friends = Author.getLocalFriends(author)
			global_friends = Author.getGlobalFriends(author)

			# Get all of the public posts on the node
			all_posts = Post.objects.filter(visibility="PUBLIC")

			# LOCAL FOAF STUFF
			# Need to go via all local users' local friends first to see if the <author_id> is friends
			all_local_authors = Author.objects.all() # need to exclude self?
			for local_author in all_local_authors:
				print local_author.user

				# get author's global friends and see if the global <author_id> is friends or not.
				localFriends = set(local_author.getLocalFriends())
				
				globalFriendsList = local_author.getGlobalFriends()
				localFriendsList = local_author.getLocalFriends()

				# Already friends
				if author in localFriends:
					all_posts = chain(all_posts, Post.objects.filter(visibility="SERVERONLY", author=local_author))
					all_posts = chain(all_posts, Post.objects.filter(visibility="FRIENDS", author=local_author))
					all_posts = chain(all_posts, Post.objects.filter(visibility="FOAF", author=local_author))
				else:
					# Send POST to /api/friends/<queryID> to check if anyone in the list is a friend
					# check if <author_id> is friends with any one of local_author's friends


					local_author_friends = list(itertools.chain(localFriendsList, globalFriendsList))
					id_list = []

					if len(local_author_friends) > 0:

						for friend in local_author_friends:
							if friend.getClassName() == "Author":
								id_list.append(friend.author_id)
							elif friend.getClassName() == "GlobalAuthor":
								id_list.append(friend.global_author_id)

						requestObj = {
							"query":"friends",
							"author":queryID,
							"authors": id_list
						}

						response = CheckForMutualFriends(requestObj, author)

						FOAF_list = response['authors']
						print "FOAF"
						print FOAF_list

						if len(FOAF_list) > 0:
							# at least 1 mutual friend exists between local <author_id> and local_author
							all_posts = chain(all_posts, Post.objects.filter(visibility="FOAF", author=local_author))
									

			all_posts = list(all_posts)

			# Need this here or else the pagination bitches about it being unicode
			page_num = int(page_num)
			# # Get the right page
			pages = Paginator(all_posts, page_size)
			page = pages.page(page_num+1)
			data = page.object_list
			response_obj = {}
			response_obj['query'] = 'posts'
			response_obj['count'] = len(all_posts)
			response_obj['size'] = page_size

			if page.has_next():
				response_obj['next'] = settings.LOCAL_HOST + 'author/posts/?id=' + queryID + '&page=' + str(page_num + 1) + '&size=' + str(page_size)
			if page.has_previous():
				response_obj['previous'] = settings.LOCAL_HOST + 'author/posts/?id=' + queryID + '&page=' + str(page_num - 1) + '&size=' + str(page_size)

			serializer = PostSerializer(data, many=True)
			response_obj['posts'] = serializer.data

			return Response(response_obj)

			serializer = PostSerializer(all_posts, many=True)
			return Response(serializer.data)
		except:
			print 'why you here'
			print queryID
			author = GlobalAuthor.objects.get(global_author_id = queryID)
			# Get all of the public posts on the node
			all_posts = Post.objects.filter(visibility="PUBLIC")

			# GLOBAL FOAF STUFF
			# Need to go via all local users' global friends first to see if the <author_id> is friends with
			all_local_authors = Author.objects.all() # need to exclude self?
			for local_author in all_local_authors:
				# get author's global friends and see if the global <author_id> is friends or not.
				globalFriends = set(local_author.getGlobalFriends())
				
				globalFriendsList = local_author.getGlobalFriends()
				localFriendsList = local_author.getLocalFriends()

				print "LOCAL AUTHOR IN GLOBAL FOAF STUFF: "
				print local_author.user
				# Already friends
				if author in globalFriends:
					all_posts = chain(all_posts, Post.objects.filter(visibility="FRIENDS", author=local_author))
					all_posts = chain(all_posts, Post.objects.filter(visibility="FOAF", author=local_author))
				else:
					# Send POST to /api/friends/<queryID> to check if anyone in the list is a friend
					# check if <author_id> is friends with any one of local_author's friends

					local_author_friends = list(itertools.chain(localFriendsList, globalFriendsList))

					id_list = []

					if len(local_author_friends) > 0:

						for friend in local_author_friends:
							if friend.getClassName() == "Author":
								id_list.append(friend.author_id)
							elif friend.getClassName() == "GlobalAuthor":
								id_list.append(friend.global_author_id)

						
						requestObj = {
							"query":"friends",
							"author":queryID,
							"authors": id_list
						}

						response = CheckForMutualFriends(requestObj, author)

						FOAF_list = response['authors']
						print "FOAF"
						print FOAF_list

						if len(FOAF_list) > 0:
							# at least 1 mutual friend exists between global <author_id> and local_author
							all_posts = chain(all_posts, Post.objects.filter(visibility="FOAF", author=local_author))
							

			all_posts = list(all_posts)
			# Need this here or else the pagination bitches about it being unicode
			page_num = int(page_num)
			# Get the right page
			pages = Paginator(all_posts, page_size)
			print 'all good here'
			page = pages.page(page_num+1)
			print 'cant see this'
			data = page.object_list
			response_obj = {}
			response_obj['query'] = 'posts'
			response_obj['count'] = len(all_posts)
			response_obj['size'] = page_size

			if page.has_next():
				response_obj['next'] = settings.LOCAL_HOST + 'author/posts/?id=' + queryID + '&page=' + str(page_num + 1) + '&size=' + str(page_size)
			if page.has_previous():
				response_obj['previous'] = settings.LOCAL_HOST + 'author/posts/?id=' + queryID + '&page=' + str(page_num - 1) + '&size=' + str(page_size)

			serializer = PostSerializer(data, many=True)
			response_obj['posts'] = serializer.data

			return Response(response_obj)

			serializer = PostSerializer(all_posts, many=True)
			return Response(serializer.data)
	else:
		#not given a queryID - bad request
		return HttpResponseBadRequest("Need to give id in url: ?id=<author_id>")
Esempio n. 31
0
def run():
    author1 = Author(name="J. K. Rowling", birth_date="1965-07-31", author_pic="authors/2020/05/jkrowling.jpg", bio="Es una escritora, productora de cine y guionista británica, conocida por ser la autora de la serie de libros Harry Potter, que han superado los quinientos millones de ejemplares vendidos.")
    author2 = Author(name="Rick Riordan", birth_date='1964-06-05', author_pic="authors/2020/06/rriordan.jpg", bio="Richard Russell Riordan es un escritor estadounidense. Es más conocido por ser el autor de la saga Percy Jackson y los dioses del Olimpo.")
    author3 = Author(name="Suzanne Collins", birth_date='1962-08-10', author_pic="authors/2020/06/scollins.jpg", bio="Escritora estadounidense, sus revolucionarias novelas juveniles, Los Juegos del Hambre, En llamas y Sinsajo fueron superventas de The New York Times. Recibieron reconocimiento en todo el mundo.")
    publisher1 = Publisher(name="Bloomsbury", city="Londres", country="Reino Unido", about="Bloomsbury Publishing es una casa editorial independiente, asentada en Londres en el Reino Unido, conocida por sus novelas literarias. Fue nombrada \"editorial del año\" en 1999 y 2000.", website="www.bloomsbury.com", publisher_pic="publishers/2020/06/bblogo.png")
    publisher2 = Publisher(name="Salamandra", city="Barcelona", country="España", about="Ediciones Salamandra, también llamada simplemente Salamandra, es una editorial fundada en 1989 en Barcelona como filial española de la editorial argentina Emecé Editores.", website="www.megustaleer.com/editoriales/salamandra/SD/", publisher_pic="publishers/2020/06/sallogo.jpg")
    publisher3 = Publisher(name="Scholastic", city="Nueva York", country="Estados Unidos", about="Scholastic es una empresa editora de libros estadounidense conocida por publicar materiales educativos para escuelas, además de libros comerciales.", website="www.scholastic.com", publisher_pic="publishers/2020/06/schlogo.png")
    tag1 = Tag(title="Fantasy")
    tag2 = Tag(title="Mystery")
    tag3 = Tag(title="Novel")
    tag4 = Tag(title="Adventure")
    book1 = Book(title="Harry Potter y la Piedra Filosofal", author=author1, pub_date="1997-06-26", publisher=publisher1, description="Harry Potter crece en la casa de sus tíos, los Dursley, quienes le ocultan su verdadera historia familiar; al cumplir Harry once años de edad, empiezan a llegarle cartas de remitente desconocido, que van aumentando en número a medida que sus tíos no dejan que las abra. Las mismas traen la noticia de que el niño ha sido admitido en el Colegio Hogwarts de Magia y Hechicería, ya que, al igual que sus padres, tiene poderes mágicos. \\n\\nSe descubre entonces que los Potter no murieron en un accidente de coche como se le había dicho a Harry, sino que habían sido asesinados en la noche de Halloween por un hechicero tenebroso conocido como lord Voldemort, quien había aterrorizado a la comunidad mágica británica años atrás. Sin embargo, algo ocurrió esa noche: Voldemort consiguió matar al matrimonio Potter pero no pudo asesinar al bebé, perdió su cuerpo y le dejó al niño una cicatriz permanente en forma de rayo en su frente. \\n\\nRubeus Hagrid aparece para llevarse a Harry una noche, cuando los Dursley intentan impedir que parta rumbo al colegio. Más tarde, el hombre ayuda a Harry a comprar sus materiales escolares en el callejón Diagon y allí éste descubre que es famoso entre los magos por haber sobrevivido al intento de homicidio. Posteriormente, el muchacho toma el tren que lo lleva a Hogwarts y allí conoce a Ron Weasley, un chico pelirrojo hijo de magos, y a Hermione Granger, una jovencita de origen muggle con altas aspiraciones académicas. Los tres se hacen amigos y más tarde, durante su año escolar, se ven envueltos en una serie de episodios relacionados con un objeto escondido en las profundidades del edificio: la piedra filosofal, un artefacto con el poder de transmutar los metales en oro y producir el elixir de la vida eterna. Diferentes hechos les hacen suponer que uno de sus profesores, Severus Snape, desea conseguir la piedra para entregársela a Voldemort, con quien el docente estaría confabulado.", price="199.99", cover_pic="covers/2020/05/hpylpf.jpg", book_content="contents/hpylpf.pdf")
    book2 = Book(title="Harry Potter y la Cámara Secreta", author=author1, pub_date="1998-07-08", publisher=publisher1, description="Tras derrotar una vez más a lord Voldemort, su siniestro enemigo  en Harry  Potter y la piedra filosofal, Harry espera impaciente en casa de sus insoportables tíos el inicio del segundo curso del Colegio Hogwarts de Magia y hechicería. Sin embargo, la espera dura poco, pues un elfo aparece en su habitación y le advierte que una amenaza mortal se cierne sobre la escuela. Así pues, Harry no se lo piensa dos veces y, acompañado de  Ron, su mejor amigo, se dirige a Hogwarts en un coche volador. Pero ¿puede un aprendiz de mago defender la escuela de los malvados que pretenden destruirla? Sin saber que alguien ha abierto la Cámara de los Secretos, dejando escapar una serie de monstruos peligrosos, Harry y sus amigos Ron y Hermione tendrán que enfrentarse con arañas gigantes, serpientes encantadas, fantasmas enfurecidos y, sobre todo, con la mismísima reencarnación de su más temible adversario.", price="199.99", cover_pic="covers/2020/05/hpylca.jpg", book_content="contents/hpylca.pdf")
    book3 = Book(title="Harry Potter y el Prisionero de Azkaban", author=author1, pub_date="1999-07-08", publisher=publisher1, description="Por la cicatriz que lleva en la frente, sabemos que Harry Potter no es un niño como los demás, sino el héroe que venció a lord Voldemort, el mago más temible y maligno de todos los tiempos y culpable de la muerte de los  padres  de  Harry.  Desde  entonces,  Harry  no  tiene  más  remedio  que  vivir  con  sus  pesados  tíos  y  su  insoportable  primo  Dudley,  todos  ellos  muggles, o sea, personas no magas, que desprecian a su sobrino debido a sus poderes. Igual que en las dos primeras partes de la serie —La piedra filosofal y La cámara  secreta—  Harry  aguarda  con  impaciencia  el  inicio  del  tercer  curso  en  el  Colegio  Hogwarts  de  Magia  y  Hechicería.  Tras  haber  cumplido los trece años, solo y lejos de sus amigos de Hogwarts, Harry se pelea con su bigotuda tía Marge, a la que convierte en globo, y debe huir en un autobús mágico. Mientras tanto, de la prisión de Azkaban se ha  escapado  un  terrible  villano,  Sirius  Black,  un  asesino  en  serie  con  poderes  mágicos  que  fue  cómplice  de  lord  Voldemort  y  que  parece  dispuesto  a  eliminar  a  Harry  del  mapa.  Y  por  si  esto  fuera  poco,  Harry  deberá enfrentarse también a unos terribles monstruos, los dementores, seres  abominables  capaces  de  robarles  la  felicidad  a  los  magos  y  de  borrar  todo  recuerdo  hermoso  de  aquellos  que  osan  mirarlos.  Lo  que  ninguno de estos malvados personajes sabe es que Harry, con la ayuda de sus fieles amigos Ron y Hermione, es capaz de todo y mucho más.", price="199.99", cover_pic="covers/2020/05/hpyepda.jpg", book_content="contents/hpyepda.pdf")
    book4 = Book(title="Harry Potter y el Cáliz de Fuego", author=author1, pub_date='2000-07-08', publisher=publisher1, description="Tras otro abominable verano con los Dursley, Harry se dispone a  iniciar el cuarto curso en Hogwarts, la famosa escuela de magia y  hechicería. A sus catorce años, a Harry le gustaría ser un joven  mago como los demás y dedicarse a aprender nuevos sortilegios, encontrarse con sus amigos Ron y Hermione y asistir con ellos a los Mundiales de quidditch. Sin embargo, al llegar al colegio le espera una gran sorpresa que lo obligará a  enfrentarse a los desafíos más temibles de toda su vida. Si logra superarlos, habrá demostrado que ya no es un niño y que está preparado para vivir las nuevas y emocionantes experiencias que el futuro le depara.",  price="199.99", cover_pic="covers/2020/06/hpyecdf.jpg", book_content="contents/hpyecdf.pdf")
    book5 = Book(title="Percy Jackson y el Ladrón del Rayo", author=author2, pub_date='2005-06-28', publisher=publisher2, description="¿Qué pasaría si un día descubrieras que, en realidad, eres hijo de un dios griego que debe cumplir una misión secreta? Pues eso es lo que le sucede a Percy Jackson, que a partir de ese momento se dispone a vivir los acontecimientos más emocionantes de su vida. Expulsado de seis colegios, Percy padece dislexia y dificultades para concentrarse, o al menos ésa es la versión oficial. Objeto de burlas por inventarse historias fantásticas, ni siquiera él mismo acaba de creérselas hasta el día que los dioses del Olimpo le revelan la verdad: Percy es nada menos que un semidiós, es decir, el hijo de un dios y una mortal. Y como tal ha de descubrir quién ha robado el rayo de Zeus y así evitar que estalle una guerra entre los dioses. Para cumplir la misión contará con la ayuda de sus amigos Grover, un joven sátiro, y Annabeth, hija de Atenea. El ladrón del rayo da comienzo a la apasionante serie Percy Jackson y los Dioses del Olimpo, un mundo secreto que los antiguos dioses griegos han recreado a nuestro alrededor en pleno siglo XXI.", price="159.99", cover_pic="covers/2020/06/pjyeldr.jpg", book_content="contents/pjyeldr.pdf")
    book6 = Book(title="Percy Jackson y el Mar de los Monstruos", author=author2, pub_date='2006-04-01', publisher=publisher2, description="Desde que sabe que es hijo de un dios del Olimpo, Percy Jackson espera que el destino le depare continuas aventuras. Y sus expectativas se cumplen con creces. Aunque el nuevo curso en la Escuela Meriwether transcurre con inusual nor- malidad, un simple partido de balón prisionero acaba en batalla campal contra una banda de feroces gigantes. A partir de ahí los acontecimientos se precipitan: el perímetro mágico que protege el Campamento Mestizo es destruido por un misterioso enemigo y la única seguridad con que contaban los semidioses desaparece. Así, para impedir este daño irreparable, Percy y sus amigos inician la travesía del temible Mar de los Monstruos en busca de lo único que puede salvar el campamento: el Vellocino de Oro.", price="159.99", cover_pic="covers/2020/06/pjyemdlm.jpg", book_content="contents/pjyemdlm.pdf")
    book7 = Book(title="Percy Jackson y la Maldición del Titán", author=author2, pub_date="2007-04-15", publisher=publisher2, description="Ante la llamada de socorro de su amigo el sátiro Grover, Percy acude inmediatamente en su auxilio. Y aunque va acompañado de Annabeth y Thalia, las dos semidiosas que son sus aliadas, ninguno imagina la sorpresa  que  los  aguarda:  una  terrible  mantícora  pretende secuestrarlos  y  llevarlos  ante  el  general  enviado  por  Cronos,  el diabólico señor de los titanes. Sin embargo, gracias a la ayuda de las cazadoras de Artemisa, Percy y sus aliadas logran escapar y volver al campamento  mestizo.  Una  vez  allí,  emprenderán  la  búsqueda  del monstruo que puede provocar la destrucción del Olimpo, a pesar de que, según la profecía del Oráculo, sólo uno de ellos logrará resistir la maldición del titán.", price="159.99", cover_pic="covers/2020/06/pjylmdt.jpg", book_content="contents/pjylmdt.pdf")
    book8 = Book(title="The Hunger Games", author=author3, pub_date="2008-09-14", publisher=publisher3, description="Ganar significa fama y fortuna. Perder significa muerte segura. Los juegos del hambre han comenzado. . . . En las ruinas de un lugar una vez conocido como América del Norte se encuentra la nación de Panem, un brillante Capitolio rodeado de doce distritos periféricos. El Capitolio es duro y cruel y mantiene a los distritos en línea al obligarlos a enviar a un niño y una niña entre las edades de doce y dieciocho años a participar en los Juegos Anuales del Hambre, una pelea a muerte en la televisión en vivo.Katniss Everdeen, de 16 años, lo considera una sentencia de muerte cuando se adelanta para ocupar el lugar de su hermana en los Juegos. Pero Katniss ha estado cerca de la muerte antes, y la supervivencia, para ella, es una segunda naturaleza. Sin querer realmente, se convierte en una contendiente. Pero si quiere ganar, tendrá que comenzar a tomar decisiones que sopesen la supervivencia contra la humanidad y la vida contra el amor.", price="149.99", cover_pic="covers/2020/06/thg.jpg", book_content="contents/thg.pdf")
    book9 = Book(title="Catching Fire", author=author3, pub_date="2009-09-01", publisher=publisher3, description="Suzanne Collins continúa la increíble historia de Katniss Everdeen en la fenomenal trilogía de los Juegos del Hambre. Contra viento y marea, Katniss Everdeen ha ganado los Juegos del Hambre anuales con su colega tributo del distrito, Peeta Mellark. Pero fue una victoria ganada por el desafío del Capitolio y sus duras reglas. Katniss y Peeta deberían estar felices. Después de todo, acaban de ganar para ellos y sus familias una vida segura y abundante. Pero hay rumores de rebelión entre los sujetos, y Katniss y Peeta, para su horror, son los rostros de esa rebelión. El capitolio está enojado. El Capitolio quiere venganza.", price="149.99", cover_pic="covers/2020/06/thgcf.jpg", book_content="contents/thgcf.pdf")
    book10 = Book(title="Mockingjay", author=author3, pub_date="2010-08-24", publisher=publisher3, description="Katniss Everdeen, niña en llamas, ha sobrevivido, a pesar de que su casa ha sido destruida. Hay rebeldes. Hay nuevos líderes. Se está desarrollando una revolución. El Distrito 13 salió de las sombras y está planeando derrocar al Capitolio. Aunque ha sido parte de la revolución durante mucho tiempo, Katniss no lo ha sabido. Ahora parece que todos han intervenido en los planes cuidadosamente elaborados menos ella. El éxito de la rebelión depende de la voluntad de Katniss de ser un peón, de aceptar la responsabilidad de innumerables vidas y de cambiar el curso del futuro de Panem. Para hacer esto, debe dejar de lado sus sentimientos de ira y desconfianza. Ella debe convertirse en el Sinsajo de los rebeldes, sin importar el costo.", price="149.99", cover_pic="covers/2020/06/thgmj.jpg", book_content="contents/thgmj.pdf")
    author1.save()
    author2.save()
    author3.save()
    publisher1.save()
    publisher2.save()
    publisher3.save()
    tag1.save()
    tag2.save()
    tag3.save()
    tag4.save()
    book1.save()
    book2.save()
    book3.save()
    book4.save()
    book5.save()
    book6.save()
    book7.save()
    book8.save()
    book9.save()
    book10.save()
    book1.tags.set([tag1])
    book2.tags.set([tag1, tag2])
    book3.tags.set([tag1])
    book4.tags.set([tag1, tag2])
    book5.tags.set([tag1, tag4])
    book6.tags.set([tag1, tag4])
    book7.tags.set([tag1, tag4])
    book8.tags.set([tag3])
    book9.tags.set([tag3])
    book10.tags.set([tag3])
Esempio n. 32
0
    def setUp(self):
        """ Create a user object to be used by the tests """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            self.user = CustomUser(id=111,
                                   email='*****@*****.**',
                                   password='******',
                                   first_name='fname',
                                   middle_name='mname',
                                   last_name='lname')
            self.user.save()
            self.user_free = CustomUser(id=222,
                                        email='*****@*****.**',
                                        password='******',
                                        first_name='2fname',
                                        middle_name='2mname',
                                        last_name='2lname')
            self.user_free.save()

            self.author1 = Author(id=101,
                                  name="author1",
                                  surname="s1",
                                  patronymic="p1")
            self.author1.save()

            self.author2 = Author(id=102,
                                  name="author2",
                                  surname="s2",
                                  patronymic="p2")
            self.author2.save()

            self.book1 = Book(id=101,
                              name="book1",
                              description="description1",
                              count=1)
            self.book1.save()
            self.book1.authors.add(self.author1)
            self.book1.save()

            self.book2 = Book(id=102, name="book2", description="description2")
            self.book2.save()
            self.book2.authors.add(self.author2)
            self.book2.save()

            self.book3 = Book(id=103, name="book3", description="description3")
            self.book3.save()
            self.book3.authors.add(self.author1)
            self.book3.authors.add(self.author2)
            self.book3.save()

            self.order1 = Order(id=101,
                                user=self.user,
                                book=self.book1,
                                plated_end_at=TEST_DATE)
            self.order1.save()
            self.order2 = Order(id=102,
                                user=self.user,
                                book=self.book2,
                                plated_end_at=TEST_DATE)
            self.order2.save()
            self.order3 = Order(id=103,
                                user=self.user,
                                book=self.book3,
                                end_at=TEST_DATE_END,
                                plated_end_at=TEST_DATE)
            self.order3.save()
Esempio n. 33
0
 def test_cannot_save_empty_author(self):
     author = Author()
     with self.assertRaises(ValidationError):
         author.save()
         author.full_clean()