/// <summary> /// Asserts that it contains the specified status /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { if (context.Response.StatusCode != _expectedStatusCode) { yield return(new AssertionResult(this, $"Expected status code of {_expectedStatusCode}, found {context.Response.StatusCode}")); } }
/// <summary> /// Process the request and returns the response to be asserted. /// </summary> /// <param name="autoAssertWhenAddingRules">When <code>true</code> it will validate the rule as they are added. Default is <code>false</code></param> /// <returns></returns> public RestResponse Response(bool autoAssertWhenAddingRules = false) { var clientBuilder = Configuration.ClientFactory; if (clientBuilder == null) { throw new InvalidOperationException(ErrorMessages.NoClientFactory); } var responseDeserialiser = ResponseDeserialiser ?? Configuration.ResponseDeserialiser; if (responseDeserialiser == null) { throw new InvalidOperationException(ErrorMessages.NoResponseDeserialiser); } using (var client = clientBuilder.Create()) { var context = new AssertionContext { Request = BuildRequest(clientBuilder), Client = client, ResponseDeserialiser = responseDeserialiser }; context.Response = client.ExecuteRequest(context.Request); var response = new RestResponse(this, context, autoAssertWhenAddingRules); return(response); } }
internal RequestContext(AssertionContext context) { Request = context.Request; Client = context.Client; ResponseDeserialiser = context.ResponseDeserialiser; Properties = context.Properties; }
/// <summary> /// Asserts that the response contains the specified headerkey /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { if (!context.Response.Headers.ContainsKey(headerKey)) { yield return(new AssertionResult(this, $"Expected header {headerKey} to exist but was not found")); } }
/// <summary> /// Asserts that the response is not blank. /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { if (string.IsNullOrEmpty(context.Response.Content)) { yield return(new AssertionResult(this, _error)); } }
/// <summary> /// Asserts that the assertion function is true against the header key value. /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { // note we don't validate whether the key exists as there is another assertion rule that does that. if (context.Response.Headers.ContainsKey(headerKey) && !_assertion(context.Response.Headers[headerKey])) { yield return(new AssertionResult(this, $"Expected rule {_assertBody} on header key {headerKey} failed: {_message}")); } }
/// <summary> /// Assets that the expression is true. /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { if (string.IsNullOrEmpty(context.Response.Content)) { yield return(new AssertionResult(this, $"Response was blank and could not assert {_assertBody}")); yield break; } var obj = default(T); Exception error = null; try { obj = context.ResponseDeserialiser.GetResponse <T>(context); } catch (Exception ex) { error = ex; } if (obj == null) { yield return(new AssertionResult(this, $"Failed to deserialise response to {_assertType}")); } if (error != null) { yield return(new AssertionResult(this, string.Format(_expressionException, _assertBody, error))); } if (obj == null || error != null) { yield break; } AssertionResult result = null; try { if (!_func(obj)) { result = new AssertionResult(this, string.Format(_error, _assertBody)); } } catch (Exception ex) { result = new AssertionResult(this, ex.ToString()); } if (result != null) { yield return(result); } }
public void DifferentTestContextsHaveDifferentAssertionContexts() { AssertionContext a = null, b = null; TestStep.RunStep("A", () => a = AssertionContext.CurrentContext); TestStep.RunStep("B", () => b = AssertionContext.CurrentContext); Assert.IsNotNull(a); Assert.IsNotNull(b); Assert.AreNotSame(a, b); }
/// <summary> /// Asserts that the response contains the header and value. /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { if (!context.Response.Headers.ContainsKey(headerKey)) { yield return(new AssertionResult(this, $"Expected header {headerKey} to exist but was not found")); } else if (!context.Response.Headers[headerKey].Contains(headerValue)) { yield return(new AssertionResult(this, $"Expected header {headerKey} to have value {headerValue}, found {string.Join(", ", context.Response.Headers[headerKey])}")); } }
public void Test004() { var ac = new AssertionContext(); ac.Set("abc", "def"); IDisposable s1; using (s1 = ac.Push()) { ac.Set("ghi", "jkl"); var values = ac.GetData(); assert.AreEqual(2, () => values.Count()); assert.EveryUnsorted((new[] { new { Key = "abc", Value = "def", Depth = 0 }, new { Key = "ghi", Value = "jkl", Depth = 1, } }).AsEnumerable(), () => values.Select(kvp => new { Key = kvp.Key, Value = kvp.Value, Depth = kvp.Depth }).AsEnumerable(), (t, a, b) => t.AreEqual(a, b)); } // intentionally dispose s1 ag ain here, this shouldn't cause any problems s1.Dispose(); var values2 = ac.GetData(); assert.AreEqual(1, () => values2.Count()); assert.EveryUnsorted((new[] { new { Key = "abc", Value = "def", Depth = 0 } }).AsEnumerable(), () => values2.Select(kvp => new { Key = kvp.Key, Value = kvp.Value, Depth = kvp.Depth }).AsEnumerable(), (t, a, b) => t.AreEqual(a, b)); }
public override object VisitAssertion([NotNull] AssertionContext context) { Console.WriteLine("visit asssertion " + context.verification().ID()); AssertionExpr assert = new AssertionExpr(context.verification().ID().GetText()); if (context.verification().DEADLOCKFREE() != null) { assert.Type = AssertionExpr.AssertionType.deadlockfree; } else if (context.verification().CIRCULARFREE() != null) { assert.Type = AssertionExpr.AssertionType.circularfree; } else if (context.verification().BOTTLENECKFREE() != null) { assert.Type = AssertionExpr.AssertionType.bottleneckfree; } else if (context.verification().AMBIGUOUSINTERFACEFREE() != null) { assert.Type = AssertionExpr.AssertionType.ambiguousinterface; } else if (context.verification().LAVAFLOWFREE() != null) { assert.Type = AssertionExpr.AssertionType.lavaflow; } else if (context.verification().DECOMPOSITIONFREE() != null) { assert.Type = AssertionExpr.AssertionType.decomposition; } else if (context.verification().POLTERGEISTSFREE() != null) { assert.Type = AssertionExpr.AssertionType.poltergeists; } else if (context.verification().reachexpr() != null) { assert.Type = AssertionExpr.AssertionType.reachability; assert.Expression = context.verification().reachexpr().ID().GetText().Trim(); } else if (context.verification().ltlexpr() != null) { String ltlexpr = context.verification().ltlexpr().GetText(); foreach (var token in context.verification().ltlexpr().children) { Console.WriteLine(" LTL=== " + token.GetText()); } assert.Expression = ltlexpr.Substring(ltlexpr.IndexOf("|=") + 2); assert.ExpressionContext = context.verification().ltlexpr(); assert.Type = AssertionExpr.AssertionType.LTL; } return(assert); }
internal static AssertionContext <TSubject> CreateFromEquivalencyValidationContext(IEquivalencyValidationContext context) { TSubject expectation = (context.Expectation != null) ? (TSubject)context.Expectation : default; var assertionContext = new AssertionContext <TSubject>( context.SelectedMemberInfo, (TSubject)context.Subject, expectation, context.Because, context.BecauseArgs); return(assertionContext); }
/// <summary> /// Asserts the response against the schema object type and generator. /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { JToken obj = JToken.Parse(context.Response.Content); IList <string> messages; if (!obj.IsValid(schema, out messages)) { foreach (var m in messages) { yield return(new AssertionResult(this, m)); } } }
/// <summary> /// Get the response as JToken and caches it /// </summary> /// <param name="context"></param> /// <returns></returns> public object GetResponse(AssertionContext context) { if (context.Properties.ContainsKey(BaseResponseKey)) { return((JToken)context.Properties[BaseResponseKey]); } lock (_responseLock) { if (context.Properties.ContainsKey(BaseResponseKey)) { return((JToken)context.Properties[BaseResponseKey]); } var responseObject = JToken.Parse(context.Response.Content, _loadSettings); context.Properties[BaseResponseKey] = responseObject; return(responseObject); } }
/// <summary> /// Verifies that a block of code does not throw an exception of any type. /// </summary> /// <remarks> /// <para> /// The purpose of this assertion is to improve the readability of tests /// that only verify that an exception was not thrown. Using this assertion /// makes a positive and explicit statement that not throwing an exception /// is itself the primary behavior that is being verified. /// </para> /// </remarks> /// <param name="action">The action delegate to evaluate.</param> /// <param name="messageFormat">The custom assertion message format, or null if none.</param> /// <param name="messageArgs">The custom assertion message arguments, or null if none.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="action"/> is null.</exception> /// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception> public static void DoesNotThrow(Action action, string messageFormat, params object[] messageArgs) { if (action == null) { throw new ArgumentNullException("action"); } AssertionHelper.Verify(() => { try { AssertionContext context = AssertionContext.CurrentContext; if (context != null) { // We will intercept any assertion failure which could occur while the action is run, then report it // as is. The goal is to prevent zealous "Assert.DoesNotThrow" to report the failure a second time. // Basically, a failing assertion inside a DoesNotThrow action does not make Assert.DoesNotThrow // to fail redundantly. See issue 769 (http://code.google.com/p/mb-unit/issues/detail?id=769) AssertionFailure[] failures = context.CaptureFailures(action, AssertionFailureBehavior.Throw, false); if (failures.Length > 0) { return(failures[0]); } } else { action(); } return(null); } catch (Exception actualException) { return(new AssertionFailureBuilder("The block threw an exception but none was expected.") .SetMessage(messageFormat, messageArgs) .AddException(actualException) .ToAssertionFailure()); } }); }
/// <summary> /// Asserts that the function returns true. /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { dynamic obj = null; Exception error = null; try { obj = context.ResponseDeserialiser.GetResponse <dynamic>(context); } catch (Exception ex) { error = ex; } if (obj == null || error != null) { yield return(new AssertionResult(this, $"Failed to deserialise object.")); yield break; } AssertionResult result = null; try { if (!_expression(obj)) { result = new AssertionResult(this, _error); } } catch (Exception ex) { result = new AssertionResult(this, ex.ToString()); } if (result != null) { yield return(result); } }
public void Test003() { var ac = new AssertionContext(); ac.Set("abc", "def"); var values = ac.GetData(); assert.AreEqual(1, () => values.Count()); assert.AreEqual(new { Key = "abc", Value = "def", Depth = 0 }, () => values.Select(kvp => new { Key = kvp.Key, Value = kvp.Value, Depth = kvp.Depth }).Single()); ac.Set("abc", "ghi"); var values2 = ac.GetData(); assert.AreEqual(1, () => values2.Count()); assert.AreEqual(new { Key = "abc", Value = "ghi", Depth = 0 }, () => values2.Select(kvp => new { Key = kvp.Key, Value = kvp.Value, Depth = kvp.Depth }).Single()); }
/// <summary> /// Get the response as a specified type /// </summary> /// <typeparam name="T">type to get the response as</typeparam> /// <param name="context"></param> /// <returns></returns> public T GetResponse <T>(AssertionContext context) { // returns cached value first var key = $"TypedResponse.{typeof(T).FullName}"; if (context.Properties.ContainsKey(key)) { return((T)context.Properties[key]); } // gets the default base response var baseResponse = GetResponse(context) as JToken; if (baseResponse == null) { return(default(T)); } // converts the base response into the object type T result = baseResponse.ToObject <T>(); context.Properties.Add(key, result); return(result); }
public void Test006() { var ac = new AssertionContext(); ac.Set("abc", "def"); IDisposable s2; using (var s1 = ac.Push()) { ac.Set("ghi", "jkl"); s2 = ac.Push(); ac.Set("mno", "pqr"); var values = ac.GetData(); assert.AreEqual(3, () => values.Count()); assert.EveryUnsorted((new[] { new { Key = "abc", Value = "def", Depth = 0, }, new { Key = "ghi", Value = "jkl", Depth = 1, }, new { Key = "mno", Value = "pqr", Depth = 2 } }).AsEnumerable(), () => values.Select(kvp => new { Key = kvp.Key, Value = kvp.Value, Depth = kvp.Depth }).AsEnumerable(), (t, a, b) => t.AreEqual(a, b)); // in this test, we intentionally are not disposing s2 at this point so that when we dispose s1, we can exercise the 'multi-level-rollback functionality // s2.Dispose() } // we now intentionally dispose s2 after it has been 'rolled back' by another and ensure that no errors occur from that either s2.Dispose(); var values2 = ac.GetData(); assert.AreEqual(1, () => values2.Count()); assert.EveryUnsorted((new[] { new { Key = "abc", Value = "def", Depth = 0 } }).AsEnumerable(), () => values2.Select(kvp => new { Key = kvp.Key, Value = kvp.Value, Depth = kvp.Depth }).AsEnumerable(), (t, a, b) => t.AreEqual(a, b)); }
public void Test002() { var ac = new AssertionContext(); assert.Throws <StateException>(() => ac.Pop()); }
public void Test001() { var ac = new AssertionContext(); }
public void CurrentAssertionContextIsAssociatedWithTheCurrentTestContext() { AssertionContext current = AssertionContext.CurrentContext; Assert.AreSame(TestContext.CurrentContext, current.TestContext); }
public void Test005() { var ac = new AssertionContext(); assert.Throws <ArgumentNullException>(() => ac.Set(null, "anyvaluehere")); }
public override IEnumerable <AssertionResult> Assert(AssertionContext context) { // the logic for this assertion rule is not done here, but the in AssertFailure method return(Enumerable.Empty <AssertionResult>()); }
/// <summary> /// Logic of the asssertion against the context /// </summary> /// <param name="context"></param> /// <returns></returns> public abstract IEnumerable <AssertionResult> Assert(AssertionContext context);
/// <summary> /// Constructor used for sequential execution of the tests (specflow style) /// </summary> /// <param name="request">Request that originated this response.</param> /// <param name="context">Assertion context that this response will use</param> /// <param name="autoAssertWhenAddingRule">When <code>true</code> it will validate the rule as they are added. Default is <code>false</code></param> public RestResponse(RestRequest request, AssertionContext context, bool autoAssertWhenAddingRule) { Request = request ?? throw new ArgumentNullException(nameof(request), "No RestRequest has been provided."); Context = context ?? throw new ArgumentNullException(nameof(context), "No AssertionContext has been provided."); AutoAssertWhenAddingRule = autoAssertWhenAddingRule; }
/// <summary> /// Asserts that the function returns true. /// </summary> /// <param name="context"></param> /// <returns></returns> public override IEnumerable <AssertionResult> Assert(AssertionContext context) { if (string.IsNullOrEmpty(context.Response.Content)) { yield return(new AssertionResult(this, $"Response was blank and could not assert as {_assertType}.")); yield break; } var obj = default(T); Exception error = null; try { obj = context.ResponseDeserialiser.GetResponse <T>(context); } catch (Exception ex) { error = ex; } if (obj == null) { yield return(new AssertionResult(this, $"Failed to deserialise response to {_assertType}")); } if (error != null) { yield return(new AssertionResult(this, string.Format(_expressionError, error))); } if (obj == null || error != null) { yield break; } AssertionResult result = null; try { if (!_lambda(obj)) { string errorMessage = _error; // if we have a function to generate the error we use that instead if (_errorMessage != null) { // now we need to be safe - an error here doesn't mean that the whole thing should not necessarily crash try { errorMessage = _errorMessage(obj); } catch (Exception ex) { errorMessage = $"Assertion failed and could not generate the message due to an exception on the custom error message function {ex.Message}"; } } result = new AssertionResult(this, errorMessage); } } catch (Exception ex) { result = new AssertionResult(this, ex.ToString()); } if (result != null) { yield return(result); } }