def register(request): args={} args.update(csrf(request)) if request.POST: username = request.POST.get('username', '') email = request.POST.get('email', '') nickname = request.POST.get('nickname', '') password = request.POST.get('password', '') password1= request.POST.get('password1', '') if password != password1: args['login_error'] = "Пароли не совпадают" return render_to_response('forms/register.html', args) if password is None: args['login_error'] = "Пароль обязателен" return render_to_response('forms/register.html', args) if User.objects.get(username=username): args['login_error'] = "Логин уже занят" return render_to_response('forms/register.html', args) user = User.objects.create_user(username, email, password) user.save() author = Author(user=user, nickname=nickname, avatar='static/empty.png') author.save() return redirect('/auth/login/') else: return render_to_response('forms/register.html', args)
def identifyAuthor(self): print("Creating author") channel = self.tree.find("channel") author_tree = channel.find("{http://wordpress.org/export/1.2/}author") self.author_name = author_tree.find("{http://wordpress.org/export/1.2/}author_login").text author_email = author_tree.find("{http://wordpress.org/export/1.2/}author_email").text users = User.objects.filter(username = self.author_name) if len(users) == 0: print("Creating user {0} with password 'password', don't forget to change it...".format(self.author_name)) admin = User.objects.create_user(self.author_name, author_email, "password") admin.is_superuser = True admin.is_staff = True admin.save() else: print("User {0} found, skipping".format(users[0].username)) admin = users[0] authors = Author.objects.filter(user = admin) if len(authors) == 0: print("Creating author for user {0}".format(admin.username)) author = Author() author.user = admin author.save() self.author = author else: print("Author {0} present, skipping".format(authors[0].user.username)) self.author = authors[0]
def createAuthor(request): if request.method == 'POST': form = CreateAuthorForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] birthDate = form.cleaned_data['birthDate'] deathDate = form.cleaned_data['deathDate'] nationality = form.cleaned_data['nationality'] auteur = Author(name=name, birthDate=birthDate, deathDate=deathDate, nationality=nationality) auteur.save() messages.add_message(request, messages.INFO, 'L\'auteur à été créé') return redirect('author-list', ) else: pass else: form = CreateAuthorForm() return render(request, "author/create.html", { 'form': form, })
def create_author_object_based_on_book_dict_and_save_in_db(book_dict): authors_list = book_dict["authors"] for author in authors_list: try: object_allready_in_db = Author.objects.get(authorName=author) return object_allready_in_db except Author.DoesNotExist: new_author_object = Author(authorName=author) new_author_object.save() return new_author_object
def add(request): message = "" if request.method == "POST": author_form = AuthorForm(request.POST) if author_form.is_valid(): author = Author( name=author_form.cleaned_data["name"], nickname=author_form.cleaned_data["nickname"], gender=author_form.cleaned_data["gender"], ) author.save() return HttpResponseRedirect("/view/author/{}/".format(author.id)) else: author_form = AuthorForm() return render_to_response( "author/add.html", {"form": author_form, "message": message}, context_instance=RequestContext(request) )
def create(request): topics = Topic.objects.all() if request.user.id == None: return HttpResponse('please login') if request.method == 'POST': requestpost = request.POST.getlist('choice') # returns topic id requestweight = request.POST.getlist( 'weight') # returns a list of weights form = ChallengeForm(request.POST) if form.is_valid(): challenge = form.save(commit=False) exist = Challenge.objects.filter(name=challenge.name) if not exist.exists(): challenge.save() a = Author() a.user = request.user a.challenge = challenge a.timestamp = datetime.datetime.now() a.save() for i in range(0, len(requestpost)): idx = int(requestpost[i]) topicweight = 0 for j in range(0, len(requestweight)): if requestweight[j] != '': topicweight = requestweight[j] requestweight[j] = '' break ct = ChallengeTopic() ct.challenge = challenge ct.topic = Topic.objects.get(pk=idx) ct.weight = float(topicweight) ct.save() return redirect('thanks/') else: return HttpResponse('Challenge Name exists') else: form = ChallengeForm() return render(request, 'challenge/create.html', { 'form': form, 'topics': topics })
def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Author(docfile = request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('myproject.myapp.views.list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Author.objects.all() # Render list page with the documents and the form return render_to_response( 'author/list.html', {'documents': documents, 'form': form}, context_instance=RequestContext(request) )
def load_json_site(fic): site = {} with open(fic, 'r') as json_file: site = json.load(json_file) for a_json in site['Author']: try : a = Author.objects.get(pk=a_json['pk']) except: a = Author() a.load_from_dict(a_json) a.save() for a_json in site['Category']: try : a = Category.objects.get(pk=a_json['pk']) except: a = Category() a.load_from_dict(a_json) a.save() for a_json in site['Event']: try : a = Event.objects.get(pk=a_json['pk']) except: a = Event() a.load_from_dict(a_json) a.save() for a_json in site['Article']: try : a = Article.objects.get(pk=a_json['pk']) except: a = Article() a.load_from_dict(a_json) a.save() for a_json in site['Part']: try : a = Part.objects.get(pk=a_json['pk']) except: a = Part() a.load_from_dict(a_json) a.save()
def test_author_slug_for_multiple_unique_author_name(self): author_name = 'Author Name Author Name Author Name Author Name Author Name' author1 = Author(name=author_name) author2 = Author(name=author_name + ' ') author3 = Author(name=author_name + '. ') author1.save() author2.save() author3.save() assert Author.objects.get(name=author_name).slug == 'author-name-author-name-author-name-author-name-au' assert Author.objects.get(name=author_name + ' ').slug == 'author-name-author-name-author-name-author-name-a1' assert Author.objects.get(name=author_name + '. ').slug == 'author-name-author-name-author-name-author-name-a2'
def test_should_throw_error_if_author_name_exceeds_hundred_characters(self): author_name = 'Full Metal Havok More Sexy N Intelligent Than Spock And All The Superheroes Combined With Frostnova nova'; author_with_long_name = Author(name=author_name) with self.assertRaises(DataError) as context_message: author_with_long_name.save()
def post(self, request): """ 用户修改个人信息 :param request: :return: """ """ nick_name = request.POST.get('nick_name', '') author=Author.objects.filter(name=nick_name) if author.__len__()==0: introduce = request.POST.get('introduce', '') mobile = request.POST.get('mobile', '') birday = request.POST.get('birday', '') user = UserProfile.objects.get(username=request.user) request.user.nick_name = nick_name request.user.mobile = mobile request.user.birday = birday request.user.save() author = Author() author.user = user author.name = user.nick_name author.introduce = introduce author.save() return HttpResponse('{"status":"0","msg":"修改个人信息成功"}', content_type='application/json') else: introduce = request.POST.get('introduce', '') mobile = request.POST.get('mobile', '') birday = request.POST.get('birday', '') user = UserProfile.objects.get(username=request.user) request.user.nick_name = nick_name request.mobile = mobile request.birday = birday request.user.save() author = Author.objects.get(user=user) author.user = user author.name = user.nick_name author.introduce = introduce author.save() return HttpResponse('{"status":"0","msg":"修改个人信息成功"}', content_type='application/json') """ if request.user.nick_name: user = UserProfile.objects.get(username=request.user) author = Author.objects.get(name=user.nick_name) nick_name = request.POST.get('nick_name', '') introduce = request.POST.get('introduce', '') request.user.nick_name = nick_name request.user.introduce = introduce request.user.save() author.user = user author.name = nick_name author.introduce = introduce author.save() return HttpResponse('{"status":"0","msg":"修改个人信息成功"}', content_type='application/json') user = UserProfile.objects.get(username=request.user) nick_name = request.POST.get('nick_name', '') if Author.objects.filter(name=nick_name).__len__() != 0: return HttpResponse('{"status":"1","msg":"修改个人信息失败"}', content_type='application/json') introduce = request.POST.get('introduce', '') user.nick_name = nick_name user.save() author = Author() author.user = user author.name = user.nick_name author.introduce = introduce author.save() return HttpResponse('{"status":"0","msg":"修改个人信息成功"}', content_type='application/json')
import os,sys import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'libraryproject.settings') django.setup() from author.models import Author import csv try: with open(sys.argv[1], 'r') as file: reader = csv.reader(file) for row in reader: if not row[0] == 'name' and not row[0] == '' : newAuthor = Author( name = row[0]) print('Author:'+row[0]) newAuthor.save() print('Sucess!') except: print('Fail!')
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])
def store_link_data(values): User = get_user_model() try: user = User.objects.get(pk=values['user.id']) except User.DoesNotExist: return None date = None if 'page.published_at' in values: date = dateparse(values['page.published_at']) if not is_aware(date): date = make_aware(date) upload_dir = settings.FORM_DATA_UPLOAD_DIR page_image_path = None if 'page.image.url' in values: r = requests.get(values['page.image.url'], stream=True) if r.ok: page_image_path = os.path.join(upload_dir, uuid4().hex) with open(page_image_path, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) author_image_path = None if 'author.image.url' in values: r = requests.get(values['author.image.url'], stream=True) if r.ok: author_image_path = os.path.join(upload_dir, uuid4().hex) with open(author_image_path, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) publisher_image_path = None if 'publisher.image.url' in values: r = requests.get(values['publisher.image.url'], stream=True) if r.ok: publisher_image_path = os.path.join(upload_dir, uuid4().hex) with open(publisher_image_path, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) author = None if 'author.name' in values: try: author = Author.objects.get(user=user, name=values['author.name']) if date and author.updated_at < date: pass except Author.DoesNotExist: author = Author(name=values['author.name'], user=user, updated_at=date or now()) if author_image_path: im = Image.open(author_image_path) ext = guess_extension(Image.MIME[im.format]) author.image_height = im.size[1] author.image_width = im.size[0] author.image.save( os.path.basename(author_image_path) + ext, File(open(author_image_path, 'rb'))) author.save() for social_url in values.get('author.social', []): social = AuthorSocial(url=social_url, entity=author, user=user) social.save() publisher = None if 'publisher.name' in values: try: publisher = Publisher.objects.get(user=user, name=values['publisher.name']) if date and publisher.updated_at < date: pass except Publisher.DoesNotExist: publisher = Publisher(name=values['publisher.name'], user=user, updated_at=date or now()) if publisher_image_path: im = Image.open(publisher_image_path) ext = guess_extension(Image.MIME[im.format]) publisher.image_height = im.size[1] publisher.image_width = im.size[0] publisher.image.save( os.path.basename(publisher_image_path) + ext, File(open(publisher_image_path, 'rb'))) publisher.save() for social_url in values.get('publisher.social', []): social = PublisherSocial(url=social_url, entity=publisher, user=user) social.save() link = Link(url=values.get('page.url'), title=values.get('page.title'), description=values.get('page.description'), text=values.get('page.body.text'), html=values.get('page.body.html'), author=author, publisher=publisher, user=user, published_at=date) if page_image_path: im = Image.open(page_image_path) ext = guess_extension(Image.MIME[im.format]) link.image_height = im.size[1] link.image_width = im.size[0] link.image.save( os.path.basename(page_image_path) + ext, File(open(page_image_path, 'rb'))) link.save() if 'page.keywords' in values: for name in values['page.keywords']: keyword, _ = LinkKeyword.objects.get_or_create(name=name) link.keywords.add(keyword) return link.id
def test_should_throw_error_if_author_already_exist(self): author_one = Author(name='some author') author_two = Author(name='some author') with self.assertRaises(IntegrityError) as context_message: author_one.save() author_two.save()
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)
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)