Subscribe Join 180,000+ subscribers and receive articles from our blog about software quality, testing, QA and security. Subscribe

Send attachment to testrail result fails without warning or error message

HI

I am trying to send attachment to testresults. No error is displayed but uploads are not successful.

I am using the following c# method:

public object SendPost(string uri, object data)
{
return SendRequest(“POST”, uri, data);
}

    private object SendRequest(string method, string uri, object data)
    {
        string url = this.m_url + uri;

        // Create the request object and set the required HTTP method
        // (GET/POST) and headers (content type and basic auth).
        // Create the request object and set the required HTTP method
        // (GET/POST) and headers (content type and basic auth).
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "application/json";
        request.Method = method;

        Console.WriteLine(this.m_user + this.m_password);
        string auth = Convert.ToBase64String(
            Encoding.ASCII.GetBytes(
                String.Format(
                    "{0}:{1}",
                    this.m_user,
                    this.m_password
                )
            )
        );

        request.Headers.Add("Authorization", "Basic " + auth);

        if (method == "POST")
        {
            if (uri.StartsWith("add_attachment"))
            {
                string boundary = String.Format("{0:N}", Guid.NewGuid());
                string filePath = (String)data;

                // Set the http request header \\
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.KeepAlive = true;

                // Form the post data request
                MemoryStream postDataStream = new MemoryStream();
                StreamWriter postDataWriter = new StreamWriter(postDataStream);

                // Include the file details in the post data
                postDataWriter.Write("\r\n--" + boundary + "\r\n");
                postDataWriter.Write("Content-Disposition: form-data; name=\"attachment\";"
                                + "filename=\"{0}\""
                                + "\r\nContent-Type: {1}\r\n\r\n",
                                Path.GetFileName(filePath),
                                Path.GetExtension(filePath));
                Console.WriteLine("Content - Disposition: form - data; name =\"attachment\";"
                                     + "filename=\"{0}\""
                                     + "\r\nContent-Type: {1}\r\n\r\n",
                                Path.GetFileName(filePath),
                                Path.GetExtension(filePath));
                postDataWriter.Flush();

                // Read the file
                FileStream attachmentStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = attachmentStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    postDataStream.Write(buffer, 0, bytesRead);
                }
                attachmentStream.Close();

                postDataWriter.Write("\r\n--" + boundary + "--\r\n");
                postDataWriter.Flush();

                // Set the http request body content length
                request.ContentLength = postDataStream.Length;

                // Dump the post data from the memory stream to the request stream
                using (Stream requestStream = request.GetRequestStream())
                {
                    postDataStream.WriteTo(requestStream);
                    Thread.Sleep(10000);
                }
                postDataStream.Close();
            }
            // For non-attachment requests, add the POST arguments, if any. 
            // We just serialize the passed data object (i.e. a dictionary)
            // and then add it to the request body.
            else if (data != null)
            {
                byte[] block = Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(data)
                );
                request.GetRequestStream().Write(block, 0, block.Length);
            }
        }

        // Execute the actual web request (GET or POST) and record any
        // occurred errors.
        Exception ex = null;
        HttpWebResponse response = null;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (WebException e)
        {
            if (e.Response == null)
            {
                throw;
            }

            response = (HttpWebResponse)e.Response;
            ex = e;
        }

        // Read the response body, if any, and deserialize it from JSON.
        string text = "";
        if (response != null)
        {
            var reader = new StreamReader(
                response.GetResponseStream(),
                Encoding.UTF8
            );

            using (reader)
            {
                text = reader.ReadToEnd();
            }
        }

        JContainer result;
        if (text != "")
        {
            if (text.StartsWith("["))
            {
                result = JArray.Parse(text);
            }
            else
            {
                try
                {
                    result = JObject.Parse(text);
                }
                catch   // Response is not in JSON format
                {
                    throw new APIException(String.Format(
                        "TestRail API returned the following: {0}\n",
                        text));
                }
            }
        }
        else
        {
            result = new JObject();
        }

        // Check for any occurred errors and add additional details to
        // the exception message, if any (e.g. the error message returned
        // by TestRail).
        if (ex != null)
        {
            string error = (string)result["error"];
            if (error != null)
            {
                error = '"' + error + '"';
            }
            else
            {
                error = "No additional error message received";
            }

            throw new APIException(
                String.Format(
                    "TestRail API returned HTTP {0} ({1})",
                    (int)response.StatusCode,
                    error
                )
            );
        }

        return result;
    }

Call:

var postImage = "add_attachment_to_result/" + splitTestRunID[i] + "/" + splitTestCaseID[i];
JObject j = (JObject)TestRailApiClient.SendPost(postImage, "C:\\FileUpload.txt");

non attachment types are successfully posted. Attachments are not successful. tried png and text file.
What went wrong here?