public static T False <T>( T value, Func <T, bool> condition, Exception exception) { False(NotNull(condition)(value), NotNull(exception)); return(value); }
public static T True <T>( T value, Func <T, bool> condition, string?paramName = null, string?message = IsNotTrueMessage) { True(NotNull(condition)(value), paramName, message); return(value); }
public void TestImplicitWrap() { Foo foo = new Foo(); NotNull <Foo> notNull = foo; Assert.AreEqual(foo, notNull.Value); }
public void TestGetValue() { Foo foo = new Foo(); NotNull <Foo> notNull = new NotNull <Foo>(foo); Assert.AreEqual(foo, notNull.Value); }
public void ValueShouldThrowExceptionGivenNullScalar() { Scalar <object> scalar = new NotNull <object>(null); Action action = () => scalar.Value(); action.ShouldThrow <Exception>().WithMessage("NULL instead of valid scalar"); }
public override void AfterDamage(NotNull <Action> action, NotNull <Hit> hit) { // let the base handle elements base.AfterDamage(action, hit); //### bob: handle sustains and a chance to resist? // handle the flags TryDrain(action, hit.Value.Attack, Stats.Strength, "You feel weak."); TryDrain(action, hit.Value.Attack, Stats.Agility, "You feel clumsy."); TryDrain(action, hit.Value.Attack, Stats.Stamina, "You feel tired."); TryDrain(action, hit.Value.Attack, Stats.Will, "Your conviction falters."); TryDrain(action, hit.Value.Attack, Stats.Intellect, "You feel stupid."); TryDrain(action, hit.Value.Attack, Stats.Charisma, "You feel ugly."); // drain experience if (hit.Value.Attack.Flags.Has("drain:experience")) { // chance to resist if (Stats.Will.ResistDrain()) { action.Value.Log(LogType.Resist, this, "{possessive} will sustain[s] {pronoun}."); } else { // lower by 1% - 5% float percent = Rng.Float(0.01f, 0.05f); action.Value.Log(LogType.BadState, this, "{subject} feel[s] {possessive} life draining away."); LoseExperience(action.Value, Experience.Current * percent); } } }
public void EqualityOperators() { const string @string = "Which is the bigger number, five or one?"; const string otherString = "Our purpose died with the Mad King."; string nullString = null; NotNull <string> notNull = @string; NotNull <string> otherNotNull = otherString; // ReSharper disable ExpressionIsAlwaysNull (notNull == @string).Should().BeTrue(); (@string == notNull).Should().BeTrue(); (notNull == otherString).Should().BeFalse(); (otherString == notNull).Should().BeFalse(); (notNull == otherNotNull).Should().BeFalse(); (notNull == nullString).Should().BeFalse(); (nullString == notNull).Should().BeFalse(); (notNull != @string).Should().BeFalse(); (@string != notNull).Should().BeFalse(); (notNull != otherString).Should().BeTrue(); (otherString != notNull).Should().BeTrue(); (notNull != otherNotNull).Should().BeTrue(); (notNull != nullString).Should().BeTrue(); (nullString != notNull).Should().BeTrue(); // ReSharper restore ExpressionIsAlwaysNull }
void Start() { // Without exceptions it doesn't make sense Assert.raiseExceptions = true; // Works as usual var validObj1 = new NotNull <SomeClass>(new SomeClass("str")); SomeMethod(validObj1); // Alternative syntax var validObj2 = new SomeClass("str").AsNotNull(); SomeMethod(validObj2); // In this case we get exception when creating instance try { NotNull <SomeClass> invalidObj = new NotNull <SomeClass>(null); SomeMethod(invalidObj); } catch (Exception e) { Debug.LogError(e); } // In this case we get exception when getting value try { NotNull <SomeClass> invalidObj = default(NotNull <SomeClass>); SomeMethod(invalidObj); } catch (Exception e) { Debug.LogError(e); } }
public void ShouldThrowExceptionForNullText() { Text notNull = new NotNull(null); Action action = () => notNull.String(); action.ShouldThrowExactly <Exception>().WithMessage("NULL instead of a valid text"); }
/// <summary> /// Gets the quantity of the given item that can be stacked with the current /// equipment. /// </summary> /// <param name="item">The Item being stacked.</param> /// <returns>The amount of the Item that can be stacked, or zero if the /// Item is not stackable.</returns> public int GetStackCount(NotNull <Item> item) { // only handle stackable items if (!CanStack(item)) { return(0); } for (int i = 0; i < Count; i++) { if (mCategories[i] == item.Value.Type.Category) { // not merging stacks, so can stack the whole thing if ((mItems[i] == null) || !mItems[i].CanStack(item)) { return(item.Value.Quantity); } //### bob: hackish, -1 = stack is full if (mItems[i].Quantity == Item.MaxQuantity) { return(-1); } // can stack, so just make sure the stack doesn't get too big return(Math.Min(Item.MaxQuantity - mItems[i].Quantity, item.Value.Quantity)); } } throw new ArgumentException("Category not found."); }
public void EqualsWithDifferentInstances(string first, string second, bool expected) { var firstNotNull = new NotNull <string>(first); var secondNotNull = new NotNull <string>(second); firstNotNull.Equals(secondNotNull).Should().Be(expected); }
private static void Process <T> ( NotNull <IBlockingQueue <HierarchyElement <T> > > queue, NotNull <Func <T, CancellationToken, IEnumerable <T> > > action, CancellationToken cancellationToken, NotNull <SearchTaskOptions> options ) { var actions = new Action[options.Value.MaxDegreeOfParallelism]; for (var i = 0; i < actions.Length; i++) { actions[i] = async() => { try { await ExecuteTask ( queue, options.Value.DequeueWaitTimeout, action, cancellationToken ); } catch (OperationCanceledException) { // It's just cancelling, no errors. } }; } ParallelTask .StartNew(actions) .Wait(CancellationToken.None); }
/// <summary> /// /// </summary> /// <param name="fileWriter"></param> /// <param name="optimizedContentLengthBeforeMakeStream">Не обязателен, но при его задании чтение Length не будет приводить к созданию стрима с предварительной подготовкой</param> public FileContentProvider(FileWriterDelegate fileWriter, ContentLengthDelegate optimizedContentLengthBeforeMakeStream = null) { NotNull.CheckArgument(() => fileWriter); _fileWriter = fileWriter; _optimizedContentLengthBeforeMakeStream = optimizedContentLengthBeforeMakeStream; }
/// <summary> /// /// </summary> /// <param name="streamWriter"></param> /// <param name="optimizedContentLengthBeforeMakeStream">Не обязателен, но при его задании чтение Length не будет приводить к созданию стрима с предварительной подготовкой</param> public ContentProviderToStreamWritable(StreamWriterDelegate streamWriter, ContentLengthDelegate optimizedContentLengthBeforeMakeStream = null) { NotNull.CheckArgument(() => streamWriter); _streamWriter = streamWriter; _optimizedContentLengthBeforeMakeStream = optimizedContentLengthBeforeMakeStream; }
public static async Task StartNew <T> ( IEnumerable <T> initialItems, Func <T, CancellationToken, IEnumerable <T> > action, CancellationToken cancellationToken, SearchTaskOptions options = null ) { var notNullAction = Argument.IsNotNull(action, nameof(action)); var notNullInitialItems = Argument.IsNotNull(initialItems, nameof(initialItems)); var items = notNullInitialItems.Value.ToArray(); if (items.Length == 0) { throw new ArgumentException(@"Initial items collection cannot be empty", nameof(initialItems)); } var queueOptions = NotNull <SearchTaskOptions> .Create(options ?? new SearchTaskOptions()); var queue = NotNull <IBlockingQueue <HierarchyElement <T> > > .Create ( new HierarchicalLimitedBlockingQueue <T>(items, queueOptions.Value.MaxQueueLength, queueOptions.Value.MaxHierarchyDepth) ); await Task.Run ( () => { Process(queue, notNullAction, cancellationToken, queueOptions); }, cancellationToken ); }
public void NotNullMakeOptionalMake() { var optional = NotNull.MakeOptional("Foo"); Assert.IsTrue(optional.HasValue); Assert.AreEqual("Foo", optional.Get().Item); }
public void ShouldReturnInputAsString() { Text text = new TextOf("val"); Text notNull = new NotNull(text); notNull.String().Should().Be("val"); }
/// <summary> /// To be used with IfNull. This method is invoked in case the value checked by IsNull actually is not null. /// </summary> /// <param name="notnull">Internal use.</param> /// <param name="action">Action to be executed in case the value is null.</param> public static void Else <T>(this NotNull <T> notnull, Action <T> action) { if (notnull != null) { action.Invoke(notnull.Value); } }
public ArgumentBuilder AddArgument(string arg) { Argument.IsNotEmpty(arg, @"arg"); _stringBuilder.AppendFormat(" {0}", EscapeString(NotNull.Wrap(arg))); return(this); }
public void Drop(NotNull <Item> item) { int quantity = PromptForItemQuantity(item, item.Value.Quantity, item.Value.Quantity); mGame.Hero.SetNextAction(new DropAction(mGame.Hero, item, quantity)); ProcessGame(); }
public void NotNullCastItemTest() { NotNull <string> notNull = "Foo"; Action <string> action = (s) => Assert.AreEqual("Foo", s); action(notNull); }
public void NotEmptyStringConvertsToStringTest() { var expectedValue = new Version(1, 2, 3, 4); var notNullValue = NotNull.Wrap(expectedValue); Assert.AreEqual(expectedValue.ToString(), notNullValue.ToString()); }
/// <summary> /// Creates a new BoltAction starting at the <see cref="Entity"/> and moving in the given <see cref="Direction"/>. /// </summary> public BoltAction(NotNull <Entity> entity, Direction direction) : this(entity, entity.Value.Position + direction.Offset) { if (direction == Direction.None) { throw new ArgumentException("Direction.None is not a valid direction."); } }
public void ShouldThrowExceptionForNullTextValue() { Text text = new TextOf((string)null); Text notNull = new NotNull(text); Action action = () => notNull.String(); action.ShouldThrowExactly <Exception>().WithMessage("NULL instead of a valid result string"); }
public void ValueShouldThrowExceptionGivenValidValue() { object actual = new object(); Scalar <object> scalar = new NotNull <object>(actual); object expected = scalar.Value(); expected.Should().BeSameAs(actual); }
public static async Task StartNew(Action action, int parallelCount) { Argument.IsNotNull(action, nameof(action)); Argument.IsInRange(parallelCount, nameof(parallelCount), 2, int.MaxValue); var actions = NotNull <IEnumerable <Action> > .Create(Enumerable.Repeat(action, parallelCount)); await StartCore(actions); }
public void TestImplicitUnwrap() { Foo foo = new Foo(); NotNull <Foo> notNull = new NotNull <Foo>(foo); Foo unwrap = notNull; Assert.AreEqual(foo, unwrap); }
internal FinallyBlock(NotNull<Action> tryAction) { _tryFunc = () => { tryAction.Value.Invoke(); return true; }; }
public void NotNullEqualsTest() { Assert.IsFalse(NotNull.Make(new T1()).Equals(NotNull.Make(new T1()))); Assert.IsTrue(NotNull.Make("test").Equals(NotNull.Make("test"))); Assert.IsTrue("test".Equals(NotNull.Make("test"))); Assert.IsFalse(NotNull.Make(new T1()).Equals(null)); }
public void NotNullTest() { var obj = new object(); var notNullObj = NotNull <object> .Create(obj); Assert.IsNotNull(notNullObj); Assert.IsNotNull(notNullObj.Value); }
public void ImplicitConvert() { var str = "Data"; NotNull <string> notNull = str.ToNotNull(); string notNullValue = notNull; Assert.AreEqual(str, notNullValue); }
public object this[NotNull] Type key] { get { return null; } set { throw new NotSupportedException(); } }
/// <summary> /// Returns a value from the YafContext Global Instance Variables (Vars) collection. /// </summary> /// <param name = "varName"></param> /// <returns>Value if it's found, null if it doesn't exist.</returns> public object this[NotNull] string varName]
/// <summary> /// The this. /// </summary> /// <param name = "key"> /// The key. /// </param> public object this[NotNull] string key]
public string this[NotNull] string key]
/// <summary> /// Gets panel session state. /// </summary> /// <param name = "panelID">panelID</param> /// <returns></returns> public CollapsiblePanelState this[NotNull] string panelID]
public Command this[NotNull] string name]
/// <summary> /// The this. /// </summary> /// <param name="key"> /// The key. /// </param> public object this[NotNull] object key]
public object this[NotNull] string name]
public IEnumerable<Edge> this[NotNull] Vertex vertex] { get { return _vertices[vertex]; } }
public string this[NotNull] string name]