Skip to content

Commit ef8c482

Browse files
committed
get an initial draft of this working
1 parent 0f87d78 commit ef8c482

7 files changed

Lines changed: 222 additions & 208 deletions

File tree

‎HTTPSpec.md‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,11 @@ Assertions are specified in the final block of a request, and begin with `//#`.
7070
```
7171
GET https://api.example.com/users/123
7272
73-
> assert
74-
status == 200
75-
header["Content-Type"] == "application/json"
76-
body.id == 123
77-
body.name == "John Doe"
78-
body.email contains "@example.com"
79-
> endassert
73+
//# status == 200
74+
//# header["Content-Type"] == "application/json"
75+
//# body.id == 123
76+
//# body.name == "John Doe"
77+
//# body.email contains "@example.com"
8078
```
8179

8280
### 4.2 JSON Path

‎src/client/http_client.zig‎

Lines changed: 0 additions & 159 deletions
This file was deleted.

‎src/httpfile/assertion_checker.zig‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
const std = @import("std");
2+
const http = std.http;
3+
const HttpParser = @import("./parser.zig");
4+
const Client = @import("./http_client.zig");
5+
6+
pub fn check(request: *HttpParser.HttpRequest, response: Client.HttpResponse) !void {
7+
const stderr = std.io.getStdErr().writer();
8+
for (request.assertions.items) |assertion| {
9+
switch (assertion.assertion_type) {
10+
.equal => {
11+
if (std.ascii.eqlIgnoreCase(assertion.key, "status")) {
12+
const assert_status_code = try std.fmt.parseInt(u16, assertion.value, 10);
13+
if (response.status != try std.meta.intToEnum(http.Status, assert_status_code)) {
14+
stderr.print("[Fail] Expected status code {d}, got {d}\n", .{ assert_status_code, @intFromEnum(response.status.?) }) catch return error.StatusCodeMismatch;
15+
return error.StatusCodeMismatch;
16+
}
17+
} else if (std.ascii.eqlIgnoreCase(assertion.key, "body")) {
18+
if (!std.mem.eql(u8, response.body, assertion.value)) {
19+
stderr.print("[Fail] Expected body content \"{s}\", got \"{s}\"\n", .{ assertion.value, response.body }) catch return error.BodyContentMismatch;
20+
return error.BodyContentMismatch;
21+
}
22+
} else if (std.mem.startsWith(u8, assertion.key, "header[\"")) {
23+
// Extract the header name from the assertion key
24+
const header_name = assertion.key[8 .. assertion.key.len - 2];
25+
26+
const actual_value = response.headers.get(header_name);
27+
if (actual_value == null or !std.ascii.eqlIgnoreCase(actual_value.?, assertion.value)) {
28+
stderr.print("[Fail] Expected header \"{s}\" to be \"{s}\", got \"{s}\"\n", .{ header_name, assertion.value, actual_value orelse "null" }) catch return error.HeaderMismatch;
29+
return error.HeaderMismatch;
30+
}
31+
} else {
32+
stderr.print("[Fail] Invalid assertion key: {s}\n", .{assertion.key}) catch return error.InvalidAssertionKey;
33+
return error.InvalidAssertionKey;
34+
}
35+
},
36+
// .header => {
37+
// // assertion.key is header[""] so we need to
38+
// // parse it out of the quotes
39+
// const tokens = std.mem.splitScalar(u8, assertion.key, '\"');
40+
// const expected_header = tokens.next() orelse return error.InvalidHeaderFormat;
41+
// if (expected_header.len != 2) {
42+
// return error.InvalidHeaderFormat;
43+
// }
44+
// const actual_value = response.headers.get(expected_header);
45+
// if (actual_value == null or actual_value.* != expected_header.value) {
46+
// return error.HeaderMismatch;
47+
// }
48+
// },
49+
.contains => {
50+
if (std.ascii.eqlIgnoreCase(assertion.key, "status")) {
51+
var status_buf: [3]u8 = undefined;
52+
const status_code = @intFromEnum(response.status.?); // .? if status is optional
53+
const status_str = std.fmt.bufPrint(&status_buf, "{}", .{status_code}) catch return error.StatusCodeFormat;
54+
if (std.mem.indexOf(u8, status_str, assertion.value) == null) {
55+
stderr.print("[Fail] Expected status code to contain \"{s}\", got \"{s}\"\n", .{ assertion.value, status_str }) catch return error.StatusCodeNotContains;
56+
return error.StatusCodeNotContains;
57+
}
58+
} else if (std.ascii.eqlIgnoreCase(assertion.key, "body")) {
59+
if (std.mem.indexOf(u8, response.body, assertion.value) == null) {
60+
stderr.print("[Fail] Expected body content to NOT contain \"{s}\", got \"{s}\"\n", .{ assertion.value, response.body }) catch return error.BodyContentNotContains;
61+
return error.BodyContentNotContains;
62+
}
63+
} else {
64+
stderr.print("[Fail] Invalid assertion key for contains: {s}\n", .{assertion.key}) catch return error.InvalidAssertionKey;
65+
return error.InvalidAssertionKey;
66+
}
67+
},
68+
else => {},
69+
}
70+
}
71+
}
72+
73+
test "HttpParser parses assertions" {
74+
const allocator = std.testing.allocator;
75+
76+
var assertions = std.ArrayList(HttpParser.Assertion).init(allocator);
77+
defer assertions.deinit();
78+
79+
try assertions.append(HttpParser.Assertion{
80+
.key = "status",
81+
.value = "200",
82+
.assertion_type = .starts_with,
83+
});
84+
85+
try assertions.append(HttpParser.Assertion{
86+
.key = "body",
87+
.value = "body content",
88+
.assertion_type = .contains,
89+
});
90+
91+
try assertions.append(HttpParser.Assertion{
92+
.key = "body",
93+
.value = "Response body content",
94+
.assertion_type = .equal,
95+
});
96+
97+
// TODO: This should also work with header[\"Content-Type\"] as the key
98+
try assertions.append(HttpParser.Assertion{
99+
.key = "header[\"content-type\"]",
100+
.value = "application/json",
101+
.assertion_type = .equal,
102+
});
103+
104+
const request = HttpParser.HttpRequest{
105+
.method = .GET,
106+
.url = "https://api.example.com",
107+
.headers = std.ArrayList(http.Header).init(allocator),
108+
.assertions = assertions,
109+
.body = null,
110+
};
111+
112+
var response_headers = std.StringHashMap([]const u8).init(allocator);
113+
try response_headers.put("content-type", "application/json");
114+
defer response_headers.deinit();
115+
116+
const body = try allocator.dupe(u8, "Response body content");
117+
defer allocator.free(body);
118+
const response = Client.HttpResponse{
119+
.status = http.Status.ok,
120+
.headers = response_headers,
121+
.body = body,
122+
.allocator = allocator,
123+
};
124+
125+
try check(request, response);
126+
}

‎src/httpfile/http_client.zig‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,25 @@ const Uri = std.Uri;
66
const httpfiles = @import("./parser.zig");
77

88
pub const HttpResponse = struct {
9-
status_code: ?http.Status,
10-
headers: ArrayList(http.Header),
9+
status: ?http.Status,
10+
headers: std.StringHashMap([]const u8),
1111
body: []u8,
1212
allocator: Allocator,
1313

1414
pub fn init(allocator: Allocator) HttpResponse {
1515
return .{
16-
.status_code = null,
17-
.headers = ArrayList(http.Header).init(allocator),
16+
.status = null,
17+
.headers = std.StringHashMap([]const u8).init(allocator),
1818
.body = &[_]u8{},
1919
.allocator = allocator,
2020
};
2121
}
2222

2323
pub fn deinit(self: *HttpResponse) void {
24-
for (self.headers.items) |header| {
25-
self.allocator.free(header.name);
26-
self.allocator.free(header.value);
24+
var headers = self.headers.iterator();
25+
while (headers.next()) |header| {
26+
self.allocator.free(header.value_ptr.*);
27+
self.allocator.free(header.key_ptr.*);
2728
}
2829
self.headers.deinit();
2930
if (self.body.len > 0) {
@@ -53,7 +54,6 @@ pub const HttpClient = struct {
5354
}
5455

5556
// Parse the URL
56-
std.debug.print("{s}", .{request.url});
5757
const uri = try Uri.parse(request.url);
5858

5959
var server_header_buf: [4096]u8 = undefined;
@@ -87,14 +87,14 @@ pub const HttpClient = struct {
8787

8888
// Read the response
8989
var response = HttpResponse.init(self.allocator);
90-
response.status_code = req.response.status;
90+
response.status = req.response.status;
9191

9292
// Copy response headers
9393
var header_iterator = req.response.iterateHeaders();
9494
while (header_iterator.next()) |header| {
9595
const name = try self.allocator.dupe(u8, header.name);
9696
const value = try self.allocator.dupe(u8, header.value);
97-
try response.headers.append(.{ .name = name, .value = value });
97+
try response.headers.put(name, value);
9898
}
9999

100100
// Read response body
@@ -125,7 +125,7 @@ pub const HttpClient = struct {
125125

126126
// Utility function to print response details
127127
pub fn printResponse(response: *const HttpResponse) void {
128-
std.debug.print("Status: {d}\n", .{response.status_code});
128+
std.debug.print("Status: {d}\n", .{response.status});
129129
std.debug.print("Headers:\n");
130130
for (response.headers.items) |header| {
131131
std.debug.print(" {s}: {s}\n", .{ header.name, header.value });
@@ -156,5 +156,5 @@ test "HttpClient basic functionality" {
156156
defer response.deinit();
157157

158158
// Check that we got a 200 status
159-
try std.testing.expectEqual(http.Status.ok, response.status_code);
159+
try std.testing.expectEqual(http.Status.ok, response.status.?);
160160
}

0 commit comments

Comments
 (0)