File: HttpAssert.cs

package info (click to toggle)
mono-reference-assemblies 3.12.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 604,240 kB
  • ctags: 625,505
  • sloc: cs: 3,967,741; xml: 2,793,081; ansic: 418,042; java: 60,435; sh: 14,833; makefile: 11,576; sql: 7,956; perl: 1,467; cpp: 1,446; yacc: 1,203; python: 598; asm: 422; sed: 16; php: 1
file content (257 lines) | stat: -rw-r--r-- 10,400 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using Xunit;

namespace Microsoft.TestCommon
{
    /// <summary>
    /// Unit test utility for testing <see cref="HttpResponseMessage"/> instances.
    /// </summary>
    public class HttpAssert
    {
        private const string CommaSeperator = ", ";
        private static readonly HttpAssert singleton = new HttpAssert();

        public static HttpAssert Singleton { get { return singleton; } }

        /// <summary>
        /// Asserts that the expected <see cref="HttpRequestMessage"/> is equal to the actual <see cref="HttpRequestMessage"/>.
        /// </summary>
        /// <param name="expected">The expected <see cref="HttpRequestMessage"/>. Should not be <c>null</c>.</param>
        /// <param name="actual">The actual <see cref="HttpRequestMessage"/>. Should not be <c>null</c>.</param>
        public void Equal(HttpRequestMessage expected, HttpRequestMessage actual)
        {
            Assert.NotNull(expected);
            Assert.NotNull(actual);

            Assert.Equal(expected.Version, actual.Version);
            Equal(expected.Headers, actual.Headers);

            if (expected.Content == null)
            {
                Assert.Null(actual.Content);
            }
            else
            {
                string expectedContent = CleanContentString(expected.Content.ReadAsStringAsync().Result);
                string actualContent = CleanContentString(actual.Content.ReadAsStringAsync().Result);
                Assert.Equal(expectedContent, actualContent);
                Equal(expected.Content.Headers, actual.Content.Headers);
            }
        }

        /// <summary>
        /// Asserts that the expected <see cref="HttpResponseMessage"/> is equal to the actual <see cref="HttpResponseMessage"/>.
        /// </summary>
        /// <param name="expected">The expected <see cref="HttpResponseMessage"/>. Should not be <c>null</c>.</param>
        /// <param name="actual">The actual <see cref="HttpResponseMessage"/>. Should not be <c>null</c>.</param>
        public void Equal(HttpResponseMessage expected, HttpResponseMessage actual)
        {
            Equal(expected, actual, null);
        }

        /// <summary>
        /// Asserts that the expected <see cref="HttpResponseMessage"/> is equal to the actual <see cref="HttpResponseMessage"/>.
        /// </summary>
        /// <param name="expected">The expected <see cref="HttpResponseMessage"/>. Should not be <c>null</c>.</param>
        /// <param name="actual">The actual <see cref="HttpResponseMessage"/>. Should not be <c>null</c>.</param>
        /// <param name="verifyContentCallback">The callback to verify the Content string. If it is null, Assert.Equal will be used. </param>
        public void Equal(HttpResponseMessage expected, HttpResponseMessage actual, Action<string, string> verifyContentStringCallback)
        {
            Assert.NotNull(expected);
            Assert.NotNull(actual);

            Assert.Equal(expected.StatusCode, actual.StatusCode);
            Assert.Equal(expected.ReasonPhrase, actual.ReasonPhrase);
            Assert.Equal(expected.Version, actual.Version);
            Equal(expected.Headers, actual.Headers);

            if (expected.Content == null)
            {
                Assert.Null(actual.Content);
            }
            else
            {
                string expectedContent = CleanContentString(expected.Content.ReadAsStringAsync().Result);
                string actualContent = CleanContentString(actual.Content.ReadAsStringAsync().Result);
                if (verifyContentStringCallback != null)
                {
                    verifyContentStringCallback(expectedContent, actualContent);
                }
                else
                {
                    Assert.Equal(expectedContent, actualContent);
                }
                Equal(expected.Content.Headers, actual.Content.Headers);
            }
        }

        /// <summary>
        /// Asserts that the expected <see cref="HttpHeaders"/> instance is equal to the actual <see cref="actualHeaders"/> instance.
        /// </summary>
        /// <param name="expectedHeaders">The expected <see cref="HttpHeaders"/> instance. Should not be <c>null</c>.</param>
        /// <param name="actualHeaders">The actual <see cref="HttpHeaders"/> instance. Should not be <c>null</c>.</param>
        public void Equal(HttpHeaders expectedHeaders, HttpHeaders actualHeaders)
        {
            Assert.NotNull(expectedHeaders);
            Assert.NotNull(actualHeaders);

            Assert.Equal(expectedHeaders.Count(), actualHeaders.Count());

            foreach (KeyValuePair<string, IEnumerable<string>> expectedHeader in expectedHeaders)
            {
                KeyValuePair<string, IEnumerable<string>> actualHeader = actualHeaders.FirstOrDefault(h => h.Key == expectedHeader.Key);
                Assert.NotNull(actualHeader);

                if (expectedHeader.Key == "Date")
                {
                    HandleDateHeader(expectedHeader.Value.ToArray(), actualHeader.Value.ToArray());
                }
                else
                {
                    string expectedHeaderStr = string.Join(CommaSeperator, expectedHeader.Value);
                    string actualHeaderStr = string.Join(CommaSeperator, actualHeader.Value);
                    Assert.Equal(expectedHeaderStr, actualHeaderStr);
                }
            }
        }

        /// <summary>
        /// Asserts the given <see cref="HttpHeaders"/> contain the given <paramref name="values"/>
        /// for the given <paramref name="name"/>.
        /// </summary>
        /// <param name="headers">The <see cref="HttpHeaders"/> to examine.  It cannot be <c>null</c>.</param>
        /// <param name="name">The name of the header.  It cannot be empty.</param>
        /// <param name="values">The values that must all be present.  It cannot be null.</param>
        public void Contains(HttpHeaders headers, string name, params string[] values)
        {
            Assert.NotNull(headers);
            Assert.False(String.IsNullOrWhiteSpace(name), "Test error: name cannot be empty.");
            Assert.NotNull(values);

            IEnumerable<string> headerValues = null;
            bool foundIt = headers.TryGetValues(name, out headerValues);
            Assert.True(foundIt);

            foreach (string value in values)
            {
                Assert.Contains(value, headerValues);
            }
        }

        public bool IsKnownUnserializableType(Type type, Func<Type, bool> isTypeUnserializableCallback)
        {
            if (isTypeUnserializableCallback != null && isTypeUnserializableCallback(type))
            {
                return true;
            }

            if (type.IsGenericType)
            {
                if (typeof(IEnumerable).IsAssignableFrom(type))
                {
                    if (type.GetMethod("Add") == null)
                    {
                        return true;
                    }
                }

                // Generic type -- recursively analyze generic arguments
                return IsKnownUnserializableType(type.GetGenericArguments()[0], isTypeUnserializableCallback);
            }

            if (type.HasElementType && IsKnownUnserializableType(type.GetElementType(), isTypeUnserializableCallback))
            {
                return true;
            }

            return false;
        }

        public bool IsKnownUnserializable(Type type, object obj, Func<Type, bool> isTypeUnserializableCallback)
        {
            if (IsKnownUnserializableType(type, isTypeUnserializableCallback))
            {
                return true;
            }

            return obj != null && IsKnownUnserializableType(obj.GetType(), isTypeUnserializableCallback);
        }

        public bool IsKnownUnserializable(Type type, object obj)
        {
            return IsKnownUnserializable(type, obj, null);
        }

        public bool CanRoundTrip(Type type)
        {
            if (typeof(TimeSpan).IsAssignableFrom(type))
            {
                return false;
            }

            if (typeof(DateTimeOffset).IsAssignableFrom(type))
            {
                return false;
            }

            if (type.IsGenericType)
            {
                foreach (Type genericParameterType in type.GetGenericArguments())
                {
                    if (!CanRoundTrip(genericParameterType))
                    {
                        return false;
                    }
                }
            }

            if (type.HasElementType)
            {
                return CanRoundTrip(type.GetElementType());
            }

            return true;
        }

        private static void HandleDateHeader(string[] expectedDateHeaderValues, string[] actualDateHeaderValues)
        {
            Assert.Equal(expectedDateHeaderValues.Length, actualDateHeaderValues.Length);

            for (int i = 0; i < expectedDateHeaderValues.Length; i++)
            {
                DateTime expectedDateTime = DateTime.Parse(expectedDateHeaderValues[i]);
                DateTime actualDateTime = DateTime.Parse(actualDateHeaderValues[i]);

                Assert.Equal(expectedDateTime.Year, actualDateTime.Year);
                Assert.Equal(expectedDateTime.Month, actualDateTime.Month);
                Assert.Equal(expectedDateTime.Day, actualDateTime.Day);

                int hourDifference = Math.Abs(actualDateTime.Hour - expectedDateTime.Hour);
                Assert.True(hourDifference <= 1);

                int minuteDifference = Math.Abs(actualDateTime.Minute - expectedDateTime.Minute);
                Assert.True(minuteDifference <= 1);
            }
        }

        private static string CleanContentString(string content)
        {
            Assert.Null(content);

            string cleanedContent = null;

            // remove any port numbers from Uri's
            cleanedContent = Regex.Replace(content, ":\\d+", "");

            return cleanedContent;
        }
    }
}