使用 RestSharp,当断言失败时,会将响应代码更改为 409

问题描述 投票:0回答:1

我有提交 POST 请求并返回标头、正文和 200 状态代码的代码。我断言状态代码以确保它返回 200/204/302,然后解析响应正文和数据标头。然后,我对从响应头/正文解析的返回值进行断言,如果失败,则会在 NUnit 测试中将响应状态代码更改为 409(即使它已经对其断言并通过,因为它是 200)。这是为什么?我该如何解决这个问题?

我正在使用最新的 RestSharp 和 C# 库。运行最新的 NUnit 3 版本。

调用我的代码并对解析/返回的数据进行断言:

retvals = Common.restAPI(RestSharp.Method.Post, baseUrl, authEP, authType, get_cfg("CustomerApplication:procFinance:ep", new string[1] { "{app_id}" }, new string[1] { app_id }), get_cfg("CustomerApplication:procFinance:body", new string[2] { "{app_id}", "{amount}" }, new string[2] { app_id, amount.ToString() }), pid, new string[1] { "response.show_error" }, token: auth_token);

Assert.AreEqual("False", retvals[0]);

我调用的restAPI方法内部的代码:

        /// <summary>
        /// Main rest call method to execute a test.
        /// </summary>
        /// <param name="method">RestSharp.Method.Get, RestSharp.Method.Post, etc.</param>
        /// <param name="baseUrl">The base URL of the API</param>
        /// <param name="authRes">If authType is not AuthType.None, then this is used to authenticate before submitting the REST call.</param>
        /// <param name="authType">Type of authentication used (New: Uses login/password and authRes to get bearer token and add it as an auth header, Old: Uses the getOldKey method and adds it as a 'x-api-key' header, Hash: Passes in an already generated bearer token and adds it as an auth header, None: No auth needed and authRes parameter is ignored)</param>
        /// <param name="resource">The API endpoint under test</param>
        /// <param name="body">[Optional] Body of the API endpoint to send</param>
        /// <param name="pid">[Optional] PartnerID value to create requests, authType.Old authentication, etc.</param>
        /// <param name="retval">[Optional] Values to search for and return from the response body and headers (searches body first and if value not found also searches headers). Can search in nested JObjects/JArrays by sending 'val1.val2' format. If no value passed, defaults to returning all headers and body via string array.</param>
        /// <param name="username">[Optional] Used with authType.New for authentication</param>
        /// <param name="password">[Optional] Used with authType.New for authentication</param>
        /// <param name="token">[Optional] Used with authType.Hash for authentication</param>
        /// <param name="status_code">[Optional] Default expected response status code is '200, 204, 302'. If you want to override this, send an alternate code</param>
        /// <param name="headerNamePipeVal">[Optional] If a custom header is needed, send a string with header name and header value delimited with a '|' (myCustomHeader|myCustomHeaderValue)</param>
        /// <param name="retvalAsserts">[Optional] If assertions need to be done within the RestAPI method, pass in the same size string array here compared with the retvals string array (if retvals has an array with size of 3 but only want to assert on the second item, pass in to retvalAsserts: new string[3] { "", "my value to assert", "" }).</param>
        /// <returns>String array of values found from the retval parameter.</returns>
        public string[] restAPI(Method method, string baseUrl, string authRes, AuthType authType, string resource, string body = "", string pid = "", string[] retval = null, string username = "", string password = "", string token = "", int status_code = 0, string headerNamePipeVal = "", string[] retvalAsserts = null)
        {
            string[] retvals = null;

            //create new rest client instance
            RestClient client = new RestClient();

            //if 'New' or 'Hash' authType, this will add the appropriate bearer token header to the request
            client = GetAuthClient(client, baseUrl, resource, authType, authRes, username, password, token);

            //create the request with the resource point
            RestRequest request = new RestRequest(resource);

            if (authType == AuthType.Old)
            {
                request.AddHeader("x-api-token", GetXAPIKey(baseUrl, authRes, pid));
            }

            request.AddHeader("Accept", "*/*");

            //add a custom header
            if (headerNamePipeVal != "")
            {
                string[] head = headerNamePipeVal.Split("|");
                request.AddHeader(head[0], head[1]);
            }

            switch (method)
            {
                case Method.Post:
                    //always add this header in case the request contains a jpg upload (so far, hasn't hurt any of the other post requests)
                    request.AddHeader("x-content-type", "image/jpg");

                    //add the post body
                    request.AddParameter("text/json", body, ParameterType.RequestBody);
                    break;
                case Method.Put:
                    //always add this header in case the request contains a jpg upload (so far, hasn't hurt any of the other put requests)
                    request.AddHeader("x-content-type", "image/jpg");

                    //add the post body
                    request.AddParameter("text/json", body, ParameterType.RequestBody);
                    break;
            }

            TestContext.Out.WriteLine($"Request baseUrl: {baseUrl}");
            TestContext.Out.WriteLine($"Request resource: {resource}");
            TestContext.Out.WriteLine($"Request method: {method}");
            TestContext.Out.WriteLine($"Request body: {body}");
            TestContext.Out.WriteLine("");
            
            //execute the request
            RestResponse response = client.Execute(request, method);
            
            TestContext.Out.WriteLine($"Response code: {(int)response.StatusCode}");
            TestContext.Out.WriteLine($"Response code description: {response.StatusDescription}");
            TestContext.Out.WriteLine($"Response status: {response.ResponseStatus}");
            TestContext.Out.WriteLine($"Response headers: {JsonConvert.SerializeObject(response.Headers)}");
            TestContext.Out.WriteLine($"Response body: {response.Content}");
            TestContext.Out.WriteLine("");

            //throw exception if both return values and return value assertions don't have the same length
            if (retval != null && retvalAsserts != null)
            {
                if (retval.Length != retvalAsserts.Length)
                {
                    throw new Exception("Return value count and return value assertion count need to match.");
                }
            }

            Assert.Multiple(() =>
            {
                //verify return code is 200, 204 or 302 (OK, No Content or Redirect) if no return code specified, otherwise assert on the one specified
                if (status_code == 0)
                {
                    CollectionAssert.Contains(new[] { 200, 204, 302 }, (int)response.StatusCode);
                }
                else
                {
                    Assert.AreEqual(status_code, (int)response.StatusCode);
                }

                int retvalAssertsCount = 0;

                //parse out the specified return codes
                retvals = parseResponse(response, retval);

                //if both return values and return value assertions are not null, assert on each one that does not have a null return value assertion
                if (retval != null && retvalAsserts != null)
                {
                    foreach (string rv in retvals)
                    {
                        if (retvalAsserts[retvalAssertsCount] != "")
                        {
                            Assert.AreEqual(retvalAsserts[retvalAssertsCount], rv);
                        }

                        retvalAssertsCount++;
                    }
                }
            });

            return retvals;
        }

如果断言通过编写为 'Assert.AreEqual("False", retvals[0]);',它看起来像这样:

如果我更改 'Assert.AreEqual("False", retvals[0]);'到 'Assert.AreEqual("True", retvals[0]);'所以它失败了,响应如下所示:

c# restsharp nunit-3.0
1个回答
0
投票

这是由我测试时的 NUnit 重试引起的。第一次失败是正确的,但第二次重试时,我们的 AUT 返回 409(这是正确的)。

© www.soinside.com 2019 - 2024. All rights reserved.