/// <summary>
        /// Here is how we'll do the test
        /// </summary>
        public void TestReadWriteJson()
        {
            var testHelper = new TestDataHelper();
            var convertSample = new JsonConverterSample();

            var testObject = testHelper.CreateSampleObject();

            // Try to get JSON text
            string jsonText = convertSample.ConvertDataToJson(testObject);

            // See the output
            testHelper.WriteJsonToConsole(jsonText);

            /*** ... Importnat part starts here ... ***/

            // Add converter for Sets
            JsonSerializer serializer = convertSample.JsonSerializer;
            serializer.Converters.Add(new SetConverter());

            // The rest is normal also ...

            // Try to create new object from JSON text, using ISet for list of int
            var newObjectCopy = convertSample.GetObjectFromJson<ISet<int>>(jsonText);

            // See the output
            testHelper.WriteObjectToConsole(newObjectCopy);
        }
 public void SetUp()
 {
     testDataHelper = new TestDataHelper();
     uploadFileRepository = new UploadFileRepository();
     constituent = testDataHelper.CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin()));
     savedUpload = testDataHelper.CreateUpload(UploadMother.Test(constituent));
 }
Esempio n. 3
0
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();

            savedConstituent = testDataHelper.CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin()));
            testDataHelper.CreatePhone(PhoneMother.PrimaryMobile(savedConstituent));
        }
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();

            constituent = testDataHelper.CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin()));
            savedAddress = testDataHelper.CreateAddress(AddressMother.SanFrancisco(constituent));
        }
Esempio n. 5
0
 public void Setup()
 {
     testDataHelper = new TestDataHelper();
     var constituentWithName = ConstituentMother.ConstituentWithName(ConstituentNameMother.AgnesAlba());
     constituentWithName.BranchName = BranchTypeMother.Anavalaril();
     constituentWithName.HouseName = "xyz";
     savedConstituent = testDataHelper.CreateConstituent(constituentWithName);
 }
 public void SetUp()
 {
     testDataHelper = new TestDataHelper();
     var constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());
     savedConstituent = testDataHelper.CreateConstituent(constituent);
     educationDetailRepository = new EducationDetailRepository(testDataHelper.session);
     savedEducationalDetail = testDataHelper.CreateEducationDetail(EducationDetailMother.School(savedConstituent));
 }
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();

            constituent = testDataHelper.CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin()));
            reciprocalConstituent = testDataHelper.CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.AgnesAlba()));
            savedAssociation = testDataHelper.CreateAssociation(AsociationMother.JamesFranklinAndJessicaAlba(constituent,reciprocalConstituent));
        }
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();

            constituent1 = testDataHelper.CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin()));

            testDataHelper.CreateUpload(UploadMother.Test(constituent1));
        }
 public void SetUp()
 {
     testDataHelper = new TestDataHelper();
     committeeRepository = new CommitteeRepository(testDataHelper.session);
     var constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());
     savedConstituent = testDataHelper.CreateConstituent(constituent);
     savedCommittee = testDataHelper.CreateCommittee(CommitteeMother.President(savedConstituent));
 }
 public void SetUp()
 {
     testDataHelper = new TestDataHelper();
     constituent = testDataHelper.CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin()));
     testDataHelper.CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.AgnesAlba()));
     constituentData = new ConstituentData { Gender = "F", BornOn = DateTime.Now, BranchName = new BranchTypeData { Id = 1, Description = "Kallivayalil" }, MaritialStatus = 1 };
     constituentData.Name = new ConstituentNameData {FirstName = "James", LastName = "Franklin", Salutation = new SalutationTypeData {Id = 1, Description = "Mr"}};
 }
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();
            repository = new ConstituentNameRepository(testDataHelper.session);

            jamesFranklin = ConstituentNameMother.JamesFranklin();
            savedConstituentName = testDataHelper.CreateConstituentName(jamesFranklin);
        }
 public void SetUp()
 {
     testDataHelper = new TestDataHelper();
     var constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());
     savedConstituent = testDataHelper.CreateConstituent(constituent);
     savedAddress = testDataHelper.CreateAddress(AddressMother.SanFrancisco(savedConstituent));
     occupationRepository = new OccupationRepository(testDataHelper.session);
     savedOccupation = testDataHelper.CreateOccupation(OccupationMother.Doctor(savedConstituent, savedAddress));
 }
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();

            constituent = new Constituent {Gender = "M", BornOn = DateTime.Today, BranchName = BranchTypeMother.Kallivayalil(), MaritialStatus = 1, IsRegistered = 'N'};
            constituent.Name = ConstituentNameMother.JamesFranklin();

            registerationRepository = new RegisterationRepository();
        }
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();
            var constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());
            savedConstituent = testDataHelper.CreateConstituent(constituent);
            savedAddress = testDataHelper.CreateAddress(AddressMother.SanFrancisco(savedConstituent));

            addressRepository = new AddressRepository(testDataHelper.session);
        }
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();

            jamesFranklin = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());
            savedConstituent = testDataHelper.CreateConstituent(jamesFranklin);

            savedEvent = testDataHelper.CreateEvent(EventMother.Anniversary());
            eventRepository = new EventRepository();
        }
Esempio n. 16
0
        public void ShouldSendMailForForgotPassword()
        {
            testDataHelper = new TestDataHelper();
            var constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());
            var savedConstituent = testDataHelper.CreateConstituent(constituent);
            var email = testDataHelper.CreateEmail(EmailMother.Personal(savedConstituent, true));
            var login = testDataHelper.CreateUser(LoginMother.User(email, "Pass", false));

            var response = HttpHelper.DoHttpGet(string.Format("{0}?email={1}", "http://localhost/kallivayalilService/KallivayalilService.svc/Login/ForgotPassword",email.Address));
            Assert.That(response.StatusCode,Is.EqualTo(HttpStatusCode.OK));
        }
        public void SetUp()
        {
            testDataHelper = new TestDataHelper();
            var constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());
            savedConstituent = testDataHelper.CreateConstituent(constituent);

            constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.AgnesAlba());
            savedAssociatedConstituent = testDataHelper.CreateConstituent(constituent);

            savedAssociation = testDataHelper.CreateAssociation(AsociationMother.JamesFranklinAndParent(savedConstituent));

            associationRepository = new AssociationRepository(testDataHelper.session);
        }
Esempio n. 18
0
        public void ShouldLoadExistingLogin()
        {
            testDataHelper = new TestDataHelper();
            var constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());

            var savedConstituent = testDataHelper.CreateConstituent(constituent);
            var email = testDataHelper.CreateEmail(EmailMother.Official(savedConstituent));
            var login = testDataHelper.CreateUser(LoginMother.User(email, "Pass", false));

            var emailData = HttpHelper.Get<LoginData>(string.Format("{0}?username={1}", "http://localhost/kallivayalilService/KallivayalilService.svc/Login", email.Address));

            Assert.That(emailData.Id, Is.GreaterThan(0));
        }
        public void ShouldUpdateConstituentName()
        {
            var constituent = new TestDataHelper().CreateConstituent(ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin()));

            constituent.Name.FirstName = "John";
            constituent.Name.LastName = "Smith";
            var mapper = new AutoDataContractMapper();
            var nameData = new ConstituentNameData();
            mapper.Map(constituent.Name, nameData);
            var constituentName = HttpHelper.Put(string.Format("{0}/{1}", baseUri, nameData.Id), nameData);

            Assert.IsNotNull(constituentName);
            Assert.That(constituentName.FirstName, Is.EqualTo("John"));
            Assert.That(constituentName.LastName, Is.EqualTo("Smith"));
        }
Esempio n. 20
0
        public void ShouldUpdateExistingUser()
        {
            testDataHelper = new TestDataHelper();
            var constituent = ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin());
            var savedConstituent = testDataHelper.CreateConstituent(constituent);
            var email = testDataHelper.CreateEmail(EmailMother.Personal(savedConstituent, false));
            var login = testDataHelper.CreateUser(LoginMother.User(email,"Pass",false));

            var loginData = LoginDataMother.User(email,"Pass1",true);
            var updatedData = HttpHelper.Put(string.Format("{0}/{1}", "http://localhost/kallivayalilService/KallivayalilService.svc/Login", login.Id), loginData);

            Assert.That(updatedData.Email.Address, Is.EqualTo(email.Address));
            Assert.That(updatedData.Password, Is.EqualTo("Pass1"));
            Assert.That(updatedData.IsAdmin, Is.EqualTo(true));
        }
        /// <summary>
        /// Here is how we'll do the test
        /// </summary>
        public void TestReadWriteJson()
        {
            var testHelper = new TestDataHelper();
            var convertSample = new JsonConverterSample();

            var testObject = testHelper.CreateSampleObject();

            // Try to get JSON text
            string jsonText = convertSample.ConvertDataToJson(testObject);

            // See the output
            testHelper.WriteJsonToConsole(jsonText);

            // Try to create new object from JSON text, using HAshSet for list of int
            var newObjectCopy = convertSample.GetObjectFromJson<HashSet<int>>(jsonText);

            // See the output
            testHelper.WriteObjectToConsole(newObjectCopy);
        }
Esempio n. 22
0
        public async Task AddXsd_DatamodelsRepo_ShouldReturnCreated()
        {
            // Arrange
            var org = "ttd";
            var sourceRepository = "empty-datamodels";
            var developer        = "testUser";
            var targetRepository = Guid.NewGuid().ToString();

            await TestDataHelper.CopyRepositoryForTest(org, sourceRepository, developer, targetRepository);

            var client = GetTestClient();
            var url    = $"{_versionPrefix}/{org}/{targetRepository}/datamodels/upload";

            var fileStream    = TestDataHelper.LoadDataFromEmbeddedResource("Designer.Tests._TestData.Model.Xsd.Kursdomene_HvemErHvem_M_2021-04-08_5742_34627_SERES.xsd");
            var formData      = new MultipartFormDataContent();
            var streamContent = new StreamContent(fileStream);

            streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
            formData.Add(streamContent, "file", "Kursdomene_HvemErHvem_M_2021-04-08_5742_34627_SERES.xsd");

            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Content = formData
            };

            await AuthenticationUtil.AddAuthenticateAndAuthAndXsrFCookieToRequest(client, httpRequestMessage);

            try
            {
                var response = await client.SendAsync(httpRequestMessage);

                Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            }
            finally
            {
                TestDataHelper.DeleteAppRepository(org, targetRepository, developer);
            }
        }
Esempio n. 23
0
        public async Task search_returns_null_when_null_is_passed_in(string tenancyRef, string tenancyRef2)
        {
            //arrange
            //property
            var expectedProperty = Fake.UniversalHousing.GenerateFakeProperty();

            TestDataHelper.InsertProperty(expectedProperty, _db);
            //tenancy
            var expectedTenancy = Fake.UniversalHousing.GenerateFakeTenancy();

            expectedTenancy.house_ref = expectedTenancy.house_ref;
            expectedTenancy.prop_ref  = expectedProperty.prop_ref;
            expectedTenancy.tag_ref   = tenancyRef;
            TestDataHelper.InsertTenancy(expectedTenancy, _db);
            //tenancy
            var expectedTenancy2 = Fake.UniversalHousing.GenerateFakeTenancy();

            expectedTenancy2.house_ref = expectedTenancy.house_ref;
            expectedTenancy2.prop_ref  = expectedProperty.prop_ref;
            expectedTenancy2.tag_ref   = tenancyRef2;
            TestDataHelper.InsertTenancy(expectedTenancy2, _db);
            //member
            var expectedMember = Fake.UniversalHousing.GenerateFakeMember();

            expectedMember.house_ref = expectedTenancy.house_ref;
            TestDataHelper.InsertMember(expectedMember, _db);

            //act
            var response = await _classUnderTest.SearchTenanciesAsync(new SearchTenancyRequest
            {
                PageSize = 10,
                Page     = 1
            }, CancellationToken.None);

            //assert
            response.Should().NotBeNull();
            response.Results.Should().BeNullOrEmpty();
        }
Esempio n. 24
0
        public async Task can_search_even_with_no_arrears_agreement(string lastName)
        {
            //arrange
            //property
            var expectedProperty = Fake.UniversalHousing.GenerateFakeProperty();

            TestDataHelper.InsertProperty(expectedProperty, _db);
            //tenancy
            var expectedTenancy = Fake.UniversalHousing.GenerateFakeTenancy();

            expectedTenancy.house_ref = expectedTenancy.house_ref;
            expectedTenancy.prop_ref  = expectedProperty.prop_ref;
            TestDataHelper.InsertTenancy(expectedTenancy, _db);
            //member 1
            var expectedMember = Fake.UniversalHousing.GenerateFakeMember();

            expectedMember.house_ref = expectedTenancy.house_ref;
            expectedMember.surname   = lastName;
            TestDataHelper.InsertMember(expectedMember, _db);
            //member 2
            var expectedMember2 = Fake.UniversalHousing.GenerateFakeMember();

            expectedMember2.house_ref = expectedTenancy.house_ref;
            expectedMember2.surname   = lastName;
            TestDataHelper.InsertMember(expectedMember2, _db);
            //act
            var response = await _classUnderTest.SearchTenanciesAsync(new SearchTenancyRequest
            {
                LastName = lastName,
                PageSize = 1,
                Page     = 1
            }, CancellationToken.None);

            //assert
            response.Should().NotBeNull();
            response.Results.Should().NotBeNullOrEmpty();
            response.TotalResultsCount.Should().Be(2);
        }
        public void UpdateEmployee_SupervisorsCountryIsNotSame_ShouldThrowException()
        {
            /************* Arrange: Setting up data containers ************************************************/

            //constants to be used in test containers (optional), for test readability

            const int    SUPERVISOR_ID                 = 100;
            const string SUPERVISOR_COUNTRY            = "USA";
            const int    SUBORDINATE_ID                = 200;
            const string SUBORDINATE_DIFFERENT_COUNTRY = "UK";

            //creating sample data for other employee, that would contain the different COUNTRY of the employee

            var supervisorEmployee = TestDataHelper.CreateEmployeeWithValidData();

            supervisorEmployee.Id = SUPERVISOR_ID;
            supervisorEmployee.Address.Country = SUPERVISOR_COUNTRY;

            _employee    = TestDataHelper.CreateEmployeeWithValidData();
            _employee.Id = SUBORDINATE_ID;
            _employee.Address.Country = SUBORDINATE_DIFFERENT_COUNTRY;
            _employee.ReportsTo       = SUPERVISOR_ID;

            /************* Arrange: Setting up mock test ************************************************/

            //populating sample data to ObjectSet container that would be considered as the data source in mock database for employee entities
            _fakeEmployeeDbSet.Add(supervisorEmployee);
            _fakeEmployeeDbSet.Add(_employee);

            //setting up the mock database with sample object
            _mockDbContext.Setup(db => db.EmployeeRepository).Returns(_fakeEmployeeDbSet);

            /************* Action ************************************************/
            _employeeController.Validate(_employee);

            /************* Assert ************************************************/
            Assert.True(SupervisorCountryMustBeSame.IsErrorAvalilableIn(_employeeController));
        }
Esempio n. 26
0
        public void UpdateIf_AppliedInfo_True_Test()
        {
            string query       = null;
            var    sessionMock = new Mock <ISession>(MockBehavior.Strict);

            sessionMock
            .Setup(s => s.ExecuteAsync(It.IsAny <BoundStatement>()))
            .Returns(TestHelper.DelayedTask(TestDataHelper.CreateMultipleValuesRowSet(new[] { "[applied]" }, new [] { true })))
            .Callback <BoundStatement>(b => query = b.PreparedStatement.Cql)
            .Verifiable();
            sessionMock
            .Setup(s => s.PrepareAsync(It.IsAny <string>()))
            .Returns <string>(cql => TestHelper.DelayedTask(GetPrepared(cql)))
            .Verifiable();
            var          mapper       = GetMappingClient(sessionMock);
            const string partialQuery = "SET title = ?, releasedate = ? WHERE id = ? IF artist = ?";
            var          appliedInfo  = mapper.UpdateIf <Song>(Cql.New(partialQuery, "Ramble On", new DateTime(1969, 1, 1), Guid.NewGuid(), "Led Zeppelin"));

            sessionMock.Verify();
            Assert.AreEqual("UPDATE Song " + partialQuery, query);
            Assert.True(appliedInfo.Applied);
            Assert.Null(appliedInfo.Existing);
        }
        public async Task GetDetailedCrossReferenceAddressRecord()
        {
            var uprn   = _faker.Random.Int();
            var record = _fixture.Build <CrossReference>()
                         .With(add => add.UPRN, uprn)
                         .Create();

            TestDataHelper.InsertCrossReference(DatabaseContext, uprn, record);

            var url      = new Uri($"api/v2/properties/{uprn}/crossreferences", UriKind.Relative);
            var response = await Client.GetAsync(url).ConfigureAwait(true);

            var apiResponse = await ConvertToCrossReferenceResponseObject(response).ConfigureAwait(true);

            var recordReturned = apiResponse.Data.AddressCrossReferences.FirstOrDefault();

            recordReturned.UPRN.Should().Be(uprn);
            recordReturned.Name.Should().Be(record.Name);
            recordReturned.Value.Should().Be(record.Value);
            recordReturned.Code.Should().Be(record.Code);
            recordReturned.CrossRefKey.Should().Be(record.CrossRefKey);
            recordReturned.EndDate.Value.Date.Should().Be(record.EndDate.Value.Date);
        }
        public async Task CanSearchAddressesByUprn()
        {
            var addressKey      = _faker.Random.String2(14);
            var queryParameters = new NationalAddress
            {
                UPRN = _faker.Random.Int(),
            };
            var record = await TestDataHelper.InsertAddressInDbAndEs(DatabaseContext, ElasticsearchClient, addressKey, queryParameters)
                         .ConfigureAwait(true);

            await AddSomeRandomAddressToTheDatabase().ConfigureAwait(true);

            var queryString = $"uprn={queryParameters.UPRN}&address_status={record.AddressStatus}&format=Detailed&address_scope=national";

            var response = await CallEndpointWithQueryParameters(queryString).ConfigureAwait(true);

            response.StatusCode.Should().Be(200);

            var returnedAddress = await response.ConvertToSearchAddressResponseObject().ConfigureAwait(true);

            returnedAddress.Data.Addresses.Count.Should().Be(1);
            returnedAddress.Data.Addresses.First().AddressKey.Should().Be(addressKey);
        }
        public void DuplicatePrimitiveValuesAreNotCircularObjectReference()
        {
            var dataObject = new DataObjectWithList
            {
                Strings = { "test", "test" },
                Ints    = { 1, 2, 1 }
            };

            string text;

            using (var ms = new MemoryStream())
                using (var reader = new StreamReader(ms, Encoding.UTF8))
                {
                    KvSerializer.Create(KvSerializationFormat.KeyValues1Text).Serialize(ms, dataObject, "test");

                    ms.Seek(0, SeekOrigin.Begin);
                    text = reader.ReadToEnd();
                }

            var expected = TestDataHelper.ReadTextResource("Text.non_circular_list.vdf");

            Assert.That(text, Is.EqualTo(expected));
        }
        public void CanDeleteItemFromCache()
        {
            //Create a new test user to save to the cache
            var user = TestDataHelper.CreateNewUser();

            //Add the cached object to our clean-up list
            _cachedObjects.Add(user.UserName);

            //Save the user to the cache
            _cacheService.Save(user.UserName, user);

            //Verify that the user is in the cache
            Assert.IsTrue(_cacheService.Exists(user.UserName));

            //Attempt to delete the object from the cache...
            var removeResult = _cacheService.Remove(user.UserName);

            //Assert that the item was indeed removed from the cache..
            Assert.IsTrue(removeResult);

            //Verify that the item was removed
            Assert.IsFalse(_cacheService.Exists(user.UserName));
        }
Esempio n. 31
0
        public MakePayRunPaymentUseCaseTests()
        {
            _payrun         = TestDataHelper.CreatePayRun(type: PayrunType.ResidentialRecurring, status: PayrunStatus.Approved);
            _payRunInsights = new PayRunInsightsDomain
            {
                TotalInvoiceAmount = 1000M,
                HoldsCount         = 5,
                TotalHeldAmount    = 100M
            };

            var payRunInvoiceGateway = new Mock <IPayRunInvoiceGateway>();

            _payRunGateway = new Mock <IPayRunGateway>();
            _dbManager     = new Mock <IDatabaseManager>();

            _payRunGateway.Setup(g => g.GetPayRunAsync(It.IsAny <Guid>(), It.IsAny <PayRunFields>(), It.IsAny <bool>()))
            .ReturnsAsync(_payrun);

            payRunInvoiceGateway.Setup(g => g.GetPayRunInsightsAsync(It.IsAny <Guid>())).ReturnsAsync(_payRunInsights);

            _useCase = new MakePayRunPaymentUseCase(_payRunGateway.Object, _dbManager.Object,
                                                    payRunInvoiceGateway.Object);
        }
        public void GetAddresses_WillGetASimpleAddressFromTheDatabase()
        {
            var addressKey   = _faker.Random.String2(14);
            var savedAddress = TestDataHelper.InsertAddressInDb(DatabaseContext, addressKey);

            var addresses = _classUnderTest.GetAddresses(new List <string> {
                addressKey
            }, GlobalConstants.Format.Simple);

            var expectedAddress = new Address
            {
                Line1    = savedAddress.Line1,
                Line2    = savedAddress.Line2,
                Line3    = savedAddress.Line3,
                Line4    = savedAddress.Line4,
                Town     = savedAddress.Town,
                UPRN     = savedAddress.UPRN,
                Postcode = savedAddress.Postcode
            };

            addresses.Count.Should().Be(1);
            addresses.First().Should().BeEquivalentTo(expectedAddress);
        }
Esempio n. 33
0
        void Can_prepare_merge_package()
        {
            // client end
            var    inspection   = TestDataHelper.ConstructInspection();
            var    checklist    = TestDataHelper.ConstructChecklist();
            var    mandate      = new Mandate(1, new[] { inspection });
            var    mergePackage = MergePackage.FromDomain(mandate, new[] { checklist, checklist });
            string filename     = Path.GetTempFileName() + ".json";

            File.WriteAllText(filename, JsonConvert.SerializeObject(mergePackage));

            // server end
            var receivedMergePackage = JsonConvert.DeserializeObject <MergePackage>(File.ReadAllText(filename));

            receivedMergePackage.Should().NotBeNull();
            var mandateOnServer = JsonConvert.DeserializeObject <MandateDeserializationDto>(receivedMergePackage.Mandate);

            mandateOnServer.Should().NotBeNull();
            var checklistsOnServer = JsonConvert.DeserializeObject <ChecklistDeserializationDto[]>(receivedMergePackage.Checklists);

            checklistsOnServer.Should().NotBeNull();
            checklistsOnServer.Length.Should().Be(2);
        }
 /// <summary>
 /// load test data to cached
 /// </summary>
 /// <param name="path_file"></param>
 /// <param name="sheet_name"></param>
 /// <param name="test_data_type: TestPlan, TestSuite, Share"></param>
 public void load_test_data(string path_file, string sheet_name, string test_data_type)
 {
     try
     {
         TestDataType type = Utility.ParseEnum <TestDataType>(test_data_type);
         if (type == TestDataType.TestPlan)
         {
             TestDataHelper.LoadTestPlanData(path_file, sheet_name);
         }
         else if (type == TestDataType.TestSuite)
         {
             TestDataHelper.LoadTestSuiteData(path_file, sheet_name);
         }
         else if (type == TestDataType.Share)
         {
             TestDataHelper.LoadShareData(path_file, sheet_name);
         }
     }
     catch (Exception ex)
     {
         HandlingException(ex);
     }
 }
        public void CanSaveAndRetrieveItemFromCache()
        {
            //Create a new test user to save to the cache
            var user = TestDataHelper.CreateNewUser();

            //Add the cached object to our clean-up list
            _cachedObjects.Add(user.UserName);

            //Save the user to the cache
            _cacheService.Save(user.UserName, user);

            //Verify that the user is in the cache
            Assert.IsTrue(_cacheService.Exists(user.UserName));

            //Retrieve the object from the cache
            var userInCache = _cacheService.Get(user.UserName) as UserAccount;

            //Assert that the object isn't null
            Assert.IsNotNull(userInCache);

            //Assert that the object in the cache is the same instance as our existing object
            Assert.AreSame(user, userInCache);
        }
Esempio n. 36
0
        public async Task VehicleController_GetVehicleDetails_WhenVehicleExists_ShouldReturnOk()
        {
            // Arrange
            var vinReference = StringHelper.RandomString(6);

            _mockVehicleRepository
            .Setup(m => m.GetByVinAsync(It.IsAny <string>()))
            .ReturnsAsync(TestDataHelper.GetVehicle(vinReference))
            .Verifiable();

            // Act
            var vehiclesController = new VehiclesController(_mockVehicleRepository.Object, _mockLogger.Object);
            var result             = await vehiclesController.GetVehicleDetails(vinReference);

            var objResult = result as OkObjectResult;

            // Assert
            Assert.IsNotNull(objResult);
            var vehicleResponse = objResult.Value as VehicleModel;

            Assert.AreEqual(vinReference, vehicleResponse.VehicleNumber);
            _mockVehicleRepository.Verify(m => m.GetByVinAsync(It.IsAny <string>()), Times.Once);
        }
Esempio n. 37
0
        public void CopyRepository_DirDoestNotExists_DirCreatedAndFilesCopied()
        {
            // Arrange
            string targetPath    = Path.Combine(TestDataHelper.GetTestDataRepositoriesRootDirectory(), "newClonedApp");
            var    gitRepository = GetTestRepository("ttd", "hvem-er-hvem", "testUser");

            try
            {
                // Act
                gitRepository.CopyRepository(targetPath);
                int actualFileCount = Directory.GetFiles(targetPath, "*", SearchOption.AllDirectories).Length;

                // Assert
                int expectedFileCount = Directory.GetFiles(gitRepository.RepositoryDirectory, "*", SearchOption.AllDirectories).Length;

                Assert.True(Directory.Exists(targetPath));
                Assert.Equal(expectedFileCount, actualFileCount);
            }
            finally
            {
                Directory.Delete(targetPath, true);
            }
        }
        public async Task get_records_by_filter_with_a_given_filter_returns_the_expected_results()
        {
            // Arrange
            var expected = new List <TestTableEntity>
            {
                new TestTableEntity("John", "Smith")
                {
                    Age = 21, Email = "*****@*****.**"
                },
                new TestTableEntity("Jane", "Smith")
                {
                    Age = 28, Email = "*****@*****.**"
                }
            };

            await TestDataHelper.SetupRecords(_tableStorage);

            // Act
            var result = _tableStorage.GetRecordsByFilter(x => x.Age >= 21 && x.Age < 29);

            // Assert
            result.Should().BeEquivalentTo(expected, op => op.Excluding(o => o.Timestamp).Excluding(o => o.ETag).Excluding(o => o.SelectedMemberPath.EndsWith("CompiledRead")));
        }
Esempio n. 39
0
        public void CreatesTextDocument()
        {
            var dataObject = new[]
            {
                new DataObject
                {
                    Developer = "Valve Software",
                    Name      = "Dota 2",
                    Summary   = "Dota 2 is a complex game where you get sworn at\nin Russian all the time.",
                    ExtraData = "Hidden Stuff Here"
                },
                new DataObject
                {
                    Developer = "Valve Software",
                    Name      = "Team Fortress 2",
                    Summary   = "Known as \"America's #1 war-themed hat simulator\", this game lets you wear stupid items while killing people.",
                    ExtraData = "More Secrets"
                },
            };

            string text;

            using (var ms = new MemoryStream())
            {
                KvSerializer.Create(KvSerializationFormat.KeyValues1Text).Serialize(ms, dataObject, "test data");

                ms.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(ms))
                {
                    text = reader.ReadToEnd();
                }
            }

            var expected = TestDataHelper.ReadTextResource("Text.serialization_expected.vdf");

            Assert.That(text, Is.EqualTo(expected));
        }
Esempio n. 40
0
        public void SeresOrXmlSchema_ShouldSerializeToCSharp(string xsdResource, string modelName, string expectedJsonSchemaResource, string expectedCSharpResource)
        {
            SchemaKeywordCatalog.Add <InfoKeyword>();

            var org = "yabbin";
            var app = "hvem-er-hvem";

            Stream    xsdStream = TestDataHelper.LoadDataFromEmbeddedResource(xsdResource);
            XmlReader xmlReader = XmlReader.Create(xsdStream, new XmlReaderSettings {
                IgnoreWhitespace = true
            });

            // Compare generated JSON Schema
            XsdToJsonSchema xsdToJsonSchemaConverter = new XsdToJsonSchema(xmlReader);
            JsonSchema      jsonSchema         = xsdToJsonSchemaConverter.AsJsonSchema();
            var             expectedJsonSchema = TestDataHelper.LoadDataFromEmbeddedResourceAsJsonSchema(expectedJsonSchemaResource);

            jsonSchema.Should().BeEquivalentTo(expectedJsonSchema);

            // Compare generated C# classes
            ModelMetadata modelMetadata = GenerateModelMetadata(org, app, jsonSchema);

            string   classes       = GenerateCSharpClasses(modelMetadata);
            Assembly assembly      = Compiler.CompileToAssembly(classes);
            Type     type          = assembly.GetType(modelName);
            var      modelInstance = assembly.CreateInstance(type.FullName);

            string   expectedClasses       = TestDataHelper.LoadDataFromEmbeddedResourceAsString(expectedCSharpResource);
            Assembly expectedAssembly      = Compiler.CompileToAssembly(expectedClasses);
            Type     expectedType          = expectedAssembly.GetType(modelName);
            var      expectedModelInstance = expectedAssembly.CreateInstance(expectedType.FullName);

            expectedType.HasSameMetadataDefinitionAs(type);

            modelInstance.Should().BeEquivalentTo(expectedModelInstance);
            type.Should().BeDecoratedWith <XmlRootAttribute>();
        }
Esempio n. 41
0
        public async Task search_is_ordered_by_lastname_surname(string lastName, string firstName, string firstName2)
        {
            //arrange
            //tenancy
            var expectedTenancy = Fake.UniversalHousing.GenerateFakeTenancy();

            expectedTenancy.house_ref = expectedTenancy.house_ref;
            TestDataHelper.InsertTenancy(expectedTenancy, _db);
            //member 1
            var expectedMember = Fake.UniversalHousing.GenerateFakeMember();

            expectedMember.house_ref = expectedTenancy.house_ref;
            expectedMember.surname   = lastName;
            expectedMember.forename  = firstName;
            TestDataHelper.InsertMember(expectedMember, _db);
            //member 2
            var expectedMember2 = Fake.UniversalHousing.GenerateFakeMember();

            expectedMember2.house_ref = expectedTenancy.house_ref;
            expectedMember2.surname   = lastName;
            expectedMember2.forename  = firstName2;
            TestDataHelper.InsertMember(expectedMember2, _db);
            //act
            var response = await _classUnderTest.SearchTenanciesAsync(new SearchTenancyRequest
            {
                SearchTerm = lastName,
                PageSize   = 10,
                Page       = 1
            }, CancellationToken.None);

            //assert
            response.Should().NotBeNull();
            response.Results.Should().NotBeNullOrEmpty();
            response.TotalResultsCount.Should().Be(2);
            response.Results[0].PrimaryContactName.Should().Contain(firstName);
            response.Results[1].PrimaryContactName.Should().Contain(firstName2);
        }
Esempio n. 42
0
        public void ValidateDemoPatient()
        {
            var s = new StringReader(TestDataHelper.ReadTestData(@"TestPatient.xml"));

            var patient = new FhirXmlParser().Parse <Patient>(XmlReader.Create(s));

            ICollection <ValidationResult> results = new List <ValidationResult>();

            foreach (var contained in patient.Contained)
            {
                ((DomainResource)contained).Text = new Narrative()
                {
                    Div = "<wrong />"
                }
            }
            ;

            Assert.IsFalse(DotNetAttributeValidation.TryValidate(patient, results, true));
            Assert.IsTrue(results.Count > 0);

            results.Clear();
            foreach (DomainResource contained in patient.Contained)
            {
                contained.Text = null;
            }

            // Try again
            Assert.IsTrue(DotNetAttributeValidation.TryValidate(patient, results, true));

            patient.Identifier[0].System = "urn:oid:crap really not valid";

            results = new List <ValidationResult>();

            Assert.IsFalse(DotNetAttributeValidation.TryValidate(patient, results, true));
            Assert.IsTrue(results.Count > 0);
        }
    }
Esempio n. 43
0
        public async Task UploadSchemaFromXsd_OED_ModelsCreated()
        {
            // Arrange
            JsonSchemaKeywords.RegisterXsdKeywords();

            var org = "ttd";
            var sourceRepository = "empty-app";
            var developer        = "testUser";
            var targetRepository = Guid.NewGuid().ToString();

            await TestDataHelper.CopyRepositoryForTest(org, sourceRepository, developer, targetRepository);

            try
            {
                var altinnGitRepositoryFactory         = new AltinnGitRepositoryFactory(TestDataHelper.GetTestDataRepositoriesRootDirectory());
                ISchemaModelService schemaModelService = new SchemaModelService(altinnGitRepositoryFactory, TestDataHelper.LogFactory, TestDataHelper.ServiceRepositorySettings);
                var xsdStream         = TestDataHelper.LoadDataFromEmbeddedResource("Designer.Tests._TestData.Model.Xsd.OED.xsd");
                var schemaName        = "OED_M";
                var fileName          = $"{schemaName}.xsd";
                var relativeDirectory = "App/models";
                var relativeFilePath  = $"{relativeDirectory}/{fileName}";

                // Act
                var jsonSchema = await schemaModelService.BuildSchemaFromXsd(org, targetRepository, developer, fileName, xsdStream);

                // Assert
                var altinnAppGitRepository = altinnGitRepositoryFactory.GetAltinnAppGitRepository(org, targetRepository, developer);
                altinnAppGitRepository.FileExistsByRelativePath($"{relativeDirectory}/{schemaName}.metadata.json").Should().BeTrue();
                altinnAppGitRepository.FileExistsByRelativePath($"{relativeDirectory}/{schemaName}.schema.json").Should().BeTrue();
                altinnAppGitRepository.FileExistsByRelativePath($"{relativeDirectory}/{schemaName}.xsd").Should().BeTrue();
                altinnAppGitRepository.FileExistsByRelativePath($"{relativeDirectory}/{schemaName}.cs").Should().BeTrue();
            }
            finally
            {
                TestDataHelper.DeleteAppRepository(org, targetRepository, developer);
            }
        }
        public void CanUpdateItemInCache()
        {
            //Create a new test user to save to the cache
            var user = TestDataHelper.CreateNewUser();

            //Add the cached object to our clean-up list
            _cachedObjects.Add(user.UserName);

            //Save the user to the cache
            _cacheService.Save(user.UserName, user);

            //Verify that the user is in the cache
            Assert.IsTrue(_cacheService.Exists(user.UserName));

            //Clone the user's email address and save a copy for future comparison
            var oldUserEmail = user.EmailAddress.Clone() as string;

            //Create a new email address
            var newUserEmail = System.Guid.NewGuid().ToString();

            user.EmailAddress = newUserEmail;

            //Assert that the two emails aren't equal (reference checking, not Guid collisions)
            Assert.AreNotEqual(oldUserEmail, newUserEmail);

            //Update the user in the cache
            _cacheService.Save(user.UserName, user);

            //Retrieve the object from the cache
            var userInCache = _cacheService.Get(user.UserName) as UserAccount;

            //Assert that the object isn't null
            Assert.IsNotNull(userInCache);

            //Assert that the object in the cache is the same instance as our existing object
            Assert.AreNotEqual(oldUserEmail, userInCache.EmailAddress);
        }
Esempio n. 45
0
        private static RepositorySI GetServiceForTest(string developer, ISourceControl sourceControlMock = null)
        {
            HttpContext ctx = GetHttpContextForTestUser(developer);

            Mock <IHttpContextAccessor> httpContextAccessorMock = new Mock <IHttpContextAccessor>();

            httpContextAccessorMock.Setup(s => s.HttpContext).Returns(ctx);

            sourceControlMock ??= new ISourceControlMock();
            IOptions <ServiceRepositorySettings> repoSettings = Options.Create(new ServiceRepositorySettings());
            string unitTestFolder = Path.GetDirectoryName(new Uri(typeof(RepositorySITests).Assembly.Location).LocalPath);

            repoSettings.Value.RepositoryLocation = Path.Combine(unitTestFolder, "..", "..", "..", "_TestData", "Repositories") + Path.DirectorySeparatorChar;

            var altinnGitRepositoryFactory = new AltinnGitRepositoryFactory(TestDataHelper.GetTestDataRepositoriesRootDirectory());

            IOptions <GeneralSettings> generalSettings = Options.Create(
                new GeneralSettings()
            {
                TemplateLocation   = @"../../../../../../AppTemplates/AspNet",
                DeploymentLocation = @"../../../../../../AppTemplates/AspNet/deployment",
                AppLocation        = @"../../../../../../AppTemplates/AspNet/App"
            });

            RepositorySI service = new RepositorySI(
                repoSettings,
                generalSettings,
                new Mock <IDefaultFileFactory>().Object,
                httpContextAccessorMock.Object,
                new IGiteaMock(),
                sourceControlMock,
                new Mock <ILoggerFactory>().Object,
                new Mock <ILogger <RepositorySI> >().Object,
                altinnGitRepositoryFactory);

            return(service);
        }
Esempio n. 46
0
        public async Task CreateSchemaFromXsd_AppRepo_ShouldCreateModels()
        {
            // Arrange
            var org = "ttd";
            var sourceRepository = "empty-app";
            var developer        = "testUser";
            var targetRepository = Guid.NewGuid().ToString();

            await TestDataHelper.CopyRepositoryForTest(org, sourceRepository, developer, targetRepository);

            try
            {
                var altinnGitRepositoryFactory         = new AltinnGitRepositoryFactory(TestDataHelper.GetTestDataRepositoriesRootDirectory());
                ISchemaModelService schemaModelService = new SchemaModelService(altinnGitRepositoryFactory, TestDataHelper.LogFactory, TestDataHelper.ServiceRepositorySettings);
                var xsdStream = TestDataHelper.LoadDataFromEmbeddedResource("Designer.Tests._TestData.Model.Xsd.Kursdomene_HvemErHvem_M_2021-04-08_5742_34627_SERES.xsd");
                xsdStream.Seek(0, System.IO.SeekOrigin.Begin);
                var schemaName        = "Kursdomene_HvemErHvem_M_2021-04-08_5742_34627_SERES";
                var fileName          = $"{schemaName}.xsd";
                var relativeDirectory = "App/models";
                var relativeFilePath  = $"{relativeDirectory}/{fileName}";

                // Act
                await schemaModelService.CreateSchemaFromXsd(org, targetRepository, developer, relativeFilePath, xsdStream);

                // Assert
                var altinnAppGitRepository = altinnGitRepositoryFactory.GetAltinnAppGitRepository(org, targetRepository, developer);
                altinnAppGitRepository.FileExistsByRelativePath($"{relativeDirectory}/{schemaName}.metadata.json").Should().BeTrue();
                altinnAppGitRepository.FileExistsByRelativePath($"{relativeDirectory}/{schemaName}.schema.json").Should().BeTrue();
                altinnAppGitRepository.FileExistsByRelativePath($"{relativeDirectory}/{schemaName}.original.xsd").Should().BeTrue();
                altinnAppGitRepository.FileExistsByRelativePath($"{relativeDirectory}/{schemaName}.cs").Should().BeTrue();
            }
            finally
            {
                TestDataHelper.DeleteAppRepository(org, targetRepository, developer);
            }
        }
        public void EdgecaseRoundtrip()
        {
            string json     = TestDataHelper.ReadTestData("json-edge-cases.json");
            var    tempPath = Path.GetTempPath();

            var poco = FhirJsonParser.Parse <Resource>(json);

            Assert.IsNotNull(poco);
            var xml = FhirXmlSerializer.SerializeToString(poco);

            Assert.IsNotNull(xml);
            File.WriteAllText(Path.Combine(tempPath, "edgecase.xml"), xml);

            poco = FhirXmlParser.Parse <Resource>(xml);
            Assert.IsNotNull(poco);
            var json2 = FhirJsonSerializer.SerializeToString(poco);

            Assert.IsNotNull(json2);
            File.WriteAllText(Path.Combine(tempPath, "edgecase.json"), json2);

            List <string> errors = new List <string>();

            JsonAssert.AreSame(json, json2);
        }
        public void Select_With_Keyspace_Defined()
        {
            string query = null;

            object[] parameters = null;
            var      session    = GetSession((q, v) =>
            {
                query      = q;
                parameters = v;
            }, TestDataHelper.CreateMultipleValuesRowSet(new[] { "id" }, new[] { 5000 }));
            var map = new Map <AllTypesEntity>()
                      .ExplicitColumns()
                      .Column(t => t.DoubleValue, cm => cm.WithName("val"))
                      .Column(t => t.IntValue, cm => cm.WithName("id"))
                      .PartitionKey(t => t.UuidValue)
                      .CaseSensitive()
                      .KeyspaceName("ks1")
                      .TableName("tbl1");
            var table = GetTable <AllTypesEntity>(session, map);

            (from t in table where t.IntValue == 199 select new { Age = t.IntValue }).Execute();
            Assert.AreEqual(@"SELECT ""id"" FROM ""ks1"".""tbl1"" WHERE ""id"" = ?", query);
            CollectionAssert.AreEqual(parameters, new object[] { 199 });
        }
        public void Select_Project_To_New_Type()
        {
            string query = null;

            object[] parameters = null;
            var      session    = GetSession((q, v) =>
            {
                query      = q;
                parameters = v;
            }, TestDataHelper.CreateMultipleValuesRowSet(new[] { "val", "id" }, new[] { 1, 200 }));
            var map = new Map <AllTypesEntity>()
                      .ExplicitColumns()
                      .Column(t => t.DoubleValue, cm => cm.WithName("val"))
                      .Column(t => t.IntValue, cm => cm.WithName("id"))
                      .PartitionKey(t => t.UuidValue)
                      .TableName("tbl1");
            var table = GetTable <AllTypesEntity>(session, map);

            (from t in table where t.IntValue == 200 select new PlainUser {
                Age = t.IntValue
            }).Execute();
            Assert.AreEqual("SELECT id FROM tbl1 WHERE id = ?", query);
            CollectionAssert.AreEqual(parameters, new object[] { 200 });
        }
        public async Task ShouldUpdateCarePackageDetails()
        {
            var package = _generator.CreateCarePackage();
            var details = _generator.CreateCarePackageDetails(package, 5, PackageDetailType.AdditionalNeed);

            var request = new CarePackageBrokerageCreationRequest
            {
                CoreCost   = 123.45m,
                StartDate  = DateTimeOffset.UtcNow.Date.AddDays(-500),
                SupplierId = 2,
                Details    = details.ToRequest().ToList()
            };

            // Imitate remove, create and update at once
            request.Details.RemoveAt(1);
            request.Details.RemoveAt(2);
            request.Details.Add(TestDataHelper.CreateCarePackageDetailDomainList(1, PackageDetailType.AdditionalNeed).First().ToRequest());

            foreach (var detail in request.Details)
            {
                detail.Cost     += 1.0m;
                detail.StartDate = detail.StartDate?.AddDays(-10) ?? DateTimeOffset.UtcNow.Date.AddDays(-10);
                detail.EndDate   = detail.EndDate?.AddDays(-10) ?? DateTimeOffset.UtcNow.Date.AddDays(-10);
            }

            var response = await _fixture.RestClient
                           .PutAsync <object>($"api/v1/care-packages/{package.Id}/details", request);

            package = _fixture.DatabaseContext.CarePackages
                      .Include(p => p.Details)
                      .First(p => p.Id == package.Id);

            response.Message.StatusCode.Should().Be(HttpStatusCode.OK);

            VerifyPackageDetails(package, request);
        }
        public void Linq_CqlQuery_Automatically_Pages()
        {
            const int      pageLength  = 100;
            var            rs          = TestDataHelper.GetSingleColumnRowSet("int_val", Enumerable.Repeat(1, pageLength).ToArray());
            BoundStatement stmt        = null;
            var            sessionMock = new Mock <ISession>(MockBehavior.Strict);

            sessionMock.Setup(s => s.Keyspace).Returns <string>(null);
            sessionMock
            .Setup(s => s.ExecuteAsync(It.IsAny <BoundStatement>()))
            .Returns(TestHelper.DelayedTask(rs))
            .Callback <IStatement>(s => stmt = (BoundStatement)s)
            .Verifiable();
            sessionMock.Setup(s => s.PrepareAsync(It.IsAny <string>())).Returns(TaskHelper.ToTask(GetPrepared("Mock query")));
            sessionMock.Setup(s => s.BinaryProtocolVersion).Returns(2);
            rs.AutoPage    = true;
            rs.PagingState = new byte[] { 0, 0, 0 };
            var counter = 0;

            rs.SetFetchNextPageHandler(state =>
            {
                var rs2 = TestDataHelper.GetSingleColumnRowSet("int_val", Enumerable.Repeat(1, pageLength).ToArray());
                if (++counter < 2)
                {
                    rs2.PagingState = new byte[] { 0, 0, (byte)counter };
                }
                return(Task.FromResult(rs2));
            }, int.MaxValue);
            var table = new Table <int>(sessionMock.Object);
            IEnumerable <int> results = table.Execute();

            Assert.True(stmt.AutoPage);
            Assert.AreEqual(0, counter);
            Assert.AreEqual(pageLength * 3, results.Count());
            Assert.AreEqual(2, counter);
        }
 public void SetUp()
 {
     savedEmail = new Email {Id = 1};
     loginRepository = new LoginRepository(ConfigurationFactory.SessionFactory.OpenSession());
     testDataHelper = new TestDataHelper();
 }
Esempio n. 53
0
 public void ShouldAuthenticateUser()
 {
     testDataHelper = new TestDataHelper();
     var isAuthenticated = HttpHelper.Get<bool>(string.Format("{0}?userName={1}&password={2}", baseUri, "*****@*****.**", "Password"));
     Assert.IsTrue(isAuthenticated);
 }
 public void SetUp()
 {
     testDataHelper = new TestDataHelper();
     contactUsRepository = new ContactUsRepository();
     savedContactUs = testDataHelper.CreateContactUs(new ContactUs {Name = "test",Email = "test",Comments = "test"});
 }
Esempio n. 55
0
 public void ShouldThrowExceptionWhenMailIsInvalid()
 {
     testDataHelper = new TestDataHelper();
     var response = HttpHelper.DoHttpGet(string.Format("{0}?email={1}", "http://localhost/kallivayalilService/KallivayalilService.svc/Login/ForgotPassword","*****@*****.**"));
     Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
 }