Compare commits

..

3 Commits

4 changed files with 154 additions and 30 deletions

View File

@ -58,7 +58,6 @@ export async function toFederate(): Promise<[string, ArticleObject][]> {
export function route(router: Router) {
router.use("/:category/:year/:slug/", async (req, res, next) => {
const best = req.accepts(["text/html", "application/activity+json"]);
console.log(best);
if (best === "text/html") {
next();
} else if (best === "application/activity+json") {

56
package-lock.json generated
View File

@ -1091,9 +1091,9 @@
}
},
"globule": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/globule/-/globule-1.2.1.tgz",
"integrity": "sha512-g7QtgWF4uYSL5/dn71WxubOrS7JVGCnFPEnoeChJmBnyR9Mw8nGoEwOgJL/RC2Te0WhbsEUCejfH8SZNJ+adYQ==",
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/globule/-/globule-1.3.0.tgz",
"integrity": "sha512-YlD4kdMqRCQHrhVdonet4TdRtv1/sZKepvoxNT4Nrhrp5HI8XFfc8kFlGlBn2myBo80aGp8Eft259mbcUJhgSg==",
"requires": {
"glob": "~7.1.1",
"lodash": "~4.17.10",
@ -1101,9 +1101,9 @@
}
},
"graceful-fs": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.2.tgz",
"integrity": "sha512-IItsdsea19BoLC7ELy13q1iJFNmd7ofZH5+X/pJr90/nRoPEX0DJo1dHDbgtYWOhJhcCgMDTOw84RZ72q6lB+Q=="
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz",
"integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ=="
},
"har-schema": {
"version": "2.0.0",
@ -1143,9 +1143,9 @@
"integrity": "sha512-Sc28JNQNDzaH6PORtRLMvif9RSn1mYuOoX3omVjnb0+HbpPygU2ALBI0R/wsiqCb4/fcp07Gdo8g+fhtFrQl6A=="
},
"hosted-git-info": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.4.tgz",
"integrity": "sha512-pzXIvANXEFrc5oFFXRMkbLPQ2rXRoDERwDLyrcUxGhaZhgP54BBSl9Oheh7Vv0T090cszWBxPjkQQ5Sq1PbBRQ=="
"version": "2.8.5",
"resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.5.tgz",
"integrity": "sha512-kssjab8CvdXfcXMXVcvsXum4Hwdq9XGtRD3TteMEvEbq0LXyiNQr6AprqKqfeaDXze7SxWvRxdpwE6ku7ikLkg=="
},
"htmlparser2": {
"version": "3.10.1",
@ -1357,7 +1357,7 @@
},
"load-json-file": {
"version": "1.1.0",
"resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz",
"resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz",
"integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=",
"requires": {
"graceful-fs": "^4.1.2",
@ -1494,7 +1494,7 @@
},
"meow": {
"version": "3.7.0",
"resolved": "http://registry.npmjs.org/meow/-/meow-3.7.0.tgz",
"resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz",
"integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=",
"requires": {
"camelcase-keys": "^2.0.0",
@ -1547,7 +1547,7 @@
},
"minimist": {
"version": "1.2.0",
"resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ="
},
"mkdirp": {
@ -1638,15 +1638,15 @@
"dependencies": {
"semver": {
"version": "5.3.0",
"resolved": "http://registry.npmjs.org/semver/-/semver-5.3.0.tgz",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz",
"integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8="
}
}
},
"node-sass": {
"version": "4.12.0",
"resolved": "https://registry.npmjs.org/node-sass/-/node-sass-4.12.0.tgz",
"integrity": "sha512-A1Iv4oN+Iel6EPv77/HddXErL2a+gZ4uBeZUy+a8O35CFYTXhgA8MgLCWBtwpGZdCvTvQ9d+bQxX/QC36GDPpQ==",
"version": "4.13.0",
"resolved": "https://registry.npmjs.org/node-sass/-/node-sass-4.13.0.tgz",
"integrity": "sha512-W1XBrvoJ1dy7VsvTAS5q1V45lREbTlZQqFbiHb3R3OTTCma0XBtuG6xZ6Z4506nR4lmHPTqVRwxT6KgtWC97CA==",
"requires": {
"async-foreach": "^0.1.3",
"chalk": "^1.1.1",
@ -1655,7 +1655,7 @@
"get-stdin": "^4.0.1",
"glob": "^7.0.3",
"in-publish": "^2.0.0",
"lodash": "^4.17.11",
"lodash": "^4.17.15",
"meow": "^3.7.0",
"mkdirp": "^0.5.1",
"nan": "^2.13.2",
@ -1743,12 +1743,12 @@
},
"os-homedir": {
"version": "1.0.2",
"resolved": "http://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz",
"resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz",
"integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M="
},
"os-locale": {
"version": "1.4.0",
"resolved": "http://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz",
"resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz",
"integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=",
"requires": {
"lcid": "^1.0.0"
@ -1756,7 +1756,7 @@
},
"os-tmpdir": {
"version": "1.0.2",
"resolved": "http://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
"resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
"integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ="
},
"osenv": {
@ -1933,7 +1933,7 @@
},
"pify": {
"version": "2.3.0",
"resolved": "http://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
"resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
"integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw="
},
"pinkie": {
@ -2105,7 +2105,7 @@
},
"readable-stream": {
"version": "2.3.6",
"resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz",
"integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==",
"requires": {
"core-util-is": "~1.0.0",
@ -2177,9 +2177,9 @@
"integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE="
},
"resolve": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.12.0.tgz",
"integrity": "sha512-B/dOmuoAik5bKcD6s6nXDCjzUKnaDvdkRyAk6rsmsKLipWj4797iothd7jmmUhWTfinVMU+wc56rYKsit2Qy4w==",
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.14.1.tgz",
"integrity": "sha512-fn5Wobh4cxbLzuHaE+nphztHy43/b++4M6SsGFC2gB8uYwf0C8LcarfCz1un7UTW8OFQg9iNjZ4xpcFVGebDPg==",
"requires": {
"path-parse": "^1.0.6"
}
@ -2353,7 +2353,7 @@
},
"source-map": {
"version": "0.4.4",
"resolved": "http://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz",
"integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=",
"requires": {
"amdefine": ">=0.0.4"
@ -2458,7 +2458,7 @@
},
"string-width": {
"version": "1.0.2",
"resolved": "http://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
"integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
"requires": {
"code-point-at": "^1.0.0",
@ -2873,7 +2873,7 @@
},
"wrap-ansi": {
"version": "2.1.0",
"resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
"integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=",
"requires": {
"string-width": "^1.0.1",

View File

@ -28,7 +28,7 @@
"markdown-it": "^8.4.2",
"markdown-it-footnote": "^3.0.2",
"morgan": "^1.9.1",
"node-sass": "^4.12.0",
"node-sass": "^4.13.0",
"pg": "^7.11.0",
"reflect-metadata": "^0.1.13",
"request": "^2.88.0",

View File

@ -0,0 +1,125 @@
```
metadata.title = "Mocking HTTP Requests for iOS App UI Tests"
metadata.category = "ios"
metadata.date = "2019-12-22 19:12:42 -0400"
metadata.shortDesc = "Integrating a tiny web server into your Xcode UI test target to mock HTTP requests."
metadata.slug = "mock-http-ios-ui-testing"
```
I recently decided to start writing User Interface tests for [Tusker](https://git.shadowfacts.net/shadowfacts/Tusker), my iOS app for Mastodon and Pleroma. But I couldn't just write tests that interacted with an account on any real instance, as that would be far too unpredictable and mean my tests could have an impact on other people. The solution to this problem is, of course, mocking. The core idea is that instead of interacting with external things, your program interacts with mock versions of them, which appear to be their real counterparts, but don't actually perform any of the operations they claim to. This allows for very tight control over what data the application receives, making it much more amenable to testing.
Unfortunately, if you search around, some of the most common solutions on the internet recommend using the environment variables (one of the only ways of sending data directly from the test to the application under test) to insert the mocked response into the app. Meaning, for every API response you need to mock, you would have an environment variable that contains the response data. This isn't a great solution, because it leaves whole code paths untested (everything after the request URL would be generated). It would also mean that there's no way of testing things like what requests are actually made by your app.
The solution to this problem is to actually run a local HTTP server that functions as the API server. This way, the app can communicate with the web server exactly as it would in the normal operating environment, but still have strictly controlled data. Of course, actually doing this isn't quite so straightforward.
<!-- excerpt-end -->
There are a couple of things to think about when looking for a solution: First, in order to meet the requirement of being able to test what API calls are made, the web server needs to be accessible to the test process. Second, we want to avoid modifications to the app if at all possible. There should be as few differences as possible in the app between the testing and production environments. The more differences, the more code that goes untested and the more potential edge-cases.
For the first requirement, there are a pair of handy open-source libraries that we can use to take care of the grunt work of responding to HTTP requests and serving responses. First there's [Embassy](https://github.com/envoy/Embassy), which acts as an asynchronous HTTP server. It handles actually listening for connections on a port and receiving and sending data to them. The other part of this stack is [Ambassador](https://github.com/envoy/Ambassador) which handles routing incoming requests and responding to them in a nicer fashion than just sending strings out.
(Note: both of these libraries are made by a company called Envoy, to which I have no relation.)
So, we need to get these libraries into our project, with the condition that we only want them to be present at test-time, not for release builds (as that would mean shipping unnecessary, extra code). If you're using CocoaPods, it can take care of this for you. But if you're not using a package manager, it's (unsurprisingly) more complicated.
First, the Xcode projects for the two libraries need to be included into the workspace for your app^[I tried to use Xcode 11's new Swift Package Manager support for this, but as far as I can tell, it doesn't provide direct access to the built frameworks produced by the libraries, so this technique isn't possible.]. Next, our app needs to be configured to actually compile against the two frameworks so we can use them in our tests. This is done in the app target of the Xcode project. Both frameworks should be added to the "Frameworks, Libraries, and Embedded Content" section of the General tab for the app target. Once added, the libraries should be set as "Do Not Embed". We don't want Xcode to embed the frameworks, because we'll handle that ourself, conditioned on the current configuration.
To handle that, add a new Run Script phase to the Build Phases section of the target. It'll need input and output files configured for each of our projects:
Input files:
- `${BUILT_PRODUCTS_DIR}/Embassy.framework`
- `${BUILT_PRODUCTS_DIR}/Ambassador.framework`
Output files:
- `${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Embassy.framework`
- `${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Ambassador.framework`
For reference, the `BUILT_PRODUCTS_DIR` environment variable refers to the location in Xcode's DerivedData folder where, as the name suggests, the compiled outputs of the project's targets live. `FRAMEWORKS_FOLDER_PATH` refers to the Frameworks folder inside of our app bundle (e.g. `Tusker.app/Frameworks`).
Configuring input and output files for the Run Script build phase instead of just hard-coding paths in the script itself has the advantage that Xcode will know to re-run our script if the input files change or the output files are missing.
The script our build phase will run is the following:
```bash
if [ "${CONFIGURATION}" == "Debug" ]; then
echo "Embedding ${SCRIPT_INPUT_FILE_0}"
cp -R $SCRIPT_INPUT_FILE_0 $SCRIPT_OUTPUT_FILE_0
codesign --force --verbose --sign $EXPANDED_CODE_SIGN_IDENTITY $SCRIPT_OUTPUT_FILE_0
echo "Embedding ${SCRIPT_INPUT_FILE_1}"
cp -R $SCRIPT_INPUT_FILE_1 $SCRIPT_OUTPUT_FILE_1
codesign --force --verbose --sign $EXPANDED_CODE_SIGN_IDENTITY $SCRIPT_OUTPUT_FILE_1
else
echo "Skipping embedding debug frameworks"
fi
```
If the product configuration is anything other than Debug, the script will simply log a message and do nothing else. If it is in Debug configuration, then we'll take a couple actions for each framework: First, we simply copy the built framework into the app's Frameworks folder. Then, we re-codesign the frameworks in the app so that they're signed with the same identity as our app is. In the script, the input/output file environment variables refer to exactly what they say, the input and output files configured for the build phase in Xcode. The `EXPANDED_CODE_SIGN_IDENTITY` environment variable gives the code signing identity^["Expanded" refers to the format of the identifier. If you look at the `codesign` manpage, it describes several formats that can be used with the `--sign` operation. The expanded format is the forty hexadecimal digit SHA-1 hash of the identity.] that was used to sign the app, which is the same one we want to sign the frameworks with. We also need to give codesign the `--force` option, so that it will overwrite any existing signature on the framework.
Now, if we build our app for debugging and take a look at the frameworks folder inside the app bundle, we can see both `Embassy.framework` and `Ambassador.framework` are present. Switching to the release build and again looking at the product in Finder, neither of those two frameworks are present.
One thing to be aware of is that this setup only excludes the frameworks from being _copied_ in release configurations. They'll still be available at compile-time, so if you're not paying attention, you could accidentally import one of them and start using it, only to encounter a crash in production due to a missing framework. As far as I could tell, there's no way within Xcode of specifying that a framework only be compiled against in certain configurations. If I've missed something and this is indeed possible, please let me know.
With that finally done, we can start setting up the web server so we can test our app. This simplest way to do this is to create a base class for all of our test cases which inherits from `XCTestCase` that will handling setting up the web server. We'll have a method called `setUpWebServer` which is called from `XCTestCase`'s `setUp` method. (In our actual test case, we'll need to be sure to call `super.setUp()` if we override the `setUp` method.)
```swift
var eventLoop: EventLoop!
var router: Router!
var eventLoopThreadCondition: NSCondition!
var eventLoopThread: Thread!
private func setUpWebServer() {
eventLoop = try! SelectorEventLoop(selector: try! KqueueSelector())
router = Router()
server = DefaultHTTPServer(eventLoop: eventLoop, port: 8080, app: router.app)
try! server.start()
eventLoopThreadCondition() = NSCondition()
eventLoopThread = Thread(block: {
self.eventLoop.runForever()
self.eventLoopThreadCondition.lock()
self.eventLoopThreadCondition.signal()
self.eventLoopThreadCondition.unlock()
})
eventLoopThread.start()
}
```
In that method, we'll create an event loop which handles performing asynchronous operations for the web server. We'll also need a `Router` object which will handle HTTP requests and delegate them to other handlers based on the request's path. Next, we'll need the web server itself, an instance of `DefaultHTTPServer`. Once we've got that, we can add our routes to the router and start the web server. Finally, we'll create a separate thread that runs in the background for actually processing web requests. We also override the `tearDown` method and stop the web server, waiting for it to gracefully shut down.
```swift
override func tearDown() {
server.stopAndWait()
eventLoopThreadCondition.lock()
eventLoop.stop()
while eventLoop.running {
if !eventLoopThreadCondition.wait(until: Date(timeIntervalSinceNow: 10)) {
fatalError("Join eventLoopThread timeout")
}
}
}
```
Now that we've finally gotten everything set up, we can test out the web server and make sure everything's working. In a new test case class, we'll extend the base class we created instead of `XCTestCase`, and we'll override the `setUp` method to add a new route:
```swift
override func setUp() {
super.setUp()
router["/hello"] = JSONResponse(handler: { (_) in
return ["Hello": "World"]
})
}
```
To actually test it out, a simple test method that just sleeps for a long time will do the trick:
```swift
func testWebServer() {
sleep(10000000)
}
```
Once we run the test and the simulator's up and runing, we can visit `http://localhost:8080/hello` in a web browser and see the JSON response we defined. Now, actually using the mock web server from the app is a simple matter of adding an environment variable the override the default API host.
One caveat to note with this set up is that, because the web server is running in the same process as the test code (just in a different thread), when the debugger pauses in a test (_not_ in the app itself), any web requests we make to the mock server won't complete until the process is resumed.