-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathunit-testing-preprocessor-macros-in-swift.html
378 lines (328 loc) · 18 KB
/
unit-testing-preprocessor-macros-in-swift.html
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://use.fontawesome.com/afd448ce82.js"></script>
<!-- Meta Tag -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- SEO -->
<meta name="author" content="Bruno Rocha">
<meta name="keywords" content="Software, Engineering, Blog, Posts, iOS, Xcode, Swift, Articles, Tutorials, OBJ-C, Objective-C, Apple">
<meta name="description" content="Macros are used to bring context to a build. Let's see how we can unit test their presence / absence while still keeping your app's unreachable code uncompiled.">
<meta name="title" content="Unit Testing Preprocessor Macros in Swift">
<meta name="url" content="https://swiftrocks.com/unit-testing-preprocessor-macros-in-swift">
<meta name="image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4">
<meta name="copyright" content="Bruno Rocha">
<meta name="robots" content="index,follow">
<meta property="og:title" content="Unit Testing Preprocessor Macros in Swift"/>
<meta property="og:image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4"/>
<meta property="og:description" content="Macros are used to bring context to a build. Let's see how we can unit test their presence / absence while still keeping your app's unreachable code uncompiled."/>
<meta property="og:type" content="website"/>
<meta property="og:url" content="https://swiftrocks.com/unit-testing-preprocessor-macros-in-swift"/>
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://swiftrocks.com/images/thumbs/thumb.jpg?4"/>
<meta name="twitter:image:alt" content="Page Thumbnail"/>
<meta name="twitter:title" content="Unit Testing Preprocessor Macros in Swift"/>
<meta name="twitter:description" content="Macros are used to bring context to a build. Let's see how we can unit test their presence / absence while still keeping your app's unreachable code uncompiled."/>
<meta name="twitter:site" content="@rockbruno_"/>
<!-- Favicon -->
<link rel="icon" type="image/png" href="images/favicon/iconsmall2.png" sizes="32x32" />
<link rel="apple-touch-icon" href="images/favicon/iconsmall2.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+3:ital,wght@0,200..900;1,200..900&display=swap" rel="stylesheet">
<!-- Bootstrap CSS Plugins -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<!-- Prism CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/prism4.css">
<!-- Main CSS Stylesheet -->
<link rel="stylesheet" type="text/css" href="css/style48.css">
<link rel="stylesheet" type="text/css" href="css/sponsor4.css">
<!-- HTML5 shiv and Respond.js support IE8 or Older for HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "https://swiftrocks.com/unit-testing-preprocessor-macros-in-swift"
},
"image": [
"https://swiftrocks.com/images/thumbs/thumb.jpg"
],
"datePublished": "2020-05-05T14:00:00+02:00",
"dateModified": "2020-05-05T14:00:00+02:00",
"author": {
"@type": "Person",
"name": "Bruno Rocha"
},
"publisher": {
"@type": "Organization",
"name": "SwiftRocks",
"logo": {
"@type": "ImageObject",
"url": "https://swiftrocks.com/images/thumbs/thumb.jpg"
}
},
"headline": "Unit Testing Preprocessor Macros in Swift",
"abstract": "Macros are used to bring context to a build. Let's see how we can unit test their presence / absence while still keeping your app's unreachable code uncompiled."
}
</script>
</head>
<body>
<div id="main">
<!-- Blog Header -->
<!-- Blog Post (Right Sidebar) Start -->
<div class="container">
<div class="col-xs-12">
<div class="page-body">
<div class="row">
<div><a href="https://swiftrocks.com">
<img id="logo" class="logo" alt="SwiftRocks" src="images/bg/logo2light.png">
</a>
<div class="menu-large">
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-large">
<div class="menu-item">
<a href="blog">blog</a>
</div>
<div class="menu-item">
<a href="about">about</a>
</div>
<div class="menu-item">
<a href="talks">talks</a>
</div>
<div class="menu-item">
<a href="projects">projects</a>
</div>
<div class="menu-item">
<a href="software-engineering-book-recommendations">book recs</a>
</div>
<div class="menu-item">
<a href="games">game recs</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
</div>
<div class="menu-small">
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-small-1">
<div class="menu-item">
<a href="blog">blog</a>
</div>
<div class="menu-item">
<a href="about">about</a>
</div>
<div class="menu-item">
<a href="talks">talks</a>
</div>
<div class="menu-item">
<a href="projects">projects</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
<div class="menu-arrow-right"></div>
<div class="menu-header menu-header-small-2">
<div class="menu-item">
<a href="software-engineering-book-recommendations">book recs</a>
</div>
<div class="menu-item">
<a href="games">game recs</a>
</div>
<div class="menu-arrow-right-2"></div>
</div>
</div>
</div>
<div class="content-page" id="WRITEIT_DYNAMIC_CONTENT">
<!--WRITEIT_POST_NAME=Unit Testing Preprocessor Macros in Swift-->
<!--WRITEIT_POST_HTML_NAME=unit-testing-preprocessor-macros-in-swift-->
<!--Add here the additional properties that you want each page to possess.-->
<!--These properties can be used to change content in the template page or in the page itself as shown here.-->
<!--Properties must start with 'WRITEIT_POST'.-->
<!--Writeit provides and injects WRITEIT_POST_NAME and WRITEIT_POST_HTML_NAME by default.-->
<!--WRITEIT_POST_SHORT_DESCRIPTION=Macros are used to bring context to a build. Let's see how we can unit test their presence / absence while still keeping your app's unreachable code uncompiled.-->
<!--WRITEIT_POST_SITEMAP_DATE_LAST_MOD=2020-05-05T14:00:00+02:00-->
<!--WRITEIT_POST_SITEMAP_DATE=2020-05-05T14:00:00+02:00-->
<title>Unit Testing Preprocessor Macros in Swift</title>
<div class="blog-post">
<div class="post-title-index">
<h1>Unit Testing Preprocessor Macros in Swift</h1>
</div>
<div class="post-info">
<div class="post-info-text">
Published on 05 May 2020
</div>
</div>
<p><b>Preprocessor macros</b> are used to bring context to a build, allowing you to transform how your app is compiled depending on why it's being built.</p>
<div class="sponsor-article-ad-auto hidden"></div>
<p>In iOS, preprocessors are popularly used to determine which scheme was used to build an app. This allows you to build things such as <b>debug views</b> which are only visible in debug builds, additional logging for non-AppStore builds, and more. My favorite use of macros is using the Factory pattern to return mocked components for XCUITests:</p>
<pre><code>enum HTTPClientFactory {
static func createClient() -> HTTPClient {
#if TESTING
return MockHTTPClient()
#else
return URLSessionHTTPClient()
#end
}
}</code></pre>
<p>Additionally, preprocessor macros have the incredible ability to change how your code is compiled. As the prefix "pre" implies, the value of a macro is tested <b>before</b> your code is compiled, meaning that everything in the "else" block of a preprocessor macros will <b>not</b> be present in the final binary. For things like debug views and mocked components, this is an amazing feature. As the code in the else block is ignored, a hacker that decompiles your app would not find a single trace that such features even existed.</p>
<h2>Preprocessor Macros Unit Testing Issues</h2>
<p>However, this same amazing feature also brings amazing problems. Since the code is ignored, you might have witnessed the fact that testing them can be very difficult. Unless you create multiple testing schemes with multiple macro settings (please don't do this), you are not easily able to test how your app behaves depending on the value of the macro -- only the value that your testing scheme is currently using. For example, in the <b>createClient()</b> snippet above, I would able to test that <b>createClient()</b> returns a <b>MockHTTPClient</b> as my testing scheme defines the <b>TESTING</b> macro, but I wouldn't be able to confirm that it returns a <b>URLSessionHTTPClient</b> in other situations.</p>
<p>This might lead you to other alternatives, like using compiler arguments or a global property instead of the macro directly:</p>
<pre><code>var isDebugging = false
func userDidShakeDevice() {
if isDebugging {
pushDebugMenu()
}
}
func startApp() {
#if DEBUG_SCHEME
isDebugging = true
#endif
...
}</code></pre>
<p>In this case, it's a lot easier for a unit test to override the value of the macro, as all we have to do is toggle the global <b>isDebugging</b> property. Unfortunately, while this works, you're giving up the macro's ability to erase your code. The usage of <b>if isDebugging</b> in this case tells the compiler that the execution of <b>userDidShakeDevice()</b> is <b>unknown</b> in compile time due to the fact that the value of that boolean can change any time. This would compile the <b>if</b> block even if you're running a non-debug build, allowing hackers to find the <b>pushDebugMenu()</b> method and use it for evil.</p>
<h2>Leveraging Optimization Settings to Unit Test Preprocessor Macros</h2>
<p>Fortunately, by leveraging the Swift Compiler's ability to ignore unused code, we can mix the best of both worlds and achieve macros that properly erase code and are easily testable at the same time.</p>
<p>To explain how to achieve this, let's use a real example. In one of the companies I worked for, for bug-finding reasons, employees couldn't install AppStore builds -- only beta ones. This was done by detecting which build you had installed and checking your user's permissions to see if you were allowed to use it. Otherwise, you would get an alert showing you where to download the correct version. The detection part was done like this:</p>
<pre><code>enum BuildType {
case appStore
case employeeBuild
case xcodeBuild
}
var currentBuildType: BuildType {
#if ENTERPRISE
return .employeeBuild
#elseif XCODE
return .xcodeBuild
#else
return .appStore
#endif
}</code></pre>
<p>As we can see, this is exactly like our previous examples, with the exact same issues as we had no way to test that <b>currentBuildType</b> returned the correct build type for each build.</p>
<p>Before learning how we can test this, let's clean this up by abstracting the macro checks into separate types:</p>
<pre><code>enum EnterpriseMacro {
static var active: Bool {
#if ENTERPRISE
return true
#else
return false
#endif
}
}
enum XcodeMacro {
static var active: Bool {
#if XCODE
return true
#else
return false
#endif
}
}
var currentBuildType: BuildType {
if EnterpriseMacro.active {
return .employeeBuild
} else if XcodeMacro.active {
return .xcodeBuild
} else {
return .appStore
}
}</code></pre>
<h2>Wait! Doesn't this have the same problem as the global property example?</h2>
<p>If this is what you thought, congratulations! The answer is <b>it depends</b>, and this is exactly what we're going to leverage to unit test this class. The global property is problematic because its value can change in runtime, but our macro type's <b>active</b> properties are <b>immutable</b>. If you compile your app without optimization (true for debug and testing builds), the compiler will behave exactly like in the global property example, but if you compile with optimization (true for release builds), since our active values are immutable, <b>the compiler will erase the unreachable parts of the code.</b></p>
<p>We can confirm this by dumping Swift's SIL, which can be thought of as the final version of your code:</p>
<pre><code>swiftc -emit-sil ./bla.swift -O -DXCODE</code></pre>
<pre><code>// currentBuildType.getter
sil hidden @$s3bla16currentBuildTypeAA0cD0Ovg : $@convention(thin) () -> BuildType {
bb0:
%0 = enum $BuildType, #BuildType.xcodeBuild!enumelt // user: %1
return %0 : $BuildType // id: %1
} // end sil function '$s3bla16currentBuildTypeAA0cD0Ovg'</code></pre>
<p>The SIL indicates that when that file is compiled with optimization and the <b>XCODE</b> macro, <b>currentBuildType</b> instantly returns <b>.xcodeBuild</b>. Traces of the other build types in this method have been completely eliminated!</p>
<p><i>(Note: This method still isn't hacker-proof because the other build types are still defined in the enum. Use this as an example of how to unit test macros, but consider the security necessities when implementing the trick shown in this article.)</i></p>
<h2>Unit Testing the Macros</h2>
<p>Finally, to test these macros, we can simply add a property to override its value when the macro isn't present:</p>
<pre><code>protocol Macro {
static var isOverridden: Bool { get set }
}
enum EnterpriseMacro: Macro {
static var isOverridden = false
static var active: Bool {
#if ENTERPRISE
return true
#else
return isOverridden
#endif
}
}</code></pre>
<p>Even though a hacker is able to force <b>isOverridden</b> to be <b>true</b>, nothing would be achieved as the code that ran as the result of the presence of this macro was never compiled.</p>
<p>Changing <b>isOverridden</b> would only have an effect if we compiled our code without optimizations, which is exactly the case of unit testing targets. We can then use it to safely unit test <b>currentBuildType</b>.</p>
<pre><code>func with<T: Macro>(macro: T.Type, block: () -> Void) {
macro.isOverridden = true
block()
macro.isOverridden = false
}
final class BuildTests: XCTestCase {
func testEnterpriseBuild() {
with(macro: EnterpriseMacro.self) {
XCTAssertEqual(currentBuildType, .employeeBuild)
}
}
func testDebugBuild() {
with(macro: XcodeMacro.self) {
XCTAssertEqual(currentBuildType, .xcodeBuild)
}
}
func testProductionBuild() {
// How it behaves when no macros are present
XCTAssertEqual(currentBuildType, .appStore)
}
}</code></pre>
<p><i>(Note that because <b>isOverridden</b> only works when a macro isn't present in the build, your testing target should not contain macros whose's presence/absence needs to be tested.)</i></p>
<div class="sponsor-article-ad-auto hidden"></div>
<p>With this setup, we're able to test preprocessor macros while being sure that our final release builds will not contain code that's not meant to be executed. This same trick can be used to test macros in XCUITests.</p>
<p>As a final note in the topic of security, note that if your intention is to <b>completely</b> get rid of something in runtime, everything needs to be wrapped by macro checks. In this case, if hiding the build types themselves was critical (and not just the logic of what's my current one), we would have to wrap the enum itself in macros, which would make unit testing it like this considerably harder, although still possible.</p>
</div></div>
<div class="blog-post footer-main">
<div class="footer-logos">
<a href="https://swiftrocks.com/rss.xml"><i class="fa fa-rss"></i></a>
<a href="https://twitter.com/rockbruno_"><i class="fa fa-twitter"></i></a>
<a href="https://github.com/rockbruno"><i class="fa fa-github"></i></a>
</div>
<div class="footer-text">
© 2025 Bruno Rocha
</div>
<div class="footer-text">
<p><a href="https://swiftrocks.com">Home</a> / <a href="blog">See all posts</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Blog Post (Right Sidebar) End -->
</div>
</div>
</div>
<!-- All Javascript Plugins -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script type="text/javascript" src="js/prism4.js"></script>
<!-- Main Javascript File -->
<script type="text/javascript" src="js/scripts30.js"></script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-H8KZTWSQ1R"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-H8KZTWSQ1R');
</script>
</body>
</html>