Exemple #1
0
        public async Task GetGenresCountShouldReturnCorrectCount()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.Genres.AddRangeAsync(
                new Genre
            {
                Name        = "test1",
                Description = "description1",
            },
                new Genre
            {
                Name        = "test2",
                Description = "description2",
            },
                new Genre
            {
                Name        = "test3",
                Description = "description3",
            });

            await db.SaveChangesAsync();

            var genresService = new GenresService(db);

            var result = await genresService.GetGenresCountAsync();

            Assert.Equal(3, result);
        }
Exemple #2
0
        public async Task GetAverageRatingByBookIdShouldZeroWhenBookIdIsInvalid()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            var ratings = new List <StarRating>();

            for (int i = 1; i <= 2; i++)
            {
                ratings.Add(
                    new StarRating
                {
                    Rate   = 5,
                    UserId = "userId",
                    BookId = 1,
                });
            }

            await db.StarRatings.AddRangeAsync(ratings);

            await db.SaveChangesAsync();

            var ratingsService = new StarRatingsService(db);
            var result         = await ratingsService.GetAverageRatingByBookIdAsync(5);

            Assert.Equal(0, result);
        }
Exemple #3
0
        public async Task SeedAsync(AlexandriaDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext.Genres.Any())
            {
                return;
            }

            var genres = new List <(string Name, string Description)>
            {
                ("Horror", "Horror fiction is fiction in any medium intended to scare, unsettle, or horrify the audience. Historically, the cause of the \"horror\" experience has often been the intrusion of a supernatural element into everyday human experience. Since the 1960s, any work of fiction with a morbid, gruesome, surreal, or exceptionally suspenseful or frightening theme has come to be called \"horror\". Horror fiction often overlaps science fiction or fantasy, all three of which categories are sometimes placed under the umbrella classification speculative fiction."),
                ("Fiction", "Fiction is the telling of stories which are not real. More specifically, fiction is an imaginative form of narrative, one of the four basic rhetorical modes. Although the word fiction is derived from the Latin fingo, fingere, finxi, fictum, \"to form, create\", works of fiction need not be entirely imaginary and may include real people, places, and events. Fiction may be either written or oral. Although not all fiction is necessarily artistic, fiction is largely perceived as a form of art or entertainment. The ability to create fiction and other artistic works is considered to be a fundamental aspect of human culture, one of the defining characteristics of humanity."),
                ("Science Fiction", "Science fiction (abbreviated SF or sci-fi with varying punctuation and capitalization) is a broad genre of fiction that often involves speculations based on current or future science or technology. Science fiction is found in books, art, television, films, games, theatre, and other media. In organizational or marketing contexts, science fiction can be synonymous with the broader definition of speculative fiction, encompassing creative works incorporating imaginative elements not found in contemporary reality; this includes fantasy, horror and related genres."),
                ("Fantasy", "Fantasy is a genre that uses magic and other supernatural forms as a primary element of plot, theme, and/or setting. Fantasy is generally distinguished from science fiction and horror by the expectation that it steers clear of technological and macabre themes, respectively, though there is a great deal of overlap between the three (collectively known as speculative fiction or science fiction/fantasy) In its broadest sense, fantasy comprises works by many writers, artists, filmmakers, and musicians, from ancient myths and legends to many recent works embraced by a wide audience today, including young adults, most of whom are represented by the works below."),
                ("Romance", "According to the Romance Writers of America, \"Two basic elements comprise every romance novel: a central love story and an emotionally - satisfying and optimistic ending.\" Both the conflict and the climax of the novel should be directly related to that core theme of developing a romantic relationship, although the novel can also contain subplots that do not specifically relate to the main characters' romantic love. Other definitions of a romance novel may be broader, including other plots and endings or more than two people, or narrower, restricting the types of romances or conflicts."),
                ("Thriller", "Thrillers are characterized by fast pacing, frequent action, and resourceful heroes who must thwart the plans of more-powerful and better-equipped villains. Literary devices such as suspense, red herrings and cliffhangers are used extensively. Thrillers often overlap with mystery stories, but are distinguished by the structure of their plots. In a thriller, the hero must thwart the plans of an enemy, rather than uncover a crime that has already happened. Thrillers also occur on a much grander scale: the crimes that must be prevented are serial or mass murder, terrorism, assassination, or the overthrow of governments.Jeopardy and violent confrontations are standard plot elements. While a mystery climaxes when the mystery is solved, a thriller climaxes when the hero finally defeats the villain, saving his own life and often the lives of others. "),
                ("Adventure", "Adventure fiction is a genre of fiction in which an adventure, an exciting undertaking involving risk and physical danger, forms the main storyline. Adventure novels and short stories were popular subjects for American pulp magazines, which dominated American popular fiction between the Progressive Era and the 1950s. Adventure fiction often overlaps with other genres, notably war novels, crime novels, sea stories, Robinsonades, spy stories (as in the works of John Buchan, Eric Ambler and Ian Fleming), science fiction, fantasy, (Robert E. Howard and J.R.R. Tolkien both combined the secondary world story with the adventure novel)[6] and Westerns. Not all books within these genres are adventures. Adventure fiction takes the setting and premise of these other genres, but the fast-paced plot of an adventure focuses on the actions of the hero within the setting."),
                ("Novels", "A novel is a long prose narrative that usually describes fictional characters and events in the form of a sequential story. It rests on the consensus that the novel is today the longest genre of narrative prose, followed by the novella, novelette and the short story. However, there is no consensus as to the minimal required lenght. In part because of this wide variation, the boundary between a novella and a novel may be arbitrary and difficult to determine."),
                ("Action", "The action genre is characterized by more emphasis on exciting action sequences than on character development or story-telling. That is not to say that the action-adventure story does not have memorable characters or circumstances, however. Generally heroes are seen as larger than life, and many times they are prime examples of the epic hero archetype."),
                ("Historical", "Historical fiction presents a story set in the past, often during a significant time period. In historical fiction, the time period is an important part of the setting and often of the story itself. Historical fiction may include fictional characters, well-known historical figures or a mixture of the two. Authors of historical fiction usually pay close attention to the details of their stories (settings, clothing, dialogue, etc.) to ensure that they fit the time periods in which the narratives take place. In some historical fiction, famous events appear from points of view not recorded in history, showing historical figures dealing with actual events while depicting them in a way that is not recorded in history.Other times, the historical event or time period complements a story's narrative, forming a framework and background for the characters' lives.Sometimes, historical fiction can be for the most part true, but the names of people and places have been in some way altered."),
                ("Victorian", "Books written during or set in the Victorian Era. The Victorian era of the United Kingdom was the period of Queen Victoria's reign from 20 June 1837 until her death on 22 January 1901. It was a long period of prosperity for the British people. Some scholars extend the beginning of the period—as defined by a variety of sensibilities and political concerns that have come to be associated with the Victorians—back five years to the passage of the Reform Act 1832. The era was preceded by the Georgian period and succeeded by the Edwardian period. The latter half of the Victorian era roughly coincided with the first portion of the Belle Époque era of continental Europe and the Gilded Age of the United States."),
                ("Medieval", "The Medieval period is subdivided into the Early (c. 476-1000), the High (c. 1001-1300), and the Late (c. 1301–1500) Middle Ages. Historical fiction novels set within this time-frame in Europe are labelled medieval. Medieval Europe offers the historical backdrop of the grandeur of medieval royalty contrasted with the stark struggle for survival of the common folk.Medieval historical fiction features, among others, conflicts between Christianity and the remnants of paganism, the open warfare of the Crusades, the medieval Celts, Anglo - Saxon and Norman England, the Wars of the Roses, the Vikings and the Byzantine Empire."),
                ("Tudor Period", "The Tudor period is the period between 1485 and 1603 in England and Wales and includes the Elizabethan period which ends with the completion of the reign of Elizabeth I in 1603. The Tudor period coincides with the rule of the Tudor dynasty in England whose first monarch was Henry VII (1457–1509). In terms of the entire century, Guy (1988) argues that \"England was economically healthier, more expansive, and more optimistic under the Tudors\" than at any time in a thousand years."),
                ("Early Modern", "Books written during or set in the Early Modern period or the Renaissance in Europe or the New World. Although the chronological limits of the period are open to debate, the timeframe spans the period after the late portion of the Middle Ages (c. 1500) through the beginning of the Age of Revolutions (c. 1800) and is variously demarcated by historians as beginning with the Fall of Constantinople in 1453, with the Renaissance or the Age of Discovery and ending with the French Revolution in 1789."),
                ("Anglo Saxon", "In the history of Great Britain, Anglo-Saxon England refers to the historical land roughly corresponding to present-day England, as it existed from the 5th to the 11th century, but not including Devon until the 9th century."),
                ("Historical Mystery", "The historical mystery or historical whodunit is a subgenre of two literary genres, historical fiction and mystery fiction. These works are set in a time period considered historical from the author's perspective, and the central plot involves the solving of a mystery or crime (usually murder). Though works combining these genres have existed since at least the early 1900s, many credit Ellis Peters's Cadfael Chronicles (1977-1994) for popularizing what would become known as the historical mystery."),
                ("Mystery", "Mystery fiction is a loosely-defined term that is often used as a synonym of detective fiction — in other words a novel or short story in which a detective (either professional or amateur) solves a crime. The term \"mystery fiction\" may sometimes be limited to the subset of detective stories in which the emphasis is on the puzzle element and its logical solution (cf. whodunit), as a contrast to hardboiled detective stories which focus on action and gritty realism. However, in more general usage \"mystery\" may be used to describe any form of crime fiction, even if there is no mystery to be solved. For example, the Mystery Writers of America describes itself as \"the premier organization for mystery writers, professionals allied to the crime writing field, aspiring crime writers, and those who are devoted to the genre\"."),
                ("Detective", "Detective fiction is a sub-genre of crime and mystery fiction in which an investigator (often a detective), either professional or amateur, investigates a crime, often murder."),
                ("Crime", "The crime genre includes the broad selection of books on criminals and the court system, but the most common focus is investigations and sleuthing. Mystery novels are usually placed into this category, although there is a separate division for \"crime\". Hard Case Crime is one example."),
                ("Memoir", "As a literary genre, a memoir (from the French: mémoire from the Latin memoria, meaning \"memory\", or a reminiscence), forms a subclass of autobiography – although the terms 'memoir' and 'autobiography' are almost interchangeable in modern parlance. Memoir is autobiographical writing, but not all autobiographical writing follows the criteria for memoir."),
                ("Biography", "A biography (from the Greek words bios meaning \"life\", and graphos meaning \"write\") is a non-fictional account of a person's life. Biographies are written by an author who is not the subject/focus of the book."),
                ("Autobiography", "An autobiography (from the Greek, αὐτός-autos self + βίος-bios life + γράφειν-graphein to write) is a book about the life of a person, written by that person. Closely associated with autobiography (and sometimes difficult to precisely distinguish from it) is the form of memoir. However, an autobiography typically focuses on the \"life and times\" of the writer, while a memoir has a narrower, more intimate focus on his or her own memories, feelings and emotions."),
                ("Classics", "A classic stands the test of time. The work is usually considered to be a representation of the period in which it was written; and the work merits lasting recognition. In other words, if the book was published in the recent past, the work is not a classic. A classic has a certain universal appeal. Great works of literature touch us to our very core beings--partly because they integrate themes that are understood by readers from a wide range of backgrounds and levels of experience. Themes of love, hate, death, life, and faith touch upon some of our most basic emotional responses."),
                ("Science", "Science (from the Latin scientia, meaning “knowledge”) is the effort to discover, and increase human understanding of how the physical world works. Through controlled methods, science uses observable physical evidence of natural phenomena to collect data, and analyzes this information to explain what and how things work."),
                ("Technology", "Technology is the making, modification, usage, and knowledge of tools, machines, techniques, crafts, systems, and methods of organization, in order to solve a problem, improve a pre-existing solution to a problem, achieve a goal, handle an applied input/output relation or perform a specific function. It can also refer to the collection of such tools, including machinery, modifications, arrangements and procedures."),
                ("Biology", "Biology is a natural science concerned with the study of life and living organisms, including their structure, function, growth, evolution, distribution, and taxonomy."),
                ("Ecology", "Ecology (from Greek: οἶκος, \"house\"; -λογία, \"study of\"[A]) is the scientific study of interactions among organisms and their environment, such as the interactions organisms have with each other and with their abiotic environment."),
                ("Genetics", "Genetics is the study of genes, heredity, and variation in living organisms.It is generally considered a field of biology, but it intersects frequently with many of the life sciences and is strongly linked with the study of information systems."),
                ("Physics", "Physics is the natural science that involves the study of matter and its motion through space and time, along with related concepts such as energy and force. More broadly, it is the general analysis of nature, conducted in order to understand how the universe behaves."),
                ("Mathematics", "Mathematicians seek out patterns and use them to formulate new conjectures. Mathematicians resolve the truth or falsity of conjectures by mathematical proof. When mathematical structures are good models of real phenomena, then mathematical reasoning can provide insight or predictions about nature. Through the use of abstraction and logic, mathematics developed from counting, calculation, measurement, and the systematic study of the shapes and motions of physical objects. Practical mathematics has been a human activity from as far back as written records exist. The research required to solve mathematical problems can take years or even centuries of sustained inquiry."),
                ("Astronomy", "Astronomy is a natural science which is the study of celestial objects (such as stars, galaxies, planets, moons, and nebulae), the physics, chemistry, and evolution of such objects, and phenomena that originate outside the atmosphere of Earth, including supernovae explosions, gamma ray bursts, and cosmic microwave background radiation. A related but distinct subject, cosmology, is concerned with studying the universe as a whole."),
                ("Nonfiction", "Nonfiction is an account or representation of a subject which is presented as fact. This presentation may be accurate or not; that is, it can give either a true or a false account of the subject in question. However, it is generally assumed that the authors of such accounts believe them to be truthful at the time of their composition. Note that reporting the beliefs of others in a nonfiction format is not necessarily an endorsement of the ultimate veracity of those beliefs, it is simply saying that it is true that people believe that (for such topics as mythology, religion). Nonfiction can also be written about fiction, giving information about these other works."),
                ("Art", "Books that showcase particular types of art."),
                ("Business", "A business (also known as enterprise or firm) is an organization engaged in the trade of goods, services, or both to consumers. Businesses are predominant in capitalist economies, where most of them are privately owned and administered to earn profit to increase the wealth of their owners. Businesses may also be not-for-profit or state-owned. A business owned by multiple individuals may be referred to as a company, although that term also has a more precise meaning."),
                ("Chemistry", "Chemistry, a branch of physical science, is the study of the composition, structure, properties and change of matter."),
                ("Comics", "A comic book or comicbook, also called comic magazine or simply comic, is a publication that consists of comic art in the form of sequential juxtaposed panels that represent individual scenes. Panels are often accompanied by brief descriptive prose and written narrative, usually dialog contained in word balloons emblematic of the comics art form."),
                ("Sports", "Sports : engagement in physical activity intended to create a benefit to the participant. Ranging from Amateur to Professional, from incompetent to proficient, for all levels of ability, all nations, all creeds, all genders. As James Joyce said \"I am, a stride at a time\""),
                ("Religion", "Religion is a cultural system that establishes symbols that relate humanity to spirituality and moral values. Many religions have narratives, symbols, traditions and sacred histories that are intended to give meaning to life or to explain the origin of life or the universe. They tend to derive morality, ethics, religious laws or a preferred lifestyle from their ideas about the cosmos and human nature."),
                ("Philosophy", "Philosophy is the study of general problems concerning matters such as existence, knowledge, truth, beauty, justice, validity, mind, and language. Philosophy is distinguished from other ways of addressing these questions (such as mysticism or mythology) by its critical, generally systematic approach and its reliance on reasoned argument. The word philosophy is of Ancient Greek origin: φιλοσοφία (philosophía), meaning \"love of wisdom.\""),
            };

            foreach (var genre in genres)
            {
                await dbContext.AddAsync(new Genre
                {
                    Name        = genre.Name,
                    Description = genre.Description,
                    CreatedOn   = DateTime.UtcNow,
                });
            }
        }
        public async Task SeedAsync(AlexandriaDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException(nameof(dbContext));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            var logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger(typeof(ApplicationDbContextSeeder));

            var seeders = new List <ISeeder>
            {
                new RolesSeeder(),
                new TagsSeeder(),
                new GenresSeeder(),
                new AwardsSeeder(),
                new CountriesSeeder(),
                new EditionLanguagesSeeder(),
                new AdminSeeder(),
            };

            foreach (var seeder in seeders)
            {
                await seeder.SeedAsync(dbContext, serviceProvider);

                await dbContext.SaveChangesAsync();

                logger.LogInformation($"Seeder {seeder.GetType().Name} done.");
            }
        }
Exemple #5
0
        public async Task GetAllRatesByUserIdShouldReturnZeroWhenInvalidUserId()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            var rates = new List <StarRating>();

            for (int i = 1; i <= 10; i++)
            {
                rates.Add(new StarRating
                {
                    Rate   = i,
                    UserId = "userId",
                    BookId = i,
                });
            }

            await db.StarRatings.AddRangeAsync(rates);

            await db.SaveChangesAsync();

            var ratingsService = new StarRatingsService(db);

            var result = await ratingsService.GetAllRatesByUserIdAsync <RatingTestModel>("id");

            Assert.Empty(result);
        }
Exemple #6
0
        public async Task GetAllAwardsShouldReturnZeroWhenAwardsAreDeleted()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            var awards = new List <Award>();

            for (int i = 1; i <= 10; i++)
            {
                awards.Add(
                    new Award
                {
                    Name      = $"test{i}",
                    CreatedOn = DateTime.UtcNow,
                    IsDeleted = true,
                    DeletedOn = DateTime.UtcNow,
                });
            }

            await db.Awards.AddRangeAsync(awards);

            await db.SaveChangesAsync();

            var awardsService = new AwardsService(db);
            var result        = await awardsService.GetAllAwardsAsync <AwardTestModel>();

            Assert.Empty(result);
        }
Exemple #7
0
        public async Task CreateUserFollowerShouldDeleteUserFollowerIfExisting()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.UserFollowers.AddAsync(
                new UserFollower
            {
                UserId     = "user1",
                FollowerId = "user2",
            });

            await db.SaveChangesAsync();

            var userFollowerService = new UserFollowersService(db);

            await userFollowerService.CreateUserFollowerAsync("user1", "user2");

            var result = await db.UserFollowers.FirstOrDefaultAsync();

            Assert.True(result.IsDeleted);
            Assert.NotNull(result.DeletedOn);
        }
        public async Task GetAllLanguagesShouldReturnTheCorrectCount()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            var languages = new List <EditionLanguage>();

            for (int i = 1; i <= 10; i++)
            {
                languages.Add(
                    new EditionLanguage
                {
                    Name = $"test{i}",
                });
            }

            await db.EditionLanguages.AddRangeAsync(languages);

            await db.SaveChangesAsync();

            var languagesService = new EditionLanguagesService(db);

            var result = await languagesService.GetAllLanguagesAsync <LanguageTestModel>();

            Assert.Equal(10, result.Count());
        }
Exemple #9
0
        public async Task GetChildrenReviewsToReviewsAsyncShouldNotReturnReviewsWithOtherBookId()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.AddRangeAsync(
                new Review
            {
                Description = "description1",
                AuthorId    = "author1",
                BookId      = 1,
            },
                new Review
            {
                Description = "description2",
                AuthorId    = "author1",
                BookId      = 1,
            },
                new Review
            {
                Description = "description3",
                AuthorId    = "author1",
                BookId      = 1,
                ParentId    = 1,
            },
                new Review
            {
                Description = "description4",
                AuthorId    = "author1",
                BookId      = 2,
                ParentId    = 2,
            },
                new Review
            {
                Description = "description4",
                AuthorId    = "author1",
                BookId      = 1,
                ParentId    = 3,
            },
                new Review
            {
                Description = "description4",
                AuthorId    = "author1",
                BookId      = 1,
                ParentId    = 4,
            });

            await db.SaveChangesAsync();

            var reviewsService = new ReviewsService(db);

            var ids = new List <int> {
                1, 2
            };
            var result = await reviewsService.GetChildrenReviewsToReviewsAsync <ReviewTestModel>(ids, 1);

            Assert.Equal(2, result.Count());
        }
Exemple #10
0
        public async Task SeedAsync(AlexandriaDbContext dbContext, IServiceProvider serviceProvider)
        {
            var roleManager = serviceProvider.GetRequiredService <RoleManager <ApplicationRole> >();
            var userManager = serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();

            var admin = await userManager.FindByNameAsync(GlobalConstants.AdministratorUsername);

            if (admin == null)
            {
                admin = new ApplicationUser
                {
                    UserName       = GlobalConstants.AdministratorUsername,
                    Email          = GlobalConstants.AdministratorEmail,
                    ProfilePicture = GlobalConstants.AdministratorProfilePicture,
                    Gender         = GenderType.Male,
                };

                var result = await userManager.CreateAsync(admin, GlobalConstants.AdministratorPassword);

                if (!result.Succeeded)
                {
                    throw new Exception(string.Join(Environment.NewLine, result.Errors.Select(e => e.Description)));
                }

                var roleResult = await userManager.AddToRoleAsync(admin, GlobalConstants.AdministratorRoleName);

                if (!roleResult.Succeeded)
                {
                    throw new Exception(string.Join(Environment.NewLine, roleResult.Errors.Select(e => e.Description)));
                }
            }
        }
        public async Task DoesEditionLanguageExistShouldReturnFalseWhenNotFound()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            await db.EditionLanguages.AddRangeAsync(
                new EditionLanguage
            {
                Name = "test1",
            },
                new EditionLanguage
            {
                Name = "test2",
            },
                new EditionLanguage
            {
                Name = "test3",
            });

            await db.SaveChangesAsync();

            var languagesService = new EditionLanguagesService(db);

            Assert.False(await languagesService.DoesEditionLanguageIdExistAsync(5));
        }
Exemple #12
0
        public async Task EditGenreShouldWorkCorrectly(string name, string description)
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.Genres.AddAsync(
                new Genre
            {
                Name        = "test",
                Description = "description",
            });

            await db.SaveChangesAsync();

            var genresService = new GenresService(db);

            await genresService.EditGenreAsync(1, name, description);

            var result = await db.Genres.FirstOrDefaultAsync();

            Assert.Equal(name, result.Name);
            Assert.Equal(description, result.Description);
            Assert.NotNull(result.ModifiedOn);
        }
Exemple #13
0
        public async Task GetRandomGenresShouldNotReturnDeletedGenres()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.Genres.AddRangeAsync(
                new Genre
            {
                Name        = "test1",
                Description = "description1",
                IsDeleted   = true,
            },
                new Genre
            {
                Name        = "test2",
                Description = "description2",
                IsDeleted   = true,
            },
                new Genre
            {
                Name        = "test3",
                Description = "description3",
            });

            await db.SaveChangesAsync();

            var genresService = new GenresService(db);

            var result = await genresService.GetRandomGenresAsync <GenreTestModel>(2);

            Assert.Single(result);
        }
Exemple #14
0
        public async Task GetGenreShouldReturnCorrectGenre()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.Genres.AddRangeAsync(
                new Genre
            {
                Name        = "test1",
                Description = "description1",
            },
                new Genre
            {
                Name        = "test2",
                Description = "description2",
            },
                new Genre
            {
                Name        = "test3",
                Description = "description3",
                IsDeleted   = true,
            });

            await db.SaveChangesAsync();

            var genresService = new GenresService(db);

            var result = await genresService.GetGenreByIdAsync <GenreTestModel>(1);

            Assert.Equal("test1", result.Name);
            Assert.Equal("description1", result.Description);
        }
        public async Task SeedAsync(AlexandriaDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext.EditionLanguages.Any())
            {
                return;
            }

            var languages = new List <string>
            {
                "English",
                "Spanish",
                "Portuguese",
                "Russian",
                "Japanese",
                "Mandarin",
                "Turkish",
                "Korean",
                "French",
                "German",
                "Italian",
                "Vietnamese",
                "Polish",
                "Dutch",
                "Bulgarian",
                "Czech",
            };

            foreach (var language in languages)
            {
                await dbContext.EditionLanguages.AddAsync(new EditionLanguage
                {
                    Name = language,
                });
            }
        }
Exemple #16
0
        public async Task AreReviewsAboutSameBookShouldReturnFalseIfDeleted()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.AddRangeAsync(
                new Review
            {
                Description     = "description1",
                AuthorId        = "author1",
                BookId          = 1,
                ReadingProgress = ReadingProgress.Finished,
                IsDeleted       = true,
            },
                new Review
            {
                Description     = "description2",
                AuthorId        = "author2",
                BookId          = 1,
                ReadingProgress = ReadingProgress.Finished,
            });

            await db.SaveChangesAsync();

            var reviewsService = new ReviewsService(db);

            var result = await reviewsService.AreReviewsAboutSameBookAsync(1, 1);

            Assert.False(result);
        }
Exemple #17
0
        public async Task SeedAsync(AlexandriaDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext.Awards.Any())
            {
                return;
            }

            var awards = new List <string>
            {
                "Goodreads Choice Award",
                "RITA Award by Romance Writers of America",
                "Locus Award",
                "Dorothy Canfield Fisher Children's Book Award",
                "National Book Award Finalist",
                "Lambda Literary Award",
                "Edgar Award",
                "World Fantasy Award",
                "Kindle Book Award",
                "National Book Award",
                "National Book Critics Circle Award",
                "Independent Publisher Book Award (IPPY)",
            };

            foreach (var award in awards)
            {
                await dbContext.Awards.AddAsync(new Award
                {
                    Name      = award,
                    CreatedOn = DateTime.UtcNow,
                });
            }
        }
Exemple #18
0
        public async Task GetAuthorIdByIdShouldReturnNullIfDeleted()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.AddRangeAsync(
                new Review
            {
                Description = "description1",
                AuthorId    = "author1",
                BookId      = 1,
                IsDeleted   = true,
            },
                new Review
            {
                Description = "description2",
                AuthorId    = "author1",
                BookId      = 1,
                ParentId    = 1,
            });

            await db.SaveChangesAsync();

            var reviewsService = new ReviewsService(db);

            var result = await reviewsService.GetAuthorIdByIdAsync(1);

            Assert.Null(result);
        }
Exemple #19
0
        public async Task DoesAwardExistMethodShouldReturnTrueIfExists()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            var awards = new List <Award>
            {
                new Award
                {
                    Name      = "test1",
                    CreatedOn = DateTime.UtcNow,
                },
                new Award
                {
                    Name      = "test2",
                    CreatedOn = DateTime.UtcNow,
                },
                new Award
                {
                    Name      = "test3",
                    CreatedOn = DateTime.UtcNow,
                },
            };

            await db.Awards.AddRangeAsync(awards);

            await db.SaveChangesAsync();

            var awardsService = new AwardsService(db);

            Assert.True(await awardsService.DoesAwardIdExistAsync(1));
        }
Exemple #20
0
        public async Task DoesReviewIdExistShouldReturnFalseIfNotFound()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.AddRangeAsync(
                new Review
            {
                Description = "description1",
                AuthorId    = "author1",
                BookId      = 1,
            },
                new Review
            {
                Description = "description2",
                AuthorId    = "author1",
                BookId      = 1,
                ParentId    = 1,
            });

            await db.SaveChangesAsync();

            var reviewsService = new ReviewsService(db);

            var result = await reviewsService.DoesReviewIdExistAsync(5);

            Assert.False(result);
        }
Exemple #21
0
        public async Task AddTagsToBookMethodShouldNotAddBookTagsWhichExist()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            await db.BookTags.AddRangeAsync(
                new BookTag
            {
                BookId = 1,
                TagId  = 1,
            },
                new BookTag
            {
                BookId = 1,
                TagId  = 2,
            });

            await db.SaveChangesAsync();

            var bookTagsService = new BookTagsService(db);

            var addTags = new List <int> {
                1, 2, 3, 4, 5, 5, 5, 5, 5, 5
            };

            await bookTagsService.AddTagsToBookAsync(1, addTags);

            Assert.Equal(5, await db.BookTags.CountAsync());
        }
Exemple #22
0
        public async Task EditReviewShouldWorkCorrectly(string description, ReadingProgress progress, bool thisEdition)
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.AddAsync(
                new Review
            {
                Description     = "description1",
                AuthorId        = "author1",
                BookId          = 1,
                ReadingProgress = ReadingProgress.Unknown,
                ThisEdition     = false,
            });

            await db.SaveChangesAsync();

            var reviewsService = new ReviewsService(db);

            await reviewsService.EditReviewAsync(1, description, progress, thisEdition);

            var result = await db.Reviews.FirstOrDefaultAsync();

            Assert.NotNull(result.ModifiedOn);
            Assert.Equal(description, result.Description);
            Assert.Equal(progress, result.ReadingProgress);
            Assert.Equal(thisEdition, result.ThisEdition);
        }
Exemple #23
0
        public async Task GetRatesCountByBookIdShouldReturnZeroWhenInvalidBookId()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            var rates = new List <StarRating>();

            for (int i = 1; i <= 10; i++)
            {
                rates.Add(new StarRating
                {
                    Rate   = i,
                    UserId = i.ToString(),
                    BookId = 1,
                });
            }

            await db.AddRangeAsync(rates);

            await db.SaveChangesAsync();

            var ratingsService = new StarRatingsService(db);
            var result         = await ratingsService.GetRatesCountByBookIdAsync(3);

            Assert.Equal(0, result);
        }
Exemple #24
0
        public async Task GetAllReviewsByAuthorIdShouldReturnAllReviews()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.AddRangeAsync(
                new Review
            {
                Description = "description1",
                AuthorId    = "author1",
            },
                new Review
            {
                Description = "description1",
                AuthorId    = "author1",
            },
                new Review
            {
                Description = "description1",
                AuthorId    = "author1",
            });

            await db.SaveChangesAsync();

            var reviewsService = new ReviewsService(db);

            var result = await reviewsService.GetAllReviewsByAuthorIdAsync <ReviewTestModel>("author1");

            Assert.Equal(3, result.Count());
        }
Exemple #25
0
        public async Task GetAllRatesByUserIdShouldReturnCorrectCountWhenTakeAndSkipAreUsed()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            var rates = new List <StarRating>();

            for (int i = 1; i <= 10; i++)
            {
                rates.Add(new StarRating
                {
                    Rate   = i,
                    UserId = "userId",
                    BookId = i,
                });
            }

            await db.StarRatings.AddRangeAsync(rates);

            await db.SaveChangesAsync();

            var ratingsService = new StarRatingsService(db);

            var result = await ratingsService.GetAllRatesByUserIdAsync <RatingTestModel>("userId", 5, 5);

            Assert.Equal(5, result.Count());
        }
Exemple #26
0
        public async Task DeleteReviewShouldSetIsDeletedAndDeletedOn()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.AddRangeAsync(
                new Review
            {
                Description     = "description1",
                AuthorId        = "author1",
                BookId          = 1,
                ReadingProgress = ReadingProgress.Finished,
            },
                new Review
            {
                Description     = "description2",
                AuthorId        = "author2",
                BookId          = 1,
                ReadingProgress = ReadingProgress.Finished,
            });

            await db.SaveChangesAsync();

            var reviewsService = new ReviewsService(db);

            await reviewsService.DeleteReviewByIdAsync(1);

            var result = await db.Reviews.FirstOrDefaultAsync();

            Assert.NotNull(result.DeletedOn);
            Assert.True(result.IsDeleted);
        }
Exemple #27
0
        public async Task CreateRatingMethodShouldNotChangeCountIfRatingExists()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            await db.StarRatings.AddAsync(
                new StarRating
            {
                Rate   = 1,
                UserId = "userId",
                BookId = 1,
            });

            await db.SaveChangesAsync();

            var starRatingsService = new StarRatingsService(db);

            await starRatingsService.CreateRatingAsync(5, "userId", 1);

            var result = await db.StarRatings.CountAsync();

            Assert.Equal(1, result);
        }
Exemple #28
0
        public async Task GetReviewByIdShouldReturnCorrectReview()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.AddRangeAsync(
                new Review
            {
                Description = "description1",
                AuthorId    = "author1",
                BookId      = 1,
            },
                new Review
            {
                Description = "description2",
                AuthorId    = "author1",
                BookId      = 1,
                ParentId    = 1,
            });

            await db.SaveChangesAsync();

            var reviewsService = new ReviewsService(db);

            var result = await reviewsService.GetReviewByIdAsync <ReviewTestModel>(2);

            Assert.Equal("description2", result.Description);
            Assert.NotNull(result.ParentId);
        }
Exemple #29
0
        public async Task GetAuthorByIdShouldReturnNullWhenDeleted()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);

            await db.Authors.AddAsync(
                new Author
            {
                FirstName  = "first1",
                SecondName = "second1",
                LastName   = "last1",
                IsDeleted  = true,
                DeletedOn  = DateTime.UtcNow,
            });

            await db.SaveChangesAsync();

            var authorsService = new AuthorsService(db);

            var result = await authorsService.GetAuthorByIdAsync <AuthorTestModel>(1);

            Assert.Null(result);
        }
Exemple #30
0
        public async Task DeleteGenreShouldSetIsDeletedAndDeletedOn()
        {
            var options = new DbContextOptionsBuilder <AlexandriaDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var db = new AlexandriaDbContext(options);
            await db.Genres.AddAsync(
                new Genre
            {
                Name        = "test",
                Description = "description",
            });

            await db.SaveChangesAsync();

            var genresService = new GenresService(db);

            await genresService.DeleteGenreByIdAsync(1);

            var result = await db.Genres.FirstOrDefaultAsync();

            Assert.True(result.IsDeleted);
            Assert.NotNull(result.DeletedOn);
        }