public async Task Get_Ancestors_Is_200_Response() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { MockServicesForAuthorizationSuccess(testServices, 123); }); await base.Get_Ancestors_Is_200_Response(startup.UseDefaultTestSetup, RouteConstants.MediaSegment); }
public HttpClient GetClient(string settings) { var startup = new TestStartup(settings); //<--- var builder = new WebHostBuilder() .ConfigureServices(services => { services.AddSingleton <IStartup>(startup); }); var server = new TestServer(builder); return(server.CreateClient()); }
public void Is_ProductService_CreateProduct_Return_ProductInfo(string command, string expectedResult) { TestStartup.ConfigureServices(); var service = TestStartup.ServiceProvider.GetService <IProductService>(); var result = service.CreateProduct(command.Split(' ')); Assert.Equal(expectedResult, result); TestStartup.DisposeServices(); }
private HttpContext CreateTestHttpContext() { var ctx = new DefaultHttpContext(); var startup = new TestStartup(); var sc = new ServiceCollection(); startup.ConfigureServices(sc); ctx.RequestServices = sc.BuildServiceProvider(); return(ctx); }
public async Task Supports_Creds() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services, (testServices) => { var mockContentService = Mock.Get(testServices.ServiceContext.ContentService); mockContentService.Setup(x => x.GetRootContent()).Returns(Enumerable.Empty <IContent>()); }); using (var server = TestServer.Create(app => { var httpConfig = startup.UseTestWebApiConfiguration(app); app.AuthenticateEverything(); app.UseUmbracoRestApi(startup.ApplicationContext, new UmbracoRestApiOptions { //customize the authz policies, in this case we want to allow everything CustomAuthorizationPolicyCallback = (policyName, defaultPolicy) => (builder => builder.RequireAssertion(context => true)), CorsPolicy = new CorsPolicy() { AllowAnyOrigin = true, SupportsCredentials = true } }); app.UseWebApi(httpConfig); })) { var request = new HttpRequestMessage() { RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.ContentSegment)), Method = HttpMethod.Get, }; //add the origin so Cors kicks in! request.Headers.Add("Origin", "http://localhost:12061"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); Assert.IsTrue(result.Headers.Contains("Access-Control-Allow-Origin")); var acao = result.Headers.GetValues("Access-Control-Allow-Origin"); Assert.AreEqual(1, acao.Count()); Assert.AreEqual("http://localhost:12061", acao.First()); } }
public async Task Get_Children_Is_200_With_Params_Result() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { MockServicesForAuthorizationSuccess(testServices, 123); var mockMediaService = Mock.Get(testServices.ServiceContext.MediaService); mockMediaService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedMedia()); long total = 6; mockMediaService.Setup(x => x.GetPagedChildren(It.IsAny <int>(), It.IsAny <long>(), It.IsAny <int>(), out total, It.IsAny <string>(), Direction.Ascending, It.IsAny <string>())) .Returns(new List <IMedia>(new[] { ModelMocks.SimpleMockedMedia(789), ModelMocks.SimpleMockedMedia(456) })); mockMediaService.Setup(x => x.HasChildren(It.IsAny <int>())).Returns(true); }); using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.MediaSegment}/123/children?page=2&size=2"), Method = HttpMethod.Get, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var djson = JsonConvert.DeserializeObject <JObject>(json); Assert.AreEqual(6, djson["totalResults"].Value <int>()); Assert.AreEqual(2, djson["page"].Value <int>()); Assert.AreEqual(2, djson["pageSize"].Value <int>()); Assert.IsNotNull(djson["_links"]["next"]); Assert.IsNotNull(djson["_links"]["prev"]); } }
public static void ClassInit(TestContext context) { serviceProvider = TestStartup.ConfigureServices(); voteCounter = serviceProvider.GetRequiredService <IVoteCounter>(); tally = serviceProvider.GetRequiredService <Tally>(); voteConstructor = serviceProvider.GetRequiredService <VoteConstructor>(); agnostic = serviceProvider.GetRequiredService <IAgnostic>(); IQuest quest = new Quest(); agnostic.ComparisonPropertyChanged(quest, new System.ComponentModel.PropertyChangedEventArgs(nameof(quest.CaseIsSignificant))); }
public void Is_CampaignService_GetCampaignInfo_Return_CampaignInfo(string createComman, string getCommand, string expectedResult) { TestStartup.ConfigureServices(); var service = TestStartup.ServiceProvider.GetService <ICampaignService>(); service.CreateCampaign(createComman.Split(' ')); var result = service.CreateCampaign(getCommand.Split(' ')); Assert.NotEqual(expectedResult, result); TestStartup.DisposeServices(); }
public async Task Get_Root_Result_With_Custom_Start_Nodes() { //represents the node(s) that the user will receive as their root based on their custom start node var rootNodes = ModelMocks.SimpleMockedContent(123, 456); var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services, (testServices) => { MockServicesForAuthorizationSuccess(testServices, 456); var mockContentService = Mock.Get(testServices.ServiceContext.ContentService); mockContentService.Setup(x => x.GetByIds(It.IsAny <int[]>())).Returns(new[] { rootNodes }); mockContentService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedContent(789, 123) }); mockContentService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedContent(321, 456) }); }); var djson = await Get_Root_Result(app => { //we are doing a custom authz for this call so need to change the startup process var identity = new UmbracoBackOfficeIdentity( new UserData(Guid.NewGuid().ToString()) { Id = 0, Roles = new[] { "admin" }, AllowedApplications = new[] { "content", "media", "members" }, Culture = "en-US", RealName = "Admin", StartContentNodes = new[] { 456 }, StartMediaNodes = new[] { -1 }, Username = "******", SessionId = Guid.NewGuid().ToString(), SecurityStamp = Guid.NewGuid().ToString() }); var httpConfig = startup.UseTestWebApiConfiguration(app); app.AuthenticateEverything(new AuthenticateEverythingAuthenticationOptions(identity)); app.UseUmbracoRestApi(startup.ApplicationContext); app.UseWebApi(httpConfig); }, RouteConstants.ContentSegment); Assert.AreEqual(1, djson["_links"]["content"].Count()); Assert.AreEqual($"/umbraco/rest/v1/content/{123.ToGuid()}", djson["_links"]["content"]["href"].Value <string>()); Assert.AreEqual(1, djson["_embedded"]["content"].Count()); Assert.AreEqual(rootNodes.Key, (Guid)djson["_embedded"]["content"].First["id"]); }
public async Task Get_By_Key_Result() { var guidId = Guid.NewGuid(); var content = ModelMocks.SimpleMockedPublishedContent(guidId, 456, 789); var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { var mockTypedContent = Mock.Get(testServices.PublishedContentQuery); mockTypedContent.Setup(x => x.TypedContent(It.IsAny <Guid>())).Returns(() => content); }); using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.ContentSegment}/{RouteConstants.PublishedSegment}/{guidId}"), Method = HttpMethod.Get, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); Assert.AreEqual("application/hal+json", result.Content.Headers.ContentType.MediaType); Assert.IsAssignableFrom <StreamContent>(result.Content); //TODO: Need to assert more values! var djson = JsonConvert.DeserializeObject <JObject>(json); Assert.AreEqual($"/umbraco/rest/v1/content/published/{content.Key}", djson["_links"]["self"]["href"].Value <string>()); Assert.AreEqual($"/umbraco/rest/v1/content/published/{456.ToGuid()}", djson["_links"]["parent"]["href"].Value <string>()); Assert.AreEqual($"/umbraco/rest/v1/content/published/{content.Key}/children{{?page,size,query}}", djson["_links"]["children"]["href"].Value <string>()); Assert.AreEqual("/umbraco/rest/v1/content/published", djson["_links"]["root"]["href"].Value <string>()); var properties = djson["properties"].ToObject <IDictionary <string, object> >(); Assert.AreEqual(2, properties.Count()); Assert.IsTrue(properties.ContainsKey("TestProperty1")); Assert.IsTrue(properties.ContainsKey("testProperty2")); } }
/// <summary> /// Gets the default service provider /// </summary> /// <returns></returns> private IServiceProvider GetDefaultServiceProvider() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); var configuration = builder.Build(); var startup = new TestStartup(configuration); var serviceProvicer = startup.ConfigureServices(new ServiceCollection()); return(serviceProvicer); }
public async void Supports_Post() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (request, umbCtx, typedContent, serviceContext, searchProvider) => { TestHelpers.ContentServiceMocks.SetupMocksForPost(serviceContext); }); using (var server = TestServer.Create(builder => startup.Configuration(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.ContentSegment)), Method = HttpMethod.Post, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); request.Headers.Add("Origin", "http://*****:*****@"{ ""contentTypeAlias"": ""testType"", ""parentId"": 456, ""templateId"": 9, ""name"": ""Home"", ""properties"": { ""TestProperty1"": ""property value1"", ""testProperty2"": ""property value2"" } }", Encoding.UTF8, "application/json"); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); //CORS Assert.IsTrue(result.Headers.Contains("Access-Control-Allow-Origin")); var acao = result.Headers.GetValues("Access-Control-Allow-Origin"); Assert.AreEqual(1, acao.Count()); Assert.AreEqual("http://localhost:12061", acao.First()); //Creation var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.Created, result.StatusCode); } }
public async Task Post_Is_400_Validation_Property_Required() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { MockServicesForAuthorizationSuccess(testServices, 456); MediaServiceMocks.SetupMocksForPost(testServices.ServiceContext); var mockPropertyEditor = Mock.Get(PropertyEditorResolver.Current); mockPropertyEditor.Setup(x => x.GetByAlias("testEditor")).Returns(new ModelMocks.SimplePropertyEditor()); }); using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.MediaSegment)), Method = HttpMethod.Post, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); //NOTE: it is missing request.Content = new StringContent(@"{ ""name"": ""test"", ""contentTypeAlias"": ""test"", ""parentId"": 456, ""templateId"": 9, ""properties"": { ""TestProperty1"": """", ""testProperty2"": ""property value2"" } }", Encoding.UTF8, "application/json"); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode); var djson = JsonConvert.DeserializeObject <JObject>(json); Assert.AreEqual(1, djson["totalResults"].Value <int>()); Assert.AreEqual("content.properties.TestProperty1.value", djson["_embedded"]["errors"][0]["logRef"].Value <string>()); } }
public async void Supports_Creds() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services, (request, umbCtx, typedContent, serviceContext, searchProvider) => { var mockContentService = Mock.Get(serviceContext.ContentService); mockContentService.Setup(x => x.GetRootContent()).Returns(Enumerable.Empty <IContent>()); }); using (var server = TestServer.Create(builder => { startup.Configuration(builder); //default options builder.ConfigureUmbracoRestApi(new UmbracoRestApiOptions { CorsPolicy = new CorsPolicy() { AllowAnyOrigin = true, SupportsCredentials = true } }); })) { var request = new HttpRequestMessage() { RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.ContentSegment)), Method = HttpMethod.Get, }; //add the origin so Cors kicks in! request.Headers.Add("Origin", "http://localhost:12061"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); Assert.IsTrue(result.Headers.Contains("Access-Control-Allow-Origin")); var acao = result.Headers.GetValues("Access-Control-Allow-Origin"); Assert.AreEqual(1, acao.Count()); Assert.AreEqual("http://localhost:12061", acao.First()); } }
public HttpClient GetClient(string settings) { TestServer server = null; if (!cache.TryGetValue(settings, out server)) { var startup = new TestStartup(settings); //<--- var builder = new WebHostBuilder() .ConfigureServices(services => { services.AddSingleton <IStartup>(startup); }); server = new TestServer(builder); } return(server.CreateClient()); }
public async Task Post_Is_400_Validation_Property_Missing() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { MemberServiceMocks.SetupMocksForPost(testServices.ServiceContext); }); using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.MembersSegment}"), Method = HttpMethod.Post, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); //NOTE: it is missing request.Content = new StringContent(@"{ ""contentTypeAlias"": ""testType"", ""name"": ""John Johnson"", ""email"" : ""*****@*****.**"", ""userName"" : ""johnjohnson"", ""parentId"": 456, ""templateId"": 9, ""properties"": { ""thisDoesntExist"": ""property value1"", ""testProperty2"": ""property value2"" } }", Encoding.UTF8, "application/json"); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode); var djson = JsonConvert.DeserializeObject <JObject>(json); Assert.AreEqual(1, djson["totalResults"].Value <int>()); Assert.AreEqual("content.properties.thisDoesntExist", djson["_embedded"]["errors"][0]["logRef"].Value <string>()); } }
public async void Get_Id_Result() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (request, umbCtx, typedContent, serviceContext, searchProvider) => { var mockMediaService = Mock.Get(serviceContext.MediaService); mockMediaService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedMedia()); mockMediaService.Setup(x => x.GetChildren(It.IsAny <int>())).Returns(new List <IMedia>(new[] { ModelMocks.SimpleMockedMedia(789) })); mockMediaService.Setup(x => x.HasChildren(It.IsAny <int>())).Returns(true); }); using (var server = TestServer.Create(builder => startup.Configuration(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}/123", RouteConstants.MediaSegment)), Method = HttpMethod.Get, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var djson = JsonConvert.DeserializeObject <JObject>(json); Assert.AreEqual("/umbraco/rest/v1/media/123", djson["_links"]["self"]["href"].Value <string>()); Assert.AreEqual("/umbraco/rest/v1/media/456", djson["_links"]["parent"]["href"].Value <string>()); Assert.AreEqual("/umbraco/rest/v1/media/123/children{?pageIndex,pageSize}", djson["_links"]["children"]["href"].Value <string>()); Assert.AreEqual("/umbraco/rest/v1/media", djson["_links"]["root"]["href"].Value <string>()); var properties = djson["properties"].ToObject <IDictionary <string, object> >(); Assert.AreEqual(2, properties.Count()); Assert.IsTrue(properties.ContainsKey("TestProperty1")); Assert.IsTrue(properties.ContainsKey("testProperty2")); } }
public TokenHelperTests() { _startup = new TestStartup(); _cacheKey = "clientIdclientSecretscopehttp://localhost/api/oauth/token"; _settings = new ServiceSettings { Scheme = HttpSchema.Http, Host = "localhost", Path = "api", OAuthPathAddition = "oauth/token", OAuthClientId = "clientId", OAuthClientSecret = "clientSecret", OAuthScope = "scope" }; }
public async Task Post_Is_201_Response() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { RelationServiceMocks.SetupMocksForPost(testServices.ServiceContext); }); await base.Post_Is_201_Response(startup.UseDefaultTestSetup, RouteConstants.RelationsSegment, new StringContent(@"{ ""relationTypeAlias"": ""testType"", ""parentId"": 8910, ""childId"" : 567, ""comment"" : ""Comment"" }", Encoding.UTF8, "application/json")); }
public async void Post_Is_400_Validation_Required_Fields() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (request, umbCtx, typedContent, serviceContext, searchProvider) => { MediaServiceMocks.SetupMocksForPost(serviceContext); }); using (var server = TestServer.Create(builder => startup.Configuration(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.MediaSegment)), Method = HttpMethod.Post, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); //NOTE: it is missing request.Content = new StringContent(@"{ ""contentTypeAlias"": """", ""parentId"": 456, ""templateId"": 9, ""name"": """", ""properties"": { ""TestProperty1"": ""property value1"", ""testProperty2"": ""property value2"" } }", Encoding.UTF8, "application/json"); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode); var djson = JsonConvert.DeserializeObject <JObject>(json); Assert.AreEqual(2, djson["totalResults"].Value <int>()); Assert.AreEqual("content.ContentTypeAlias", djson["_embedded"]["errors"][0]["logRef"].Value <string>()); Assert.AreEqual("content.Name", djson["_embedded"]["errors"][1]["logRef"].Value <string>()); } }
// Use Respawn checkpoints to store database clean states if testing with a persistent/production-like database //private static readonly Checkpoint _checkpoint; static SliceFixture() { _host = A.Fake <IHostingEnvironment>(); A.CallTo(() => _host.ContentRootPath).Returns(Directory.GetCurrentDirectory()); var startup = new TestStartup(new ConfigurationBuilder().Build()); _configuration = Startup.Configuration; var services = new ServiceCollection(); startup.ConfigureServices(services); _rootContainer = services.BuildServiceProvider(); _scopeFactory = _rootContainer.GetService <IServiceScopeFactory>(); //_checkpoint = new Checkpoint(); }
public void Is_ProductRepository_CreateProduct_Return_ProductInfo(string code, int price, int stock, int expectedResult) { TestStartup.ConfigureServices(); var repository = TestStartup.ServiceProvider.GetService <IProductRepository>(); var product = new Product { ProductCode = code, Price = price, Stock = stock }; var result = repository.AddProduct(product); Assert.NotEqual(expectedResult, result.Id); TestStartup.DisposeServices(); }
public async Task Get_Id_Result() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { var mockRelationService = Mock.Get(testServices.ServiceContext.RelationService); mockRelationService.Setup(x => x.GetById(It.IsAny <int>())).Returns(() => ModelMocks.SimpleMockedRelation(123, 4567, 8910, ModelMocks.SimpleMockedRelationType())); }); var djson = await Get_Id_Result(startup.UseDefaultTestSetup, RouteConstants.RelationsSegment); Assert.AreEqual("/umbraco/rest/v1/relations/123", djson["_links"]["self"]["href"].Value <string>()); Assert.AreEqual("/umbraco/rest/v1/relations", djson["_links"]["root"]["href"].Value <string>()); Assert.AreEqual("/umbraco/rest/v1/relations/relationtype/testType", djson["_links"]["relationtype"]["href"].Value <string>()); Assert.AreEqual("/umbraco/rest/v1/content/published/{id}", djson["_links"]["content"]["href"].Value <string>()); }
public async void Get_Root_Result() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services, (request, umbCtx, typedContent, serviceContext, searchProvider) => { var mockMediaService = Mock.Get(serviceContext.MediaService); mockMediaService.Setup(x => x.GetRootMedia()).Returns(new[] { ModelMocks.SimpleMockedMedia(123, -1), ModelMocks.SimpleMockedMedia(456, -1) }); mockMediaService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedMedia(789, 123) }); mockMediaService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedMedia(321, 456) }); }); using (var server = TestServer.Create(builder => startup.Configuration(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.MediaSegment)), Method = HttpMethod.Get, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var asdf = GlobalConfiguration.Configuration; var djson = JsonConvert.DeserializeObject <JObject>(json); Assert.AreEqual("/umbraco/rest/v1/media", djson["_links"]["root"]["href"].Value <string>()); Assert.AreEqual(2, djson["totalResults"].Value <int>()); Assert.AreEqual(2, djson["_links"]["content"].Count()); Assert.AreEqual(2, djson["_embedded"]["content"].Count()); } }
public void TestGetBookById() { var mockRepo = new Mock <IProductSessionRepository>(); mockRepo.Setup(repo => repo.GetProductById(1)).Returns(TestStartup.GetTestSession()); var controller = new ProductsController(mockRepo.Object); string expectedName = "product 1"; var result = controller.GetProduct(1); // Assert var okResult = Assert.IsType <OkObjectResult>(result); var product = Assert.IsType <Product>(okResult.Value); Assert.Equal(expectedName, product.ProductName); }
public async Task Get_Root_With_OPTIONS() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services, (testServices) => { var mockMediaService = Mock.Get(testServices.ServiceContext.MediaService); mockMediaService.Setup(x => x.GetRootMedia()).Returns(new[] { ModelMocks.SimpleMockedMedia(123, -1), ModelMocks.SimpleMockedMedia(456, -1) }); mockMediaService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedMedia(789, 123) }); mockMediaService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedMedia(321, 456) }); }); await Get_Root_With_OPTIONS(startup.UseDefaultTestSetup, RouteConstants.MediaSegment); }
public async void Get_Root_With_OPTIONS() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services, (request, umbCtx, typedContent, serviceContext, searchProvider) => { var mockMediaService = Mock.Get(serviceContext.MediaService); mockMediaService.Setup(x => x.GetRootMedia()).Returns(new[] { ModelMocks.SimpleMockedMedia(123, -1), ModelMocks.SimpleMockedMedia(456, -1) }); mockMediaService.Setup(x => x.GetChildren(123)).Returns(new[] { ModelMocks.SimpleMockedMedia(789, 123) }); mockMediaService.Setup(x => x.GetChildren(456)).Returns(new[] { ModelMocks.SimpleMockedMedia(321, 456) }); }); using (var server = TestServer.Create(builder => startup.Configuration(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri(string.Format("http://testserver/umbraco/rest/v1/{0}", RouteConstants.MediaSegment)), Method = HttpMethod.Options, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); request.Headers.Add("Access-Control-Request-Headers", "accept, authorization"); request.Headers.Add("Access-Control-Request-Method", "GET"); request.Headers.Add("Origin", "http://localhost:12061"); request.Headers.Add("Referer", "http://localhost:12061/browser.html"); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); } }
public async Task Post_Is_400_Validation_Required_Fields() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { RelationServiceMocks.SetupMocksForPost(testServices.ServiceContext); }); using (var server = TestServer.Create(builder => startup.UseDefaultTestSetup(builder))) { var request = new HttpRequestMessage() { RequestUri = new Uri($"http://testserver/umbraco/rest/v1/{RouteConstants.RelationsSegment}"), Method = HttpMethod.Post, }; request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json")); //NOTE: it is missing parent id request.Content = new StringContent(@"{ ""relationTypeAlias"": """", ""childId"" : 1234, ""comment"" : ""Comment"" }", Encoding.UTF8, "application/json"); Console.WriteLine(request); var result = await server.HttpClient.SendAsync(request); Console.WriteLine(result); var json = await((StreamContent)result.Content).ReadAsStringAsync(); Console.Write(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(json), Formatting.Indented)); Assert.AreEqual(HttpStatusCode.BadRequest, result.StatusCode); var djson = JsonConvert.DeserializeObject <JObject>(json); Assert.AreEqual(2, djson["totalResults"].Value <int>()); Assert.AreEqual("relation.ParentId", djson["_embedded"]["errors"][0]["logRef"].Value <string>()); Assert.AreEqual("relation.RelationTypeAlias", djson["_embedded"]["errors"][1]["logRef"].Value <string>()); } }
public async Task Post_Is_201_Response() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services (testServices) => { MemberServiceMocks.SetupMocksForPost(testServices.ServiceContext); }); await base.Post_Is_201_Response(startup.UseDefaultTestSetup, RouteConstants.MembersSegment, new StringContent(@"{ ""contentTypeAlias"": ""testType"", ""name"": ""John Johnson"", ""email"" : ""*****@*****.**"", ""userName"" : ""johnjohnson"", ""properties"": { ""TestProperty1"": ""property value1"", ""testProperty2"": ""property value2"" } }", Encoding.UTF8, "application/json")); }
public async Task Get_Root_Result() { var startup = new TestStartup( //This will be invoked before the controller is created so we can modify these mocked services, (testServices) => { var mockRelationService = Mock.Get(testServices.ServiceContext.RelationService); mockRelationService.Setup(x => x.GetAllRelationTypes(It.IsAny <int[]>())) .Returns(new[] { new RelationType(Constants.ObjectTypes.DocumentGuid, Constants.ObjectTypes.DocumentGuid, "test1", "Test1"), new RelationType(Constants.ObjectTypes.MediaGuid, Constants.ObjectTypes.MediaGuid, "test2", "Test2"), }); }); var djson = await Get_Root_Result(startup.UseDefaultTestSetup, RouteConstants.RelationsSegment); Assert.AreEqual(2, djson["_links"]["relationtype"].Count()); Assert.AreEqual(2, djson["_embedded"]["relationtype"].Count()); }