// Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of KeyNotFoundException."); try { string expectValue = "HELLO"; KeyNotFoundException myException = new KeyNotFoundException(expectValue); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "KeyNotFoundException instance can not create correctly."); retVal = false; } if (myException.Message != expectValue) { TestLibrary.TestFramework.LogError("001.2", "the Message should return " + expectValue); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
// Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: the parameter string is null."); try { string expectValue = null; KeyNotFoundException myException = new KeyNotFoundException(expectValue); if (myException == null) { TestLibrary.TestFramework.LogError("002.1", "KeyNotFoundException instance can not create correctly."); retVal = false; } if (myException.Message == expectValue) { TestLibrary.TestFramework.LogError("002.2", "the Message should return the default value."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
public void GetInnermostException_ExceptionHasInnerValue_ReturnItself() { //Arrange var ex1 = new Exception("1"); var ex2 = new Exception("2", ex1); var ex3_1 = new KeyNotFoundException("3.1", ex2); var ex3_2 = new InvalidDataException("3.2"); var ex4 = new AggregateException(ex3_1, ex3_2); //Act var result = ex4.GetInnermostException(); //Assert result.Should().BeSameAs(ex1); }
public async Task UpdateMembershipAsync_ShouldFail_WhenMembershipIsNull() { // Arrange _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); var user = _fixture.Create <User>(); var expectedResult = new KeyNotFoundException($"{typeof(Membership)} with id 1 was not found"); _userRepository.GetAsync(user.Id).Returns(user); // Act var result = await Assert.ThrowsAsync <KeyNotFoundException>(async() => await _sut.UpdateMembershipAsync(user.Id, 1)); // Assert Assert.Equal(expectedResult.Message, result.Message); }
internal V Lookup <K, V>(K key) { IReadOnlyDictionary <K, V> _this = JitHelpers.UnsafeCast <IReadOnlyDictionary <K, V> >(this); V value; bool keyFound = _this.TryGetValue(key, out value); if (!keyFound) { Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } return(value); }
public async Task Get_product_by_Id_fail() { //Arrange Guid fakeProductId = new Guid(); var fakeDynamicResult = new KeyNotFoundException(); _productQueriesMock.Setup(x => x.GetProductByIdAsync(It.IsAny <Guid>())) .Throws(new KeyNotFoundException()); //Act var productController = new ProductController(_mediatorMock.Object, _productQueriesMock.Object, _loggerMock.Object); //Assert await Assert.ThrowsAsync <KeyNotFoundException>(() => productController.GetProductByIdAsync(fakeProductId)); }
public TValue Lookup(TKey key) { TValue value; bool found = TryGetValue(key, out value); if (!found) { Debug.Assert(key != null); Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); e.HResult = HResults.E_BOUNDS; throw e; } return(value); }
public void GivenAccountNotExisted_WhenReadAccountByNumber_ThrowArgumentNullException(string accountNumber) { //arrange _accountRepoMock.Setup(a => a.ReadOne(It.IsAny <Expression <Func <Account, bool> > >())) .Returns((Expression <Func <Account, bool> > expression) => { var data = AccountFakeDb.SingleOrDefault(expression); return(data); }); //Action KeyNotFoundException result = Assert.Throws <KeyNotFoundException>(() => _accountService.ReadOneAccountByNumber(accountNumber)); //assert Assert.NotNull(result); }
// V Lookup(K key) internal V Lookup <K, V>(K key) where K : notnull { IReadOnlyDictionary <K, V> _this = Unsafe.As <IReadOnlyDictionary <K, V> >(this); bool keyFound = _this.TryGetValue(key, out V value); if (!keyFound) { Debug.Assert(key != null); Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); e.HResult = HResults.E_BOUNDS; throw e; } return(value); }
// V Lookup(K key) internal V Lookup <K, V>(K key) { IDictionary <K, V> _this = Unsafe.As <IDictionary <K, V> >(this); V value; bool keyFound = _this.TryGetValue(key, out value); if (!keyFound) { Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); e.SetErrorCode(HResults.E_BOUNDS); throw e; } return(value); }
public void UpdatingAnInexistentElementMustRaiseAnException() { // Given MockRepository rep = new MockRepository(); MockClass data = new MockClass(); // When long resp = (long)rep.Add(data); MockClass updatedData = new MockClass(); updatedData.Id = resp + 1; // When / Then KeyNotFoundException exc = Assert.Throws <KeyNotFoundException>(() => rep.Update(updatedData), "Updating inexistent data must raise exception"); }
/// <summary> /// Get the Table data element corresponding to particular column name in containing table /// </summary> /// <param name="ColumnName">Column name</param> /// <returns> Table Data element WebElementWrapper</returns> public WebElementWrapper this[String ColumnName] { get { if (ColumnList.Contains(ColumnName)) { return(new WebElementWrapper(DataList[ColumnList.IndexOf(ColumnName)])); } else { var e = new KeyNotFoundException("The Column " + ColumnName + " is not found in the list of columns" + ColumnList.ToString()); Logger.Error(e); throw e; } } }
protected override void EndProcessing() { if (!TryGetResourceSchema(out ResourceSchema resourceSchema)) { var resourceId = $"{Namespace}/{Type}@{ApiVersion}"; var exception = new KeyNotFoundException($"Unable to find resource '{resourceId}'"); this.ThrowTerminatingError( exception, "ResourceNotFound", ErrorCategory.ObjectNotFound, resourceId); return; } Dictionary <string, ScriptBlock> keywordDefinitions = GetDslKeywordDefinitions(resourceSchema); var armResource = new ConstructingArmBuilder <ArmResource>(); armResource.AddSingleElement(ArmTemplateKeys.Name, (ArmElement)Name); armResource.AddSingleElement(ArmTemplateKeys.ApiVersion, (ArmElement)ApiVersion); armResource.AddSingleElement(ArmTemplateKeys.Type, ComposeResourceTypeElement()); foreach (KeyValuePair <string, RuntimeDefinedParameter> dynamicParameter in _dynamicParameters) { if (resourceSchema.Discriminator is not null && dynamicParameter.Key.Equals(resourceSchema.Discriminator, StringComparison.OrdinalIgnoreCase)) { continue; } armResource.AddSingleElement( new ArmStringLiteral(dynamicParameter.Key), (ArmElement)dynamicParameter.Value.Value); } foreach (PSObject output in Body.InvokeWithContext(keywordDefinitions, variablesToDefine: null)) { if (output.BaseObject is not ArmEntry armEntry) { continue; } armResource.AddEntry(armEntry); } WriteObject(new ArmEntry(ArmTemplateKeys.Resources, armResource.Build(), isArrayElement: true)); }
public void Provider_RemoveProperty_NonexistentID() { BasicPropertiesProvider provider = new BasicPropertiesProvider(TestConstants.anID, TestConstants.aName); KeyNotFoundException expectedException = null; try { provider.RemoveProperty(TestConstants.anID); } catch (KeyNotFoundException e) { expectedException = e; } Assert.IsNotNull(expectedException, "KeyNotFoundException not thrown"); TestUtilities.checkEmpty(provider.Properties, "Properties"); }
public static Dictionary <string, TObject> GetValuesWhere <TObject>(Dictionary <string, TObject> dictionary, Func <TObject, bool> action, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject { dictionary = Check.Object(dictionary, logger); Dictionary <string, TObject> foundElements = dictionary.Values.Where(action).ToDictionary(x => x.Name, x => x); result = foundElements.Count > 1; if ((exception) && (!result)) { object[] args = { }; string message = "Elements aren't found"; var ex = new KeyNotFoundException(message: String.Format(message, args)); logger?.LogError(ex, message, args); throw ex; } return(foundElements); }
public static string Contains <TObject>(Dictionary <string, TObject> dictionary, string nameObject, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject { dictionary = Check.Object(dictionary, logger); nameObject = Check.Name(nameObject, logger); result = dictionary.ContainsKey(nameObject); if ((exception) && (!result)) { object[] args = { nameObject }; string message = "Element with name \"{0}\" is not found"; var ex = new KeyNotFoundException(message: String.Format(message, args)); logger?.LogError(ex, message, args); throw ex; } return(nameObject); }
public void CreateException_WithAllProperties_AssignsAllProperties() { // Arrange string logicApp = "logic app name", resourceGroup = "resource group", subscriptionId = "subscription ID"; string message = "There's something wrong with updating the logic app"; var innerException = new KeyNotFoundException("Couldn't find the logic app"); // Act var exception = new LogicAppNotUpdatedException(subscriptionId, resourceGroup, logicApp, message, innerException); // Assert Assert.Equal(message, exception.Message); Assert.Equal(logicApp, exception.LogicAppName); Assert.Equal(resourceGroup, exception.ResourceGroup); Assert.Equal(subscriptionId, exception.SubscriptionId); Assert.Equal(innerException, exception.InnerException); }
public void TestConstructor__UnknownMod() { IPatch patch = Substitute.For <IPatch>(); UrlDir.UrlConfig urlConfig = UrlBuilder.CreateConfig("abc/def", new ConfigNode("NODE")); patch.PassSpecifier.Returns(new BeforePassSpecifier("mod3", urlConfig)); IPatchProgress progress = Substitute.For <IPatchProgress>(); KeyNotFoundException ex = Assert.Throws <KeyNotFoundException>(delegate { new PatchList(new[] { "mod1", "mod2" }, new[] { patch }, progress); }); Assert.Equal("Mod 'mod3' not found", ex.Message); progress.DidNotReceive().PatchAdded(); }
public void Group_RemoveGroup_NonexistentID() { BasicGroup targetGroup = new BasicGroup(TestConstants.anID, TestConstants.aName); KeyNotFoundException expectedException = null; try { targetGroup.RemoveGroup(TestConstants.anID); } catch (KeyNotFoundException e) { expectedException = e; } Assert.IsNotNull(expectedException, "KeyNotFoundException not thrown"); TestUtilities.checkEmpty(targetGroup.Groups, "Groups"); }
public static bool NotContains <TObject>(Dictionary <string, TObject> dictionary, string nameObject, ILogger logger, bool exception = true) where TObject : NamedObject { dictionary = Check.Object(dictionary, logger); nameObject = Check.Name(nameObject, logger); bool notContains = !dictionary.ContainsKey(nameObject); if ((exception) && (!notContains)) { object[] args = { nameObject }; string message = "Element of type \"{0}\" already exists"; var ex = new KeyNotFoundException(message: String.Format(message, args)); logger?.LogError(ex, message, args); throw ex; } return(notContains); }
internal void SerializeOperationId <TDoc, TCursor>(IO.TagElementStream <TDoc, TCursor, string> s, ref int type, MegaloScriptModelObjectType objType) where TDoc : class where TCursor : class { if (objType == MegaloScriptModelObjectType.Condition && TagElementStreamSerializeFlags.UseConditionTypeNames()) { string name = s.IsReading ? null : Database.Conditions[type].Name; s.StreamAttribute("name", ref name); if (s.IsReading) { Proto.MegaloScriptProtoCondition proto; if (Database.TryGetCondition(name, out proto)) { type = proto.DBID; } else { var ex = new KeyNotFoundException("Not a valid condition name: " + name); s.ThrowReadException(ex); } } } else if (objType == MegaloScriptModelObjectType.Action && TagElementStreamSerializeFlags.UseActionTypeNames()) { string name = s.IsReading ? null : Database.Actions[type].Name; s.StreamAttribute("name", ref name); if (s.IsReading) { Proto.MegaloScriptProtoAction proto; if (Database.TryGetAction(name, out proto)) { type = proto.DBID; } else { var ex = new KeyNotFoundException("Not a valid action name: " + name); s.ThrowReadException(ex); } } } else { s.StreamAttribute("DBID", ref type); } }
public static IList <T> GetDatabase <T>(ILogger logger) { if (_instance == null) { _instance = new InMemoryDatabase(); Seed(logger); } if (_instance._dictionary.Count(where => where.Key == typeof(T)) != 1) { var error = new KeyNotFoundException($"Database not found for type {typeof(T).FullName}."); logger?.LogError(error.Message, error); throw error; } return((IList <T>)_instance._dictionary.SingleOrDefault(x => x.Key == typeof(T)).Value); }
public void LoadingBrokenCountyWillThrowException() { var mapper = new CK3RegionMapper(); var landedTitles = new Title.LandedTitles(); var landedTitlesReader = new BufferedReader( "k_anglia = { d_aquitane = { c_mers_broken = { b_hgy = { province = 69 } } } } \n" ); landedTitles.LoadTitles(landedTitlesReader); const string regionPath = "TestFiles/regions/CK3RegionMapperTests/LoadingBrokenCountyWillThrowException.txt"; void action() => mapper.LoadRegions(landedTitles, regionPath, islandRegionPath); KeyNotFoundException exception = Assert.Throws <KeyNotFoundException>(action); Assert.Equal("Region's test_region county c_mers does not exist!", exception.Message); }
//////////////// public static void GetLatestKnownVersionAsync(Mod mod, Action <Version> on_success, Action <Exception> on_fail) { Action check = delegate() { var mymod = HamstarHelpersMod.Instance; try { if (mymod.ModVersionGet.ModVersions.ContainsKey(mod.Name)) { on_success(mymod.ModVersionGet.ModVersions[mod.Name]); } else { var ke = new KeyNotFoundException("GetLatestKnownVersion - Unrecognized mod " + mod.Name + " (not found on mod browser)"); on_fail(ke); } } catch (Exception e) { on_fail(e); } }; ThreadPool.QueueUserWorkItem(_ => { lock (ModVersionGet.MyLock) { var mymod = HamstarHelpersMod.Instance; if (mymod.ModVersionGet.ModVersions == null) { ModVersionGet.RetrieveLatestKnownVersionsAsync((versions, found) => { if (found) { mymod.ModVersionGet.ModVersions = versions; } check(); }); } else { check(); } } }); //string username = ModMetaDataManager.GetGithubUserName( mod ); //string projname = ModMetaDataManager.GetGithubProjectName( mod ); //string url = "https://api.github.com/repos/" + username + "/" + projname + "/releases"; }
public async Task CreateMembershipDiscountAsync_ShouldFail_WhenMembershipIsNull() { // Arrange var createMembershipDiscount = _fixture.Create <CreateMembershipDiscount>(); createMembershipDiscount.Discount.MaxQuantity = 20; createMembershipDiscount.Discount.MinQuantity = 10; createMembershipDiscount.Discount.Percentage = 14; createMembershipDiscount.Discount.ValidFrom = null; createMembershipDiscount.Discount.ValidUntil = null; var expectedResult = new KeyNotFoundException($"{typeof(Membership)} with id {createMembershipDiscount.MembershipId} was not found"); // Act var result = await Assert.ThrowsAsync <KeyNotFoundException>(async() => await _sut.CreateMembershipDiscountAsync(createMembershipDiscount)); // Assert Assert.Equal(expectedResult.Message, result.Message); }
public async Task AddProductAsync_ShouldFail_WhenProductIsNull() { // Arrange _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); var quantity = _fixture.Create <int>(); var cart = _fixture.Create <Cart>(); var product = _fixture.Create <Product>(); var expectedException = new KeyNotFoundException($"{typeof(Product)} with id {product.Id} was not found"); _cartRepository.GetAsync(cart.Id).Returns(cart); // Act var result = await Assert.ThrowsAsync <KeyNotFoundException>(async() => await _sut.AddProductAsync(cart.Id, product.Id, quantity)); // Assert Assert.Equal(expectedException.Message, result.Message); }
public static bool Contains <TObject>(Dictionary <string, TObject> dictionary, TObject objectRequested, ILogger logger, bool exception = true) where TObject : NamedObject { dictionary = Check.Object(dictionary, logger); objectRequested = Check.Object(objectRequested, logger); bool contains = dictionary.ContainsValue(objectRequested); if ((exception) && (!contains)) { object[] args = { objectRequested.Name }; string message = "Element with name \"{0}\" is not found"; var ex = new KeyNotFoundException(message: String.Format(message, args)); logger?.LogError(ex, message, args); throw ex; } return(contains); }
public bool PurchaseReturn(Purchase purchase) { using (var scope = new TransactionScope()) { var dbPurchase = Repository.GetById(purchase.Id); if (dbPurchase == null) { var exception = new KeyNotFoundException("No item found by this id"); throw exception; } var detailRepository = new BaseRepository <PurchaseDetail>(Repository.Db); foreach (var detail in purchase.PurchaseDetails) { var dbDetail = dbPurchase.PurchaseDetails.FirstOrDefault(x => x.Id == detail.Id); if (dbDetail != null) { dbDetail.CostPricePerUnit = detail.CostPricePerUnit; dbDetail.Quantity = detail.Quantity; dbDetail.CostTotal = detail.CostTotal; this.Repository.Db.SaveChanges(); } else { AddCommonValues(purchase, detail); detail.ShopId = purchase.ShopId; detail.PurchaseId = purchase.Id; detailRepository.Add(detail); } } Repository.Db.SaveChanges(); string purchaseId = dbPurchase.Id; UpdateProductDetail(purchase); this.UpdatePurchaseAmounts(purchaseId); scope.Complete(); } UpdateProductReport(purchase); return(true); }
internal bool TrySavePage(JournalEntity journalEntity, JournalPageEntity page, out Exception exception) { bool result = false; exception = null; if (!journalEntity.Pages.Exists(page)) { return(TryAddPage(journalEntity, page, out exception)); } try { // connecting to, or creating a brand new given journal's DB using (var db = GetInternalStorageContext(journalEntity)) { var id = new BsonValue(page.Id); // looking for page var pageInCollection = db.GetCollection <JournalPageEntity>("JournalPages").FindById(id); if (pageInCollection == null) { exception = new KeyNotFoundException("Page exists in memory, but doesn't exist in the storage in Journal: " + journalEntity.DisplayName); result = false; } // saving a page result = db.GetCollection <JournalPageEntity>("JournalPages").Update(page); // we are good to go } } catch (Exception ex) { // setting our exception exception = ex; result = false; } return(result); }
public override bool Edit(StockTransfer sale) { using (var scope = new TransactionScope()) { BusinessDbContext db = this.Repository.Db as BusinessDbContext; StockTransfer dbSale = db.StockTransfers.Where(x => x.Id == sale.Id).Include(x => x.StockTransferDetails).FirstOrDefault(); if (dbSale == null) { var exception = new KeyNotFoundException("No sale found by this id"); throw exception; } var detailRepository = new BaseRepository <StockTransferDetail>(this.Repository.Db); foreach (var detail in sale.StockTransferDetails) { var dbDetail = dbSale.StockTransferDetails.FirstOrDefault(x => x.Id == detail.Id); if (dbDetail != null) { dbDetail.SalePricePerUnit = detail.SalePricePerUnit; dbDetail.Quantity = detail.Quantity; dbDetail.PriceTotal = detail.PriceTotal; dbDetail.Remarks = detail.Remarks; this.Repository.Db.SaveChanges(); } else { this.AddCommonValues(sale, detail); detail.ShopId = sale.ShopId; detail.StockTransferId = sale.Id; detailRepository.Add(detail); } } dbSale.ProductAmount = sale.ProductAmount; this.Repository.Db.SaveChanges(); scope.Complete(); } return(true); }
// Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new instance of KeyNotFoundException."); try { KeyNotFoundException myException = new KeyNotFoundException(); if (myException == null) { TestLibrary.TestFramework.LogError("001.1", "KeyNotFoundException instance can not create correctly."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); retVal = false; } return retVal; }
private Exception DetermineSecretStoreException(string secretName, IEnumerable <Exception> criticalExceptions) { if (!criticalExceptions.Any()) { _logger.LogError("None of the configured {Count} configured secret providers was able to retrieve the requested secret with name '{SecretName}'", _secretProviders.Count(), secretName); var noneFoundException = new KeyNotFoundException($"None of the {_secretProviders.Count()} configured secret providers was able to retrieve the requested secret with name '{secretName}'"); return(new SecretNotFoundException(secretName, noneFoundException)); } if (criticalExceptions.Count() == 1) { return(criticalExceptions.First()); } return(new AggregateException( $"None of the configured secret providers was able to retrieve the secret with name '{secretName}' while {criticalExceptions.Count()} critical exceptions were thrown", criticalExceptions)); }
public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception error) { var response = context.Response; response.ContentType = "application/json"; response.StatusCode = error switch { ApplicationException e => (int)HttpStatusCode.BadRequest, KeyNotFoundException e => (int)HttpStatusCode.NotFound, _ => (int)HttpStatusCode.InternalServerError, }; var result = JsonSerializer.Serialize(new { message = error?.Message }); await response.WriteAsync(result); } }