Skip to content

Commit ebb91df

Browse files
Adds support for binary response to GenericRandomErrorPlugin (#234)
1 parent b24c730 commit ebb91df

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

msgraph-developer-proxy-plugins/RandomErrors/GenericRandomErrorPlugin.cs

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,29 @@ private void UpdateProxyResponse(ProxyRequestArgs ev, GenericErrorResponse error
9090
headers.Add(new HttpHeader("Retry-After", retryAfterInSeconds.ToString()));
9191
}
9292

93-
string body = error.Body is null ? string.Empty : JsonSerializer.Serialize(error.Body);
94-
_logger?.LogRequest(new[] { $"{error.StatusCode} {((HttpStatusCode)error.StatusCode).ToString()}" }, MessageType.Chaos, new LoggingContext(ev.Session));
95-
session.GenericResponse(body ?? string.Empty, (HttpStatusCode)error.StatusCode, headers);
93+
var statusCode = (HttpStatusCode)error.StatusCode;
94+
var body = error.Body is null ? string.Empty : JsonSerializer.Serialize(error.Body);
95+
// we get a JSON string so need to start with the opening quote
96+
if (body.StartsWith("\"@")) {
97+
// we've got a mock body starting with @-token which means we're sending
98+
// a response from a file on disk
99+
// if we can read the file, we can immediately send the response and
100+
// skip the rest of the logic in this method
101+
// remove the surrounding quotes and the @-token
102+
var filePath = Path.Combine(Directory.GetCurrentDirectory(), body.Trim('"').Substring(1));
103+
if (!File.Exists(filePath)) {
104+
_logger?.LogError($"File {filePath} not found. Serving file path in the mock response");
105+
session.GenericResponse(body, statusCode, headers);
106+
}
107+
else {
108+
var bodyBytes = File.ReadAllBytes(filePath);
109+
session.GenericResponse(bodyBytes, statusCode, headers);
110+
}
111+
}
112+
else {
113+
session.GenericResponse(body, statusCode, headers);
114+
}
115+
_logger?.LogRequest(new[] { $"{error.StatusCode} {statusCode.ToString()}" }, MessageType.Chaos, new LoggingContext(ev.Session));
96116
}
97117

98118
private string BuildThrottleKey(Request r) => $"{r.Method}-{r.Url}";

0 commit comments

Comments
 (0)