public async Task GetProductNoResultTestById() { // arrange var id = Guid.NewGuid().ToString(); var mock = new Mock <IProductService>(); mock.Setup(p => p.GetAsync(It.IsAny <string>())) .ReturnsAsync(() => null) ; var prod = new ProductController(mock.Object); // act var data = await prod.GetProduct(id); IActionResult actionResult = data.Result; OkObjectResult okObjectResult = Assert.IsType <OkObjectResult>(actionResult); ProductApi model = null; if (okObjectResult.Value != null) { model = Assert.IsType <ProductApi>(okObjectResult.Value); } // assert Assert.Null(model); }
public void GetWorksCorrectly() { ProductApi api = new ProductApi(); var result = api.Get(new [] { "9788741201122", "9788702168044" }); result.Count().Should().Be(2); }
public void GetByFacetsTest() { // Setup the handler var json = File.ReadAllText("Product/TestProductsByFacets.json"); var jsonData = JObject.Parse(json); var mockHandler = GetHttpMessageHandlerMock(json); // Use HttpClient with mocked HttpMessageHandler var httpClient = new HttpClient(mockHandler.Object); var objectToTest = new ProductApi(new Uri("https://test.com/"), ref httpClient); // Prepare query var query = new Dictionary <string, string> { { "language", "italian" }, { "brand", "monoprix" } }; // Perform test var res = objectToTest.GetByFacets(query).Result; res.Should().NotBeNull().And.HaveCount(1); res.First().Id.Should().Be("3350033164765"); // Check the http call was as expected var expectedUri = new Uri("https://test.com/brand/monoprix/language/italian.json"); VerifyMockCalls(mockHandler, HttpMethod.Get, expectedUri); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Matches request to an endpoint. app.UseRouting(); // Endpoint aware middleware. // Middleware can use metadata from the matched endpoint. app.UseAuthentication(); app.UseAuthorization(); // Execute the matched endpoint. #region snippet app.UseEndpoints(endpoints => { // Route-based APIs UserApi.Map(endpoints); ProductApi.Map(endpoints); // Map other endpoints... endpoints.MapRazorPages(); }); #endregion }
public void CRUDProductTest() { int pid = 9876; var product = new product() { product_id = pid, product1 = "TestProduct", price = 123, quantity = 321, catagory = "Test Catagory", subcatagory = "Test SubCatagory", note = "Note" }; var addedProduct = this.invoiceDbEntities.products.Add(product); pid = addedProduct.product_id; this.invoiceDbEntities.SaveChanges(); var products = ProductApi.GetProductList(null); var testProduct = products.FirstOrDefault(x => x.product_id == addedProduct.product_id); Assert.IsNotNull(testProduct, "Test product not found."); Assert.AreEqual(testProduct.price, product.price, "Products are different."); testProduct = this.invoiceDbEntities.products.Remove(product); this.invoiceDbEntities.SaveChanges(); products = ProductApi.GetProductList(null); Assert.IsNull(products.FirstOrDefault(x => x.product_id == addedProduct.product_id), "Test product is not removed."); }
public CreateOrderAction(OrderApi orderApi, CustomerApi customerApi, ProductApi productApi, OrderLineApi orderLineApi) { _orderApi = orderApi; _customerApi = customerApi; _productApi = productApi; _orderLineApi = orderLineApi; }
public JsonResult GetAllProducts() { ProductApi productApi = new ProductApi(); List <ProductViewModel> result = productApi.GetActive().Where(q => q.ParentProductId == null).ToList(); return(Json(new { data = result }, JsonRequestBehavior.AllowGet)); }
private static ClassifierResult CreateClassifierResult(JObject result) { ClassifierResult classifierResult = Newtonsoft.Json.JsonConvert.DeserializeObject <ClassifierResult>(result.ToString()); switch (classifierResult.Type) { case PageType.Article: classifierResult.PageResult = ArticleApi.CreateArticle(result); break; case PageType.FrontPage: classifierResult.PageResult = FrontPageApi.CreateFrontPage(result); break; case PageType.Image: classifierResult.PageResult = ImageApi.CreateImages(result); break; case PageType.Product: classifierResult.PageResult = ProductApi.CreateProduct(result); break; } return(classifierResult); }
public void AddProdectTest() { var addProductData = new AddProductData(); var result = ProductApi.AddProduct("[appid]", addProductData); Console.Write(result); Assert.IsNotNull(result); }
public List <ProductFindResult> CollectProducts(string filter) { ProductApi api = new ProductApi(site, company, username, password, cookie); List <ProductFindResult> results = api.FindProducts(filter, "Id", null, null, returnFields); logger.Info("Found " + results.Count + " products"); return(results); }
private async void MainForm_Load(object sender, EventArgs e) { var result = await ProductApi.GetAllProductsAsync(null); if (result != null) { this.dataGridViewBooks.DataSource = result; } }
public async Task <(OpenFoodFactsData, ProductData)> InsertFromBarcode(string code) { HttpClient httpClient = new HttpClient(); ProductApi productApi = new ProductApi(Utils.BuildBaseUri(), ref httpClient); ProductData productData = await productApi.GetAsync(code); OpenFoodFactsData openFoodFactsData = new OpenFoodFactsData(productData); return(base.Insert(openFoodFactsData).GetAwaiter().GetResult(), productData); }
public void Init() { var account = TestAccount.Create(); _configuration = new Configuration() { Username = account.Username, Password = account.Password }; _subject = new ProductApi(_configuration); }
public ShopifyReferenceGet( ShopApi shopApi, ProductApi productApi, ShopifyInventoryRepository locationRepository, ReferenceDataRepository referenceDataRepository, ShopifyJsonService shopifyJsonService) { _shopApi = shopApi; _productApi = productApi; _locationRepository = locationRepository; _referenceDataRepository = referenceDataRepository; _shopifyJsonService = shopifyJsonService; }
private async void btnGet_Click(object sender, EventArgs e) { var result = await ProductApi.GetAllProductsAsync(null); if (result != null) { foreach (var item in result) { txtLog.Text += item.ID + "\t" + item.Name + "\t" + item.Category + "\t" + item.Price; txtLog.Text += "\r\n"; } } }
public ShopifyJsonService( OrderApi orderApi, ProductApi productApi, InventoryApi inventoryApi, CustomerApi customerApi, ProcessPersistContext dataContext) { _orderApi = orderApi; _productApi = productApi; _inventoryApi = inventoryApi; _customerApi = customerApi; _dataContext = dataContext; }
public async Task CompareRecordsTest() { // Arrange IProductRepository mockRepo = new MockProductRepository(); var mockDownloadTimesApi = Substitute.For <IDownloadTimesApi>(); var mockProductTypesApi = Substitute.For <IProductTypesApi>(); var mockManufacturersApi = Substitute.For <IManufacturersApi>(); var mockInstallTypesApi = Substitute.For <IInstallTypesApi>(); var mockMobileLookupApi = Substitute.For <IMobileLookupApi>(); var mockBrandApi = Substitute.For <IBrandApi>(); IDistributedCache mockCache = Substitute.For <IDistributedCache>(); IOptions <Settings> appSettings = Substitute.For <IOptions <Settings> >(); IStringLocalizer <ProductsController> mockLocalizer = new MockStringLocalizer <ProductsController>(); IProductApi productApi = new ProductApi(appSettings, mockRepo); var controller = new ProductsController(mockCache, productApi, mockDownloadTimesApi, mockProductTypesApi, mockManufacturersApi, mockInstallTypesApi, mockMobileLookupApi, mockBrandApi, mockLocalizer); var request = new GetProductsWithPagingRequestModel { FirstRecordNumber = 0, PageSize = 10, SortField = string.Empty, SortOrder = SortOrderEnum.Asc }; var testProducts = await mockRepo.GetAllProductsAsync(); var firstProduct = new List <ProductModel>(testProducts)[0]; //// Act var actionResult = await controller.GetProductsWithPaging(request); //// Assert var actualRecord = ((ObjectResult)actionResult).Value; Assert.Equal(((List <ProductModel>)actualRecord).Count, 10); var testProduct = ((List <ProductModel>)actualRecord)[0]; Assert.Equal(JsonConvert.SerializeObject(firstProduct), JsonConvert.SerializeObject(testProduct)); }
public async Task BadRequestTest() { // Arrange IProductRepository mockRepo = new MockProductRepository(); var mockDownloadTimesApi = Substitute.For <IDownloadTimesApi>(); var mockProductTypesApi = Substitute.For <IProductTypesApi>(); var mockManufacturersApi = Substitute.For <IManufacturersApi>(); var mockInstallTypesApi = Substitute.For <IInstallTypesApi>(); var mockMobileLookupApi = Substitute.For <IMobileLookupApi>(); var mockBrandApi = Substitute.For <IBrandApi>(); IDistributedCache mockCache = Substitute.For <IDistributedCache>(); IOptions <Settings> appSettings = Substitute.For <IOptions <Settings> >(); IStringLocalizer <ProductsController> mockLocalizer = new MockStringLocalizer <ProductsController>(); IProductApi productApi = new ProductApi(appSettings, mockRepo); var controller = new ProductsController(mockCache, productApi, mockDownloadTimesApi, mockProductTypesApi, mockManufacturersApi, mockInstallTypesApi, mockMobileLookupApi, mockBrandApi, mockLocalizer); var request = new GetProductsWithPagingRequestModel { FirstRecordNumber = -1, PageSize = 0, SortField = string.Empty, SortOrder = SortOrderEnum.Asc }; controller.ModelState.AddModelError("", "Error"); //// Act var actionResult = await controller.GetProductsWithPaging(request); var badResponse = actionResult as BadRequestObjectResult; //// Assert Assert.NotNull(badResponse); Assert.Equal(badResponse.StatusCode, (int)System.Net.HttpStatusCode.BadRequest); }
public ShopifyProductVariantPut( SyncInventoryRepository syncInventoryRepository, SettingsRepository settingsRepository, ShopifyInventoryGet shopifyInventoryGet, ShopifyInventoryPut shopifyInventoryPut, AcumaticaJsonService acumaticaJsonService, ExecutionLogService logService, ProductApi productApi) { _syncInventoryRepository = syncInventoryRepository; _settingsRepository = settingsRepository; _shopifyInventoryGet = shopifyInventoryGet; _shopifyInventoryPut = shopifyInventoryPut; _acumaticaJsonService = acumaticaJsonService; _logService = logService; _productApi = productApi; }
public ShopifyInventoryPut( InventoryApi inventoryApi, ProductApi productApi, ShopifyInventoryRepository inventoryRepository, SyncInventoryRepository syncInventoryRepository, SettingsRepository settingsRepository, ExecutionLogService executionLogService, IPushLogger logger, AcumaticaJsonService acumaticaJsonService) { _inventoryApi = inventoryApi; _productApi = productApi; _inventoryRepository = inventoryRepository; _syncInventoryRepository = syncInventoryRepository; _settingsRepository = settingsRepository; _executionLogService = executionLogService; _logger = logger; _acumaticaJsonService = acumaticaJsonService; }
public async void ListProducts_ReturnsProducts() { //Arrange var mockLogger = new Mock <ILogger <ProductApi> >(); var mockHttpRequestFactory = new Mock <IHttpRequestFactory>(); mockHttpRequestFactory.Setup(x => x.Get( It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), It.IsAny <string>() ) ) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new JsonContent(new ListProductsResponse { Products = new List <Core.Abstractions.Api.ProductApi.ListProducts.Product> { new Core.Abstractions.Api.ProductApi.ListProducts.Product { ProductNumber = "ST-1401" }, new Core.Abstractions.Api.ProductApi.ListProducts.Product { ProductNumber = "ST-1402" }, } }) }); var baseAddress = "BaseAddress"; var sut = new ProductApi( mockLogger.Object, mockHttpRequestFactory.Object, baseAddress ); //Act var response = await sut.ListProductsAsync(new ListProductsRequest()); //Assert mockHttpRequestFactory.Verify(x => x.Get(It.IsAny <string>(), It.IsAny <Dictionary <string, string> >(), It.IsAny <string>())); response.Products[0].ProductNumber.Should().Be("ST-1401"); response.Products[1].ProductNumber.Should().Be("ST-1402"); }
private async void Button_Clicked(object sender, EventArgs e) { var scanner = new MobileBarcodeScanner(); var result = await scanner.Scan(); if (result != null) { string barcode = result.Text; IProductApi api = new ProductApi("http://192.168.1.100:5000"); try { ProductInformationDto dto = await api.GetByBarcodeAsync(barcode); ProductName.Text = dto.Name; } catch (ApiException ex) { string message; ErrorResultDto errorDto = JsonConvert.DeserializeObject <ErrorResultDto>(ex.ErrorContent.ToString()); switch (errorDto.ErrorCode) { case ErrorResultDto.ErrorCodeEnum.GenericError: message = "A szerver nem tudta feldolgozni a kérést"; break; case ErrorResultDto.ErrorCodeEnum.ProductNotFound: message = "Nincs termék ezzel a vonalkóddal"; break; default: message = "Ismeretlen hiba történt"; break; } await DisplayAlert("Hiba", message, "Ok"); } catch (Exception) { await DisplayAlert("Hiba", "Ismeretlen hiba történt", "Ok"); } } }
public ShopifyInventoryGet( IPushLogger logger, ProductApi productApi, InventoryApi inventoryApi, EventApi eventApi, ShopifyInventoryRepository inventoryRepository, JobMonitoringService jobMonitoringService, ShopifyBatchRepository batchRepository, ExecutionLogService executionLogService, ShopifyJsonService shopifyJsonService) { _productApi = productApi; _inventoryApi = inventoryApi; _eventApi = eventApi; _inventoryRepository = inventoryRepository; _jobMonitoringService = jobMonitoringService; _batchRepository = batchRepository; _executionLogService = executionLogService; _shopifyJsonService = shopifyJsonService; _logger = logger; }
public async Task <ActionResult> Update(int id, ProductApi productApi) { if (!ModelState.IsValid || id != productApi.Id) { return(BadRequest(ModelState)); } try { await _dictionaryService.ProductUpdateAsync(_mapper.Map <Product>(productApi)); return(CreatedAtAction(nameof(Get), productApi)); } catch (Exception ex) { var message = $"Update product error. {ex.Message}"; _logger.LogError(message); return(BadRequest(message)); } }
public void GetProductListWebApi() { var category = (string)this.CatagoryBox.SelectedItem; var products = ProductApi.GetProductList(category); foreach (var product in products.OrderBy(x => x.product_id)) { // product_id as No, Product, Price, Quantity, Catagory, SubCatagory, Not DataGridViewRow row = (DataGridViewRow)ProductDataView.Rows[0].Clone(); row.Cells[0].Value = product.product_id.ToString(); row.Cells[1].Value = product.product1.ToString(); row.Cells[2].Value = product.price.ToString(); row.Cells[3].Value = product.quantity.ToString(); row.Cells[4].Value = product.catagory.ToString().Trim(); SelectedCatagory(row, product.catagory.ToString().Trim()); row.Cells[5].Value = (string)product.subcatagory; row.Cells[6].Value = (string)product.note; this.ProductDataView.Rows.Add(row); } }
public void GetAsyncTest() { // Setup the handler var json = File.ReadAllText("Product/TestProduct.json"); var jsonData = JObject.Parse(json); var mockHandler = GetHttpMessageHandlerMock(json); // Use HttpClient with mocked HttpMessageHandler var httpClient = new HttpClient(mockHandler.Object); var objectToTest = new ProductApi(new Uri("https://test.com/"), ref httpClient); // Perform test var res = objectToTest.GetAsync("3222475893421").Result; res.Should().NotBeNull(); res.Id.Should().Be("3222475893421"); // Check the http call was as expected var expectedUri = new Uri("https://test.com/api/v0/product/3222475893421.json"); VerifyMockCalls(mockHandler, HttpMethod.Get, expectedUri); }
public ActionResult AddNewProduct(string name, string[] sizeList, string[] colorList, string description, int categoryID, int supplierID, decimal price) { StringBuilder size = new StringBuilder(); StringBuilder color = new StringBuilder(); for (int i = 0; i < sizeList.Length; i++) { size.Append(sizeList[i]); if (i < sizeList.Length - 1) { size.Append(","); } } for (int i = 0; i < colorList.Length; i++) { color.Append(colorList[i]); if (i < colorList.Length - 1) { color.Append(","); } } List <ProductImageViewModel> listProductImage = new List <ProductImageViewModel>(); ProductImageViewModel productImage = new ProductImageViewModel(); var orderCount = 0; byte[] avatarImage = null; if (Request.Files.Count > 0) { for (int i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; int fileSizeInBytes = file.ContentLength; using (var br = new BinaryReader(file.InputStream)) { avatarImage = br.ReadBytes(fileSizeInBytes); } string picUrl = null; if (avatarImage != null) { picUrl = SaveImageToServer(avatarImage); productImage.PicUrl = picUrl; productImage.DisplayOrder = ++orderCount; listProductImage.Add(productImage); } } } ProductViewModel newProduct = new ProductViewModel() { Name = name, Size = size.ToString(), Color = color.ToString(), Description = description, CategoryID = categoryID, SupplierId = supplierID, Price = price, ProductImages = listProductImage, Active = true, }; ProductApi productApi = new ProductApi(); productApi.Create(newProduct); return(Json(new { success = true, message = "Successfully added!" }, JsonRequestBehavior.AllowGet)); }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// </param> /// <param name='productApi'> /// </param> public static Stream Update(this IProductApiOperations operations, int id, ProductApi productApi) { return(operations.UpdateAsync(id, productApi).GetAwaiter().GetResult()); }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='productApi'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <Stream> CreateAsync(this IProductApiOperations operations, ProductApi productApi, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.CreateWithHttpMessagesAsync(productApi, null, cancellationToken).ConfigureAwait(false); _result.Request.Dispose(); return(_result.Body); }
/// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='productApi'> /// </param> public static Stream Create(this IProductApiOperations operations, ProductApi productApi) { return(operations.CreateAsync(productApi).GetAwaiter().GetResult()); }
public List<ProductFindResult> CollectProducts(string filter) { ProductApi api = new ProductApi(site, company, username, password, cookie); List<ProductFindResult> results = api.FindProducts(filter, "Id", null, null, returnFields); logger.Info("Found " + results.Count + " products"); return results; }