public void ValidateGoodPropertyWithOtherBadData()
        {
            MockData d = new MockData()
            {
                Name = "Elizabeth",
                Email = "not.a.real.email",
                Age = 45,
                Website = null
            };

            Assert.IsNull(ValidationHelper.ValidateProperty(d, "Age"));
        }
        public void ValidateBadPropertyWithOtherBadData()
        {
            MockData d = new MockData()
            {
                Name = "Elizabeth",
                Email = "not.a.real.email",
                Age = 45,
                Website = null
            };

            Assert.IsTrue(ValidationHelper.ValidateProperty(d, "Name").Count > 0);
        }
        public void ValidateBadDataObject()
        {
            MockData d = new MockData()
            {
                Name = "Elizabeth",
                Email = "not.a.real.email",
                Age = -1,
                Website = null
            };

            Assert.IsTrue(ValidationHelper.ValidateDataObject(d).Count > 0);
        }
        public void ValidateGoodDataObject()
        {
            MockData d = new MockData()
            {
                Name = "Bob",
                Email = "*****@*****.**",
                Age = 40,
                Website = "http://net.com/"
            };

            Assert.IsNull(ValidationHelper.ValidateDataObject(d));
        }
        public void DeepCopyA()
        {
            var dorig = new MockData();

            var d = dorig.Clone();

            dorig = null;

            Assert.AreEqual(default(string), d.Name);
            Assert.AreEqual(default(int), d.Age);
            Assert.AreEqual(default(string), d.Email);
            Assert.AreEqual(default(string), d.Website);
        }
        public void DeepCopyB()
        {
            var dorig =  new MockData()
            {
                Name = "Bob",
                Age = 25,
                Email = "*****@*****.**",
                Website = "http://doubleyouww.com"
            };

            var d = dorig.Clone();

            dorig = null;

            Assert.AreEqual("Bob", d.Name);
            Assert.AreEqual(25, d.Age);
            Assert.AreEqual("*****@*****.**", d.Email);
            Assert.AreEqual("http://doubleyouww.com", d.Website);
        }
        public void Test_Deserialize_Stream_To_Expando_Object([Values(false, true)] bool leaveStreamOpen)
        {
            var stream   = MockData.GetEmployeeAsStream(DataSource.Configuration.Encoding);
            var employee = DataSource.Deserialize <ExpandoObject>(stream, 1024, leaveStreamOpen);

            if (employee is IDictionary <string, object> dictionary)
            {
                EnsureFirstNameAndLastNameMatchMockData(dictionary["FirstName"].ToString(), dictionary["LastName"].ToString());
            }
            else
            {
                Assert.Fail("Object did not deserialize to expected type");
            }
            if (leaveStreamOpen)
            {
                EnsureStreamIsNotDisposeAndIsAtEndOfStream(stream);
            }
            else
            {
                EnsureStreamIsDispose(stream);
            }
        }
예제 #8
0
        public static async Task PostFourthMockMapping(MockData mockData)
        {
            Logger.Info("Sending /* mapping with redirection to the server mockup via POST request");

            var mockRequestData4 = MockBuilder.Setup()
                                   .RequestWith(
                RequestBuilder.Setup()
                .WithPath(mockData.Path)
                .UsingPut()
                .Build()
                )
                                   .RespondWith(
                ResponseBuilder.Setup()
                .WithStatusCode(mockData.StatusCode)
                .WithHeader(mockData.RedirectPath)
                .WithDelay(mockData.Delay)
                .Build()
                )
                                   .Build();

            await WireMockApi.PostMockMapping(mockRequestData4);
        }
        public async Task ActionResultPost_ShouldReturnCreateStatus_WithASignleCustomer()
        {
            // Arrange
            List <Customer> customerList = new List <Customer>();
            Customer        mockCustomer = MockData.GetOneCustomerMockData();

            _mockContext.Setup(x => x.InsertOneAsync(It.IsAny <Customer>()))
            .Callback((Customer customer) =>
            {
                customerList.Add(customer);
            });

            // Act
            var result = await _customerController.Post(mockCustomer);

            // Assert
            var viewResult = Assert.IsType <ActionResult <Customer> >(result);
            var model      = Assert.IsAssignableFrom <CreatedAtRouteResult>(viewResult.Result as CreatedAtRouteResult);

            Assert.NotNull(model.Value);
            Assert.Equal(201, model.StatusCode);
        }
예제 #10
0
        public static async Task PostFirstMockMapping(MockData mockData)
        {
            Logger.Info("Sending /plaintext/mapping1 mapping to the server mockup via POST request");

            var mockRequestData = MockBuilder.Setup()
                                  .RequestWith(
                RequestBuilder.Setup()
                .WithPath(mockData.Path)
                .UsingGet()
                .Build()
                )
                                  .RespondWith(
                ResponseBuilder.Setup()
                .WithStatusCode(mockData.StatusCode)
                .WithBody(mockData.Body)
                .WithHeader(mockData.Headers)
                .Build()
                )
                                  .Build();

            await WireMockApi.PostMockMapping(mockRequestData);
        }
        public void LoginNoCustomerInUserObject()
        {
            //For token, email and roles are required
            var mockData = new MockData
            {
                Users = new List <User>
                {
                    new User {
                        id    = 1, username = "******", password = "******", customer_code = "cust", email = "email",
                        Roles = new List <Role>
                        {
                            new Role {
                                id = Role.User
                            }
                        }
                    }
                },
                Customers = new List <Customer>
                {
                    new Customer {
                        code = "cust"
                    }
                }
            };

            unitOfWork.Data = mockData;
            var result = controller.Login("username", "password");

            Assert.IsNotNull(result);
            var user = mockData.Users.FirstOrDefault();

            Assert.IsNotNull(user);
            Assert.IsNotNull(user.Customer);
            Assert.IsNotNull(user.token);
            Assert.IsNotNull(user.lastLogin);
            Assert.IsTrue(unitOfWork.Saved);
            Assert.IsNotNull(user.Sessions);
            Assert.AreEqual(1, user.Sessions.Count);
        }
        public void Test_Deserialize_Stream_To_Typed_Object_2([Values(false, true)] bool leaveStreamOpen)
        {
            var stream   = MockData.GetEmployeeAsStream(DataSource.Configuration.Encoding);
            var employee = DataSource.Deserialize(stream, typeof(Employee), 1024, leaveStreamOpen);

            if (employee is Employee dyn)
            {
                EnsureFirstNameAndLastNameMatchMockData(dyn.FirstName, dyn.LastName);
            }
            else
            {
                Assert.Fail("Object did not deserialize to expected type");
            }
            if (leaveStreamOpen)
            {
                EnsureStreamIsNotDisposeAndIsAtEndOfStream(stream);
            }
            else
            {
                EnsureStreamIsDispose(stream);
            }
        }
        public void Test_Deserialize_Stream_To_Expando_Object_List_2([Values(false, true)] bool leaveStreamOpen)
        {
            var stream    = MockData.GetEmployeeListAsStream(DataSource.Configuration.Encoding);
            var employees = DataSource.Deserialize(stream, typeof(List <ExpandoObject>), 1024, leaveStreamOpen);

            if (employees is List <ExpandoObject> list)
            {
                EnsureDynamicObjectMatchMockData(list.First());
            }
            else
            {
                Assert.Fail("Deserialize Failed");
            }
            if (leaveStreamOpen)
            {
                EnsureStreamIsNotDisposeAndIsAtEndOfStream(stream);
            }
            else
            {
                EnsureStreamIsDispose(stream);
            }
        }
        public async Task Create_ShouldNotSavedNewCustomer_WhenCustomerIsNull()
        {
            //Arrange
            List <Customer>       customerList = new List <Customer>();
            IQueryable <Customer> customers    = new List <Customer>().AsQueryable();
            Customer mockCustomer = MockData.GetOneCustomerMockData();

            _mockContext.Setup(x => x.InsertOneAsync(It.IsAny <Customer>()))
            .Callback((Customer customer) =>
            {
                if (customer != null)
                {
                    customerList.Add(customer);
                }
            });

            //Act
            await _customerService.Create(null);

            //Assert
            Assert.Empty(customerList);
        }
예제 #15
0
        public void TestCannotQueryInAnotherClass()
        {
            var lst = MockData.GetList();

            Assert.IsNotNull(lst);
            Assert.IsTrue(lst.Count > 0);
            string errorMessage = null;
            object din          = null;

            try
            {
                din = AnotherClass.QueryList(lst, 3);
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            // you can query when using another class, same project
            Assert.IsNull(errorMessage);
            Assert.IsNotNull(din);
        }
        public async Task GetAllArticles_WhenCalled_Returns_AllArticles()
        {
            articleRepositoryMock.Setup(x => x.GetAllArticles()).Returns(MockData.TestArticlesMock());

            IEnumerable <Article> articles = await articleService.GetAllArticles();

            articles.Count().Should().Be(2);

            Article firstArticle = articles.First();

            firstArticle.Id.Should().Be(1);
            firstArticle.Title.Should().Be("Article Test 1");
            firstArticle.Body.Should().Be("Article Main Body");
            firstArticle.Author.Should().Be("Joe Bloggs");

            Article secondArticle = articles.Last();

            secondArticle.Id.Should().Be(2);
            secondArticle.Title.Should().Be("Article Test 2");
            secondArticle.Body.Should().Be("Article Main Body");
            secondArticle.Author.Should().Be("Joe Bloggs");
        }
예제 #17
0
        public void TestSeekFromAnotherProject()
        {
            var lst = MockData.GetList();

            Assert.IsNotNull(lst);
            Assert.IsTrue(lst.Count > 0);
            string errorMessage = null;
            object din          = null;

            try
            {
                din = lst.GetValueFromDynamicList("Id", "Name", "3");
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            Assert.IsNull(errorMessage);
            Assert.IsNotNull(din);
            Trace.Write(din.ToString());
        }
예제 #18
0
        public async Task MoveStep_WithCorrectModel_MustChangeCurrentFlag()
        {
            //Arrange
            var stateManager      = new MockState().MockStateManager();
            var instance          = MockData.GetFlowInstances().FirstOrDefault();
            var flowManager       = new ManagerFactory().GetFlowManager(stateManager);
            var flowReportManager = new ManagerFactory().GetFlowReportManager(stateManager);
            var existTransitions  = await flowReportManager.GetInstanceTransitionsAsync(instance.Id);

            var targetTransition = existTransitions.Result.FirstOrDefault();
            var preSteps         = await flowReportManager.GetInstanceStepsAsync(instance.Id);

            var preStep = preSteps.Result.FirstOrDefault(x => x.IsCurrent);

            var moveModel = new MoveModel()
            {
                IdentityId   = "1",
                InstanceId   = instance.Id,
                Payload      = string.Empty,
                TransitionId = targetTransition.Id,
                Comment      = "Sure, It's ok.",
            };
            //Act
            var act = await flowManager.MoveAsync(moveModel);

            var steps = await flowReportManager.GetInstanceStepsAsync(instance.Id);

            var currentStep    = steps.Result.FirstOrDefault(x => x.IsCurrent);
            var updatedPreStep = steps.Result.FirstOrDefault(x => x.Id.Equals(preStep.Id));

            //Assert
            LogTestInfo(moveModel, act);
            Assert.True(act.Succeeded);
            Assert.NotNull(act.Result);
            Assert.True(currentStep.IsCurrent);
            Assert.False(updatedPreStep.IsCurrent);
            Assert.Equal(moveModel.TransitionId, currentStep.TransitionId);
        }
        public async Task GetApiResponseAsync_Should_Return_ApiResponse_With_Success_And_DeserializedObject_If_HttpResponseMessage_IsSuccessStatusCode_True()
        {
            var podcast = new SampleData()
            {
                Owner = "Fatma", SampleCount = 5, CreateDate = TimeProvider.Current.UtcNow
            };

            string stringContent = JsonConvert.SerializeObject(podcast);

            var httpMessageHandler = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            httpMessageHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK, Content = new StringContent(stringContent)
            })
            .Verifiable();

            HttpClient httpClient    = MockData.GetMockHttpClient(httpMessageHandler);
            var        restApiClient = new RestApiClient(httpClient);

            IApiResponse <SampleData> apiResponse = await restApiClient.GetApiResponseAsync <SampleData>("pull_request");

            httpMessageHandler.Protected()
            .Verify("SendAsync", Times.Once(),
                    ItExpr.Is <HttpRequestMessage>(
                        message => message.Method == HttpMethod.Get && message.RequestUri.ToString().Contains("pull_request")),
                    ItExpr.IsAny <CancellationToken>());

            Assert.Equal(HttpStatusCode.OK, apiResponse.HttpStatusCode);
            Assert.False(apiResponse.Error);
            Assert.NotNull(apiResponse.Model);
            Assert.Null(apiResponse.Message);
            Assert.Equal(podcast.Owner, apiResponse.Model.Owner);
            Assert.Equal(podcast.SampleCount, apiResponse.Model.SampleCount);
            Assert.Equal(podcast.CreateDate, apiResponse.Model.CreateDate);
        }
        public async Task GetApiResponseAsync_Should_Return_ApiResponse_With_StatusCode_And_Headers_And_UrlPath_Regardless_Of_StatusCode_Success_Or_Not(
            HttpStatusCode httpStatusCode, string headerParams, string path)
        {
            var podcast = new SampleData()
            {
                Owner = "Yiğit", SampleCount = 5, CreateDate = TimeProvider.Current.UtcNow
            };

            IDictionary <string, string> headerParameters = headerParams.ToHeaderParameters();

            string stringContent = JsonConvert.SerializeObject(podcast);

            var httpMessageHandler = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            httpMessageHandler.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = httpStatusCode, Content = new StringContent(stringContent)
            })
            .Verifiable();

            HttpClient httpClient    = MockData.GetMockHttpClient(httpMessageHandler);
            var        restApiClient = new RestApiClient(httpClient);

            IApiResponse <SampleData> apiResponse = await restApiClient.GetApiResponseAsync <SampleData>(path, null, headerParameters);

            httpMessageHandler.Protected()
            .Verify("SendAsync", Times.Once(),
                    ItExpr.Is <HttpRequestMessage>(message => message.Method == HttpMethod.Get && message.RequestUri.ToString().Contains(path)),
                    ItExpr.IsAny <CancellationToken>());

            Assert.Equal(httpStatusCode, apiResponse.HttpStatusCode);

            Assert.Contains(headerParameters, pair => apiResponse.Headers.All(valuePair => valuePair.Key == pair.Key && valuePair.Value == pair.Value));

            Assert.Equal(path, apiResponse.UrlPath);
        }
        public void GetUserPermissions()
        {
            var mockData = new MockData
            {
                Users = new List <User>
                {
                    new User {
                        id    = 1, username = "******", password = "******", customer_code = "cust", email = "email",
                        Roles = new List <Role>
                        {
                            new Role {
                                id = Role.User
                            }
                        },
                        Customer = new Customer {
                            code = "cust"
                        },
                        Permissions = new List <Permission>
                        {
                            new Permission
                            {
                                id = (int)PermissionId.ViewAccountDetails
                            }
                        }
                    }
                }
            };

            unitOfWork.Data = mockData;

            var permissions = controller.GetUserPermissions(mockData.Users[0]);

            Assert.AreEqual(1, permissions.Count);

            cache.Set("permissions_1", new List <Permission>(), null);
            permissions = controller.GetUserPermissions(mockData.Users[0]);
            Assert.AreEqual(0, permissions.Count);
        }
예제 #22
0
        public void GetPlayersTotalStatsWhileInTeam_ShouldWork_VerifyReturnData(int teamId, int?expected)
        {
            //Testing behaviour by comparing results
            //when a property in playerProfile is null, or has value.

            var playerStats = new MockData().PlayerProfile.ExtractPlayerStats();

            var actual = PlayerStats.GetPlayersTotalStatsWhileInTeam(teamId, playerStats);

            double?expectedDouble = (expected == null) ? null : (double?)1;

            Assert.Equal(expected, actual.GamesPlayed);
            Assert.Equal(expected, actual.GamesStarted);
            Assert.Equal(expected, actual.MinutesPlayed);

            Assert.Equal(expected, actual.FieldGoalsMade);
            Assert.Equal(expected, actual.FieldGoalsAttempted);
            Assert.Equal(expectedDouble, actual.FieldGoalsPercentage);

            Assert.Equal(expected, actual.ThreePointFieldGoalsMade);
            Assert.Equal(expected, actual.ThreePointFieldGoalsAttempted);
            Assert.Equal(expectedDouble, actual.ThreePointsFieldGoalPercentage);

            Assert.Equal(expected, actual.FreeThrowsMade);
            Assert.Equal(expected, actual.FreeThrowsAttempted);
            Assert.Equal(expectedDouble, actual.FreeThrowPercentage);

            Assert.Equal(expected, actual.OffensiveRebounds);
            Assert.Equal(expected, actual.DefensiveRebounds);
            Assert.Equal(expected, actual.Rebounds);

            Assert.Equal(expected, actual.Points);
            Assert.Equal(expected, actual.Assists);
            Assert.Equal(expected, actual.Steals);
            Assert.Equal(expected, actual.Blocks);
            Assert.Equal(expected, actual.Turnover);
            Assert.Equal(expected, actual.PersonalFouls);
        }
예제 #23
0
        public static void ConfigureMockContext(IServiceCollection services)
        {
            // Create a new service provider.
            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkInMemoryDatabase()
                                  .BuildServiceProvider();

            services.AddDbContext <SqlContext>(options =>
            {
                options.UseInMemoryDatabase("TestStartupTesting");
                options.EnableSensitiveDataLogging();
                options.UseInternalServiceProvider(serviceProvider);
            });

            var sp = services.BuildServiceProvider();

            using (var scope = sp.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetRequiredService <SqlContext>();
                var logger         = scopedServices
                                     .GetRequiredService <ILogger <MockContext> >();

                // Ensure the database is created.
                db.Database.EnsureCreated();

                try
                {
                    // Seed the database with test data.
                    MockData.SeedTestData(db);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "An error occurred seeding the " +
                                    $"database with test messages. Error: {ex.Message}");
                }
            }
        }
        public async Task <SprintProgressVm> SetSprintProgressVm(IJSRuntime jsRuntime, string uri)
        {
            _jsRuntime = jsRuntime;
            _sprintIterationProcessor = new SprintIterationProcessor();
            _workItemProcessor        = new WorkItemProcessor();
            SprintProgressDto sprintProgressDto;

            if (uri.Contains("localhost"))
            {
                sprintProgressDto = MockData.GetSprintProgressDtoTest();
            }
            else
            {
                sprintProgressDto = await GetSprintProgressDtoLive();
            }

            var sprintProgressVm = GetSprintProgressVm(sprintProgressDto);

            //do not delete the following DEBUG line!
            //sprintProgressVm.DebugString = JsonConvert.SerializeObject(sprintProgressDto, Formatting.Indented);

            return(sprintProgressVm);
        }
예제 #25
0
        private static void LinqCSV()
        {
            MockData MockData = new MockData();
            List <RegionForTaxesEntity> RegionForTaxesEntityList = MockData.RegionForTaxesEntityList;
            List <TaxRateEntity>        TaxRateEntityList        = MockData.TaxRateEntityList;
            List <TaxTreatmentEntity>   TaxTreatmentEntityList   = MockData.TaxTreatmentEntityList;

            foreach (var e in RegionForTaxesEntityList)
            {
                Console.WriteLine($"{e.Id} {e.Name} {e.Legislation} {e.IsTheMainRegion} {e.UseFromTaxes} {e.UseMainTaxes}");
            }
            Console.WriteLine("------------\n");
            foreach (var e in TaxRateEntityList)
            {
                Console.WriteLine($"{e.Id} {e.Legislation} {e.Name} {e.RegionForTaxes} {e.TaxTreatment} {e.TaxItemType} {e.TaxCode} {e.Rate} {e.RegionForTaxesId} {e.TaxTreatmentId} {e.TaxItemTypeId} {e.TaxCodeId}");
            }
            Console.WriteLine("------------\n");
            foreach (var e in TaxTreatmentEntityList)
            {
                Console.WriteLine($"{e.Id} {e.Legislation} {e.TaxTreatment} {e.RegionForTaxes} {e.UseFromTaxes} {e.RegionForTaxesId}");
            }
            Console.WriteLine("------------\n");
        }
예제 #26
0
        public void ParseInputData_AddressWayNumberEquals0AndSkipResultCode1_ReturnNull()
        {
            Address   address   = MockData.SetIncorrectWayNumberAddress();
            Person    person    = MockData.SetCorrectPerson();
            InputData inputData = new InputData()
            {
                AddressData = address, PersonData = person
            };

            RulesValidator <InputData> businessRulesValidator = new RulesValidator <InputData>(inputData);
            AddressRules <InputData>   addressRules           = new AddressRules <InputData>();
            PersonRules <InputData>    personRules            = new PersonRules <InputData>();

            List <int> rulesToSkip = new List <int>();

            rulesToSkip.Add(1);

            businessRulesValidator.AddRules(addressRules.Rules);
            businessRulesValidator.AddRules(personRules.Rules);
            ValidationError result = businessRulesValidator.GetValidationError(rulesToSkip);

            Assert.IsNull(result);
        }
예제 #27
0
        public void ShouldAuthenticateAUserByMatricula()
        {
            // configuramos el test llamando los repositorios, controladores o servicios a usar
            var userService = new Mock <IUserService>();
            var unitOfWork  = new Mock <IUnitOfWork>();
            var users       = MockData.GetFakeUsers();

            unitOfWork.Setup(x => x.UserRepository.GetAll()).Returns(users);

            // configuramos lo valores a ser retornados por el test
            var testUser          = users.First();
            var authenticationDto = new AuthenticationDTO();

            authenticationDto.EmailOrMatricula = testUser.Matricula;
            authenticationDto.Password         = testUser.Password;
            userService.Setup(x => x.Authenticate(authenticationDto)).Returns(users.First());

            // verifcamos que el retorno de datos sea lo configurado en el test
            var controller = new AuthenticationController(userService.Object);
            var result     = controller.Authentication(authenticationDto);

            Assert.AreEqual(testUser, result);
        }
        public async Task ActionResultPut_ShouldReturOKStatus_WithUpdatedCustomer()
        {
            // Arrange
            List <Customer> customerList = new List <Customer>();
            Customer        mockCustomer = MockData.GetOneCustomerMockData();

            _mockContext.Setup(x => x.FindByIdAsync(mockCustomer.Id)).ReturnsAsync(mockCustomer);
            _mockContext.Setup(x => x.ReplaceOne(It.IsAny <Customer>()))
            .Callback((Customer customer) =>
            {
                customerList.Add(customer);
            });

            // Act
            var result = await _customerController.Put(mockCustomer);

            // Assert
            var viewResult = Assert.IsType <ActionResult <Customer> >(result);
            var model      = Assert.IsAssignableFrom <OkObjectResult>(viewResult.Result as OkObjectResult);

            Assert.NotNull(model.Value);
            Assert.Equal(200, model.StatusCode);
        }
예제 #29
0
        public static async Task PostSecondMockMapping(MockData mockData)
        {
            Logger.Info("Sending /jsontext/mapping2 mapping with params to the server mockup via POST request");

            var mockRequestData2 = MockBuilder.Setup()
                                   .RequestWith(
                RequestBuilder.Setup()
                .WithPath(mockData.Path)
                .WithParam(mockData.Param, mockData.Pattern)
                .UsingGet()
                .Build()
                )
                                   .RespondWith(
                ResponseBuilder.Setup()
                .WithStatusCode(mockData.StatusCode)
                .WithBody(mockData.Body)
                .WithHeader(mockData.Headers)
                .Build()
                )
                                   .Build();

            await WireMockApi.PostMockMapping(mockRequestData2);
        }
예제 #30
0
        public void InstanceSerializeTest()
        {
            DynamicEntity entity = MockData.CreateEntityAndChildEntity();

            DEEntityInstanceBase instance = entity.CreateInstance();

            string json = JSONSerializerExecute.Serialize(instance);

            instance.Fields.ForEach(f =>
            {
                if (f.Definition.FieldType == FieldTypeEnum.Collection)
                {
                    foreach (var item in f.Definition.ReferenceEntity.Fields)
                    {
                        Assert.IsTrue(json.Contains(item.Name));
                    }
                }
                else
                {
                    Assert.IsTrue(json.Contains(f.Definition.Name));
                }
            });
        }
        public async Task Init()
        {
            var data      = new MockData();
            var container = GetMockContainer(data);

            data.StoredData.Clear();

            container.Service.Init();

            var result = container.Service.GetStatistics("TestDevice1").ToArray();

            Assert.AreEqual(1, result.Length);
            Assert.AreEqual(21.5, result[0].Data);

            data.AllSubDevices[0].Value = 22.5;

            await Task.Delay(800);

            result = container.Service.GetStatistics("TestDevice1").ToArray();

            Assert.AreEqual(2, result.Length);
            Assert.AreEqual(22.5, result[1].Data);
        }
예제 #32
0
        public void GetString_must_return_personMockData()
        {
            string key = "personList";

            provider.Delete(key);

            var persons = MockData.GetPersonsMock();

            var timeOut = new TimeSpan(0, 0, 15);

            bool actual = provider.Add(key, persons, timeOut);

            actual.Should().BeTrue();

            var redisPersons = provider.GetString <List <Person> >(key);

            foreach (var person in persons)
            {
                bool exist = redisPersons.FirstOrDefault(x => x.Id == person.Id) != null;

                exist.Should().BeTrue();
            }
        }
예제 #33
0
        public void GetAccount_GetAccountsbyAccountName_Succeed()
        {
            AccountsController controller = new AccountsController(mockAccountService.Object, mockWebAnalyticsProviderService.Object);

            this.SetupControllerTests(controller, "http://localhost/STCRMService/api/accounts/account1", HttpMethod.Get);

            var mockResponse = mockRepository.Create <GetAccountResponse>();

            GetAccountResponse response = mockRepository.Create <GetAccountResponse>().Object;

            response.AccountViewModel = MockData.CreateMockList <AccountViewModel>(mockRepository).Select(c => c.Object).FirstOrDefault();

            mockAccountService.Setup(c => c.GetAccountByName(It.IsAny <GetAccountNameRequest>())).Returns(response);

            var httpResponseMessage = controller.GetAccountByName(SAMPLE_ACCOUNT_NAME);
            var accountResponse     = httpResponseMessage.Content.ReadAsAsync <GetAccountResponse>().ContinueWith(
                t => { return(t.Result); }).Result;

            mockRepository.VerifyAll();
            //Assert.AreEqual("Account1", accountResponse.AccountViewModel.AccountName);
            Assert.AreEqual(httpResponseMessage.StatusCode, HttpStatusCode.OK);
            Assert.AreEqual(accountResponse.Exception, null);
        }
예제 #34
0
        protected override async Task SaveAsync(ApiChangeAction operation, object entity, bool commit = true)
        {
            if (operation == ApiChangeAction.Insert)
            {
                var policy = entity as Policy;
                policy.PolicyId = MockData.Policies.Max(p => p.PolicyId) + 1;

                MockData.AddRelatedData(policy);
                MockData.Policies.Add(policy);
            }
            else if (operation == ApiChangeAction.Update)
            {
                var newPolicy = entity as Policy;
                var oldPolicy = MockData.Policies
                                .First(p => p.PolicyId == newPolicy.PolicyId);

                MockData.AddRelatedData(newPolicy);
                MockData.Policies.Add(newPolicy);
                MockData.Policies.Remove(oldPolicy);
            }
            else if (operation == ApiChangeAction.Delete)
            {
                var policy = entity as Policy;
                MockData.Policies.Remove(policy);

                var policyCoverages = MockData.PolicyCoverages
                                      .Where(pc => pc.PolicyId == policy.PolicyId)
                                      .ToList();

                for (var i = 0; i < policyCoverages.Count; i++)
                {
                    MockData.PolicyCoverages.Remove(policyCoverages[i]);
                }
            }

            await Task.FromResult(0);
        }
예제 #35
0
        public async Task Updates()
        {
            var data = new MockData()
            {
                HasUpdates = true
            };
            var container = GetMockContainer(data);

            await container.Service.InitAsync(data.Configuration);

            var dateTime = DateTime.Now;

            await Task.Delay(1500);

            var result = container.Service.GetUpdatedDevices(dateTime);

            Assert.AreEqual(4, result.Length);

            var airDevice           = result.First(d => d.Id == "Weather_Air_Device") as WeatherAirDevice;
            var roadDevice          = result.First(d => d.Id == "Weather_Road_Device") as WeatherRoadDevice;
            var precipitationDevice = result.First(d => d.Id == "Weather_Precipitation_Device") as WeatherPercipitationDevice;
            var windDevice          = result.First(d => d.Id == "Weather_Wind_Device") as WeatherWindDevice;

            Assert.AreEqual(21.7, airDevice.Value);
            Assert.AreEqual(40.5, airDevice.RealtiveHumidity);

            Assert.AreEqual(33.1, roadDevice.Value);

            Assert.AreEqual(2.2, precipitationDevice.Value);
            Assert.AreEqual("Mkt Regn", precipitationDevice.AmountTextual);
            Assert.AreEqual("Regn", precipitationDevice.Type);

            Assert.AreEqual(1.1, windDevice.Value);
            Assert.AreEqual(3.4, windDevice.MaxValue);
            Assert.AreEqual(180, windDevice.Direction);
            Assert.AreEqual("Syd", windDevice.DirectionTextual);
        }
예제 #36
0
        public async Task OnUpdateDevices()
        {
            var data = new MockData()
            {
                PerformDeviceUpdates = true
            };
            var container = GetMockContainer(data);

            var updateDevices = new List <IDevice[]>();

            container.Service.OnDevicesUpdated += (o, e) =>
            {
                updateDevices.Add(e.UpdatedDevices);
            };

            await container.Service.InitAsync(new Models.ZWayConfiguration()
            {
                Adress   = data.BaseAdress,
                Password = data.Password,
                Username = data.Username,
                Devices  = data.DeviceConfiguration
            });

            await Task.Delay(4000);

            Assert.AreEqual(1, updateDevices[0].Length);
            Assert.AreEqual("Device1", updateDevices[0][0].Id);
            Assert.AreEqual(23.5, updateDevices[0][0].Value);

            Assert.AreEqual(1, updateDevices[1].Length);
            Assert.AreEqual("Device2", updateDevices[1][0].Id);
            Assert.AreEqual("20", (updateDevices[1][0] as ZWavePowerPlugDevice).PowerConsumption);

            Assert.AreEqual(1, updateDevices[2].Length);
            Assert.AreEqual("Device2", updateDevices[2][0].Id);
            Assert.AreEqual(false, updateDevices[2][0].Value);
        }
예제 #37
0
파일: MockMessage.cs 프로젝트: Zapote/EzBus
 public MockMessage(string stringValue)
 {
     StringValue = stringValue;
     MockData = new MockData();
     MockEnum = MockEnum.Bar;
 }