Example #1
0
        public void DeleteRecord_Returns_OkResult()
        {
            // Arrange
            var recordServiceMock = new Mock <IRecordService>();

            recordServiceMock.Setup(service => service
                                    .GetRecordByIdAsync(It.IsAny <int>()))
            .Returns(Task.FromResult(GetRecord()));

            recordServiceMock.Setup(service => service
                                    .DeleteRecordByIdAsync(It.IsAny <int>()))
            .Returns(Task.FromResult(true));

            var loggerMock = new Mock <ILogger <RecordsController> >();

            var controller = new RecordsController(recordServiceMock.Object, loggerMock.Object);
            var id         = 1;

            // Act
            var result = controller.DeleteRecord(id).GetAwaiter().GetResult();

            // Assert
            var okObjectResult = Assert.IsType <OkObjectResult>(result);

            Assert.IsAssignableFrom <int>(okObjectResult.Value);
        }
Example #2
0
        public void UpdateRecord_WithNullValue_Returns_ConflictResult()
        {
            // Arrange
            var recordServiceMock = new Mock <IRecordService>();

            recordServiceMock.Setup(service => service
                                    .GetRecordByIdAsync(It.IsAny <int>()))
            .Returns(Task.FromResult(GetRecord()));

            recordServiceMock.Setup(service => service
                                    .UpdateRecordAsync(It.IsAny <RecordDTO>()))
            .Returns(Task.FromResult(false));

            var loggerMock = new Mock <ILogger <RecordsController> >();

            var controller = new RecordsController(recordServiceMock.Object, loggerMock.Object);
            var recordDTO  = new RecordDTO {
                Id = 1
            };

            // Act
            var result = controller.UpdateRecord(recordDTO).GetAwaiter().GetResult();

            // Assert
            var conflictResult = Assert.IsType <ConflictResult>(result);
        }
Example #3
0
        public void Delete_Throws()
        {
            // Arrange
            var mapper = Substitute.For <IMapper>();
            var repo   = Substitute.For <IRepository>();

            repo.DeleteRecord(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <string>()).Returns(Task.FromException <int>(new System.Exception("Boom")));

            var logger = Substitute.For <ILogger <RecordsController> >();

            var target = new RecordsController(repo, logger, mapper);

            // Act
            var result = target.Delete("testAppName", "dataType", "version1").Result;

            // Assert
            logger.Received().Log(
                LogLevel.Error,
                Arg.Any <EventId>(),
                Arg.Is <object>(o => o.ToString() == "Boom"),
                null,
                Arg.Any <Func <object, Exception, string> >());

            Assert.IsType <BadRequestObjectResult>(result);
        }
Example #4
0
        public void Post_Update()
        {
            // Arrange
            var recordContract = new RecordContract
            {
                ApplicationName = "testAppName",
                DataType        = "dataType",
                Version         = "version1",
                Value           = "value",
                DateCreated     = DateTime.UtcNow,
                DateModified    = DateTime.UtcNow
            };

            var mapper = Substitute.For <IMapper>();
            var repo   = Substitute.For <IRepository>();

            repo.UpsertRecord(Arg.Any <Model.Record>()).Returns(Task.FromResult <Model.Record>(new Model.Record
            {
                DateModified = DateTime.Now
            }));

            var logger = Substitute.For <ILogger <RecordsController> >();

            var target = new RecordsController(repo, logger, mapper);

            // Act
            var result = target.Post(recordContract).Result;

            // Assert
            Assert.IsType <OkObjectResult>(result);
        }
Example #5
0
        public void Get_Url_Throw_NotFound()
        {
            // Arrange
            Mock <IHistoryRecordService> mock = new Mock <IHistoryRecordService>();

            mock.Setup(m => m.GetHistoryRecord(It.IsAny <long>())).Returns((HistoryRecord)null);
            var historyRecordService = mock.Object;

            var controller = new RecordsController(historyRecordService);

            SetupControllerForTests(controller);

            string hash = "70y856ilox";

            // Act
            try
            {
                var result = controller.Get(hash);
            }

            // Assert
            catch (HttpResponseException ex)
            {
                Assert.AreEqual(System.Net.HttpStatusCode.NotFound, ex.Response.StatusCode);
                throw;
            }
        }
        public void cloned_record_should_have_null_publication()
        {
            var record = new Record
            {
                Id          = new Guid("736532c8-9b3d-4524-86ac-248e0476fa38"),
                Path        = @"X:\some\path",
                Gemini      = Library.Blank().With(m => m.Title = "Some new record!"),
                Publication = new PublicationInfo
                {
                    OpenData = new OpenDataPublicationInfo
                    {
                        Assessment = new OpenDataAssessmentInfo
                        {
                            Completed = true
                        }
                    }
                }
            };

            var db         = Mock.Of <IDocumentSession>(d => d.Load <Record>(It.IsAny <Guid>()) == record);
            var service    = Mock.Of <IRecordService>();
            var controller = new RecordsController(service, db, new TestUserContext());

            var result = (RecordOutputModel)controller.Get(record.Id, true);

            result.Record.Id.Should().BeEmpty();
            result.Record.Path.Should().BeEmpty();
            result.Record.Gemini.Title.Should().BeEmpty();
            result.Record.Publication.Should().BeNull();
        }
Example #7
0
        public void AssertScenarioGetByGender()
        {
            // Setup TEst
            RecordsController controller           = new RecordsController();
            const int         expectedRecordCount  = 6;
            const string      expectedGenderFeMale = "F";
            const string      expectedGenderMale   = "M";

            // Act
            List <Person> result = controller.GetByGender();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(expectedRecordCount, result.Count());

            Person recordOne = result.ElementAt(0);

            Assert.AreEqual(expectedGenderFeMale, recordOne.Gender);
            Person recordTwo = result.ElementAt(1);

            Assert.AreEqual(expectedGenderFeMale, recordTwo.Gender);
            Person recordThree = result.ElementAt(2);

            Assert.AreEqual(expectedGenderFeMale, recordThree.Gender);
            Person recordFour = result.ElementAt(3);

            Assert.AreEqual(expectedGenderMale, recordFour.Gender);
            Person recordFive = result.ElementAt(4);

            Assert.AreEqual(expectedGenderMale, recordFive.Gender);
            Person recordSix = result.ElementAt(5);

            Assert.AreEqual(expectedGenderMale, recordSix.Gender);
        }
        public async void PostAddsRecord()
        {
            var mockRecordRepository = new Mock <IRecordRepository>();

            mockRecordRepository
            .Setup(p => p.Add(It.IsAny <Models.Record>()))
            .Returns(async() =>
            {
                await Task.Yield();
            });
            var recordRepository = mockRecordRepository.Object;
            var target           = new RecordsController(recordRepository);

            var recordToPost = new Models.Record {
                Id = "", Value = "This is a good record."
            };
            var result = await target.Post(recordToPost);

            Assert.IsAssignableFrom <HttpOkObjectResult>(result);

            var record = ((HttpOkObjectResult)result).Value as Models.Record;

            Assert.NotNull(record);
            Assert.False(string.IsNullOrWhiteSpace(record.Id), "Record Id should not be null.");
            Assert.Equal(recordToPost.Value, record.Value);
        }
        public async void GetAllReturnsTwoResults()
        {
            var records = new[]
            {
                new Models.Record {
                    Id = "1", Value = "Value 1"
                },
                new Models.Record {
                    Id = "2", Value = "Value 2"
                }
            };

            var mockRecordRepository = new Mock <IRecordRepository>();

            mockRecordRepository
            .Setup(p => p.GetAll())
            .Returns(async() =>
            {
                await Task.Yield();
                return(records);
            });
            var recordRepository = mockRecordRepository.Object;
            var target           = new RecordsController(recordRepository);

            var result = await target.Get();

            Assert.IsAssignableFrom <ObjectResult>(result);

            var expected = JsonConvert.SerializeObject(new { items = records });

            Assert.Equal(expected, JsonConvert.SerializeObject(((ObjectResult)result).Value));
        }
Example #10
0
        public void AssertScenarioPostNewPerson()
        {
            // Setup Test
            RecordsController controller          = new RecordsController();
            const int         expectedRecordCount = 7;

            Person personToAdd = new Person
            {
                FirstName     = "TestFirst",
                LastName      = "TestLast",
                Gender        = "F",
                BirthDate     = Convert.ToDateTime("1/1/2000"),
                FavoriteColor = "Infrared"
            };

            // Act
            controller.Post(personToAdd);

            // Get the people
            List <Person> result = controller.GetByGender();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(expectedRecordCount, result.Count());
        }
Example #11
0
        public void List()
        {
            // Arrange
            var mapper = Substitute.For <IMapper>();
            var repo   = Substitute.For <IRepository>();

            repo.ListRecords().Returns(x =>
            {
                return(new List <Model.Record>()
                {
                    new Model.Record {
                        ApplicationName = "appName",
                        DataType = "dataType",
                        Value = "test",
                        Version = "1.0",
                    }
                });
            });
            var logger = Substitute.For <ILogger <RecordsController> >();

            var target = new RecordsController(repo, logger, mapper);

            // Act
            var result = target.List();

            // Assert
            Assert.IsType <OkObjectResult>(result);
        }
Example #12
0
        public void Is_BirthDates_Sorted_Correctly()
        {
            //Local variables.
            RecordsController controller = new RecordsController();

            //Conduct Test Experiment.
            List <Person> people = (List <Person>)GetDummyData();

            controller.SavePerson(people[0]);
            controller.SavePerson(people[1]);
            controller.SavePerson(people[2]);
            controller.SavePerson(people[3]);
            controller.SavePerson(people[4]);
            controller.SavePerson(people[5]);
            controller.SavePerson(people[6]);
            controller.SavePerson(people[7]);
            controller.SavePerson(people[8]);
            controller.SavePerson(people[9]);
            controller.SavePerson(people[10]);
            controller.SavePerson(people[11]);

            var results = (OkNegotiatedContentResult <List <Person> >)controller.GetBirthDates();

            //Determine Test Results

            //Make sure we have results.
            if (results == null || results.Content.Count == 0)
            {
                Assert.IsTrue(true == false); //Test fails automatically with no data.
            }
            //Since we can control the testing data.
            //We need to make sure the data is sorted by birth ascending.
            //So let's check the first and last birthdates to ensure this.
            Assert.IsTrue(results.Content[0].DateOfBirth.ToShortDateString() == "1/1/1979" && results.Content[4].DateOfBirth.ToShortDateString() == "1/1/1983");
        }
        public void SortRecordsByNameTest()
        {
            RecordsController recordsController = new RecordsController(_mockRecordService.Object);
            List <RecordDto>  recordsDto        = recordsController.Name();

            Assert.AreEqual("Gates", recordsDto[0].LastName);
        }
Example #14
0
        public void Is_Names_Sorted_Correctly()
        {
            //Local variables.
            RecordsController controller = new RecordsController();

            //Conduct Test Experiment.
            List <Person> people = (List <Person>)GetDummyData();

            controller.SavePerson(people[0]);
            controller.SavePerson(people[1]);
            controller.SavePerson(people[2]);
            controller.SavePerson(people[3]);
            controller.SavePerson(people[4]);
            controller.SavePerson(people[5]);
            controller.SavePerson(people[6]);
            controller.SavePerson(people[7]);
            controller.SavePerson(people[8]);
            controller.SavePerson(people[9]);
            controller.SavePerson(people[10]);
            controller.SavePerson(people[11]);

            var results = (OkNegotiatedContentResult <List <Person> >)controller.GetNames();

            //Determine Test Results

            //Make sure we have results.
            if (results == null || results.Content.Count == 0)
            {
                Assert.IsTrue(true == false); //Test fails automatically with no data.
            }
            //Since we can control the testing data.
            //We need to make sure the data is sorted by last name desc.
            //So let's check the first.
            Assert.IsTrue(results.Content[0].LastName == "Molly");
        }
        public void SortRecordsByBirthDayTest()
        {
            RecordsController recordsController = new RecordsController(_mockRecordService.Object);
            List <RecordDto>  recordsDto        = recordsController.Birthdate();

            Assert.AreEqual("Jobs", recordsDto[0].LastName);
        }
        public void SortRecordsByGenderTest()
        {
            RecordsController recordsController = new RecordsController(_mockRecordService.Object);
            List <RecordDto>  recordsDto        = recordsController.Gender();

            Assert.AreEqual("Female", recordsDto[0].Gender);
        }
Example #17
0
        private static void WorkWithRecord()
        {
            var service    = _serviceProvider.GetRequiredService <IService <Record, int> >();
            var controller = new RecordsController(service);

            controller.Start();
        }
Example #18
0
        public void AddOne_Pipe_AddsSuccessfully()
        {
            var controller = new RecordsController();

            controller.Add(new AddRecordRequestModel
            {
                data = "Pippen | Scottie | Male | Red | 10/25/1965"
            });

            var output = controller.GetByBirthDate();

            var result =
                output as
                System.Web.Http.Results.OkNegotiatedContentResult
                <IOrderedEnumerable <Person> >;

            Assert.IsNotNull(result);

            Assert.AreEqual(1, result.Content.Count());

            var pippen = result.Content.ElementAt(0);

            Assert.AreEqual("Pippen", pippen.LastName);
            Assert.AreEqual("Scottie", pippen.FirstName);
            Assert.AreEqual(Gender.Male, pippen.Gender);
            Assert.AreEqual("Red", pippen.FavoriteColor);
            Assert.AreEqual(new DateTime(1965, 10, 25), pippen.DateOfBirth);
        }
Example #19
0
        public void Post_Throws()
        {
            // Arrange
            var recordContract = new RecordContract
            {
                ApplicationName = "testAppName",
                DataType        = "dataType",
                Version         = "version1",
                Value           = "value",
                DateCreated     = DateTime.UtcNow,
                DateModified    = DateTime.UtcNow
            };

            var mapper = Substitute.For <IMapper>();
            var repo   = Substitute.For <IRepository>();

            repo.UpsertRecord(Arg.Any <Model.Record>()).Returns(Task.FromException <Model.Record>(new System.Exception("Boom")));
            var logger = Substitute.For <ILogger <RecordsController> >();

            var target = new RecordsController(repo, logger, mapper);

            // Act
            var result = target.Post(recordContract).Result;

            // Assert
            logger.Received().Log(
                LogLevel.Error,
                Arg.Any <EventId>(),
                Arg.Is <object>(o => o.ToString() == "Boom"),
                null,
                Arg.Any <Func <object, Exception, string> >());

            Assert.IsType <BadRequestObjectResult>(result);
        }
        public void TestInitialize()
        {
            List <Model> models = GetModels();

            _dataFileReader.Setup(_ => _.ReadFiles(It.IsAny <string[]>())).ReturnsAsync(models);
            _dataFileWriter.Setup(_ => _.WriteModelToFile(It.IsAny <Model>(), It.IsAny <FileInfo>())).ReturnsAsync(true);
            _controller = new RecordsController(_dataFileReader.Object, _dataFileWriter.Object);
        }
Example #21
0
 public void PostInvalid(ref RecordsController controller)
 {
     controller.Post("blahblahblah");
     controller.Post("Error: incorrect number of elements");
     controller.Post("");
     controller.Post("Person|Mister|Female|yellow|NotADate");
     controller.Post("Rogers|Fred|NotAGender|Love|3/20/1928");
 }
        public void should_return_blank_record_for_empty_guid()
        {
            var controller   = new RecordsController(Mock.Of <IRecordService>(), Mock.Of <IDocumentSession>(), new TestUserContext());
            var recordResult = (RecordOutputModel)controller.Get(Guid.Empty);

            recordResult.Record.Gemini.Title.Should().BeBlank();
            recordResult.Record.Path.Should().BeBlank();
        }
Example #23
0
        public void TestGetAll()
        {
            var controller = new RecordsController();

            var result = controller.GetRecords() as List <Record>;

            Assert.AreEqual(2, result.Count);
        }
Example #24
0
        public void TestGetRecordByTitle()
        {
            var controller = new RecordsController();

            var result = controller.GetByTitle("Castle of Glass");

            Assert.AreEqual("Castle of Glass", result.Title);
            Assert.AreEqual("Linkin Park", result.Artist);
        }
Example #25
0
 public void PostValid(ref RecordsController controller)
 {
     controller.Post("Smith Robert M Purple 2/4/1988");
     controller.Post("Zebedane Zebediah Male Purple 3/3/1987");
     controller.Post("Does, Jane, FEM, yellow, 2/19/1942");
     controller.Post("Cooper, Sue, F, y, 5/17/1976");
     controller.Post("McCoy Mark male grn 1/2/1990");
     controller.Post("Danielson Jennifer Female BLUE 12/1/2001");
 }
Example #26
0
        public void InvalidData_ThrowsException()
        {
            var controller = new RecordsController();

            Assert.Throws(typeof(InvalidOperationException), () => controller.Add(new AddRecordRequestModel
            {
                data = "asdioudolcl"
            }));
        }
        protected override void Arrange()
        {
            controller = new RecordsController();

            var menString = "Fowler | Martin | Male | Blue | 1/1/1963" + Environment.NewLine +
                            "Kent | Beck | Male | Green | 1/1/1961" + Environment.NewLine +
                            "Liskova | Barbara | Female | Yellow | 1/1/1952";

            controller.Post(menString);
        }
        public async void DeleteReturnsBadRequestWhenNoIdProvided()
        {
            var mockRecordRepository = new Mock <IRecordRepository>();
            var recordRepository     = mockRecordRepository.Object;
            var target = new RecordsController(recordRepository);

            var result = await target.Delete("   ");

            Assert.IsAssignableFrom <BadRequestObjectResult>(result);
            Assert.Equal("Record Id not supplied.", ((BadRequestObjectResult)result).Value);
        }
        public async void PutReturnsBadRequestWhenNoRecordProvided()
        {
            var mockRecordRepository = new Mock <IRecordRepository>();
            var recordRepository     = mockRecordRepository.Object;
            var target = new RecordsController(recordRepository);

            var result = await target.Put("ABC", null);

            Assert.IsAssignableFrom <BadRequestObjectResult>(result);
            Assert.Equal("No record supplied.", ((BadRequestObjectResult)result).Value);
        }
        public void Get_InvalidResponse_SortFieldDoesntExists()
        {
            var controller = new RecordsController();

            controller.Request       = new HttpRequestMessage();
            controller.Configuration = new HttpConfiguration();

            var response = controller.Get("Unkown");

            Assert.AreEqual(response.IsSuccessStatusCode, false);
        }
 public void Setup()
 {
     _recordRepository = MockRepository.GenerateMock<IRecordRepository>();
     _sortFactory = MockRepository.GenerateMock<ISortStrategyFactory>();
     _sut = new RecordsController(_sortFactory,_recordRepository);
 }
 public RecordsForm(RecordsController c)
 {
     controller = c;
     InitializeComponent();
     records_datagridview.DataSource = controller.GetData();
 }
Example #33
0
 public void Setup()
 {
     var container = BuildContainer();
     SetupPostInitDependencies(container);
     _sut = container.Resolve<RecordsController>();
 }