-
Notifications
You must be signed in to change notification settings - Fork 20
/
test.js
1110 lines (813 loc) · 27.6 KB
/
test.js
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const test = require('ava');
const objc = require('./src/index');
const util = require('util');
const NULL_DESC = '[objc.Instance (null)]';
// TODO
// - test automatic conversion to String/Number using the constructor `Number(nsnumber_object)`
/*
Class loading
*/
test('Load existent class', t => {
t.notThrows(() => {
const {NSArray} = objc;
});
});
test('Load non-existent class', t => {
t.throws(() => {
const {NSArrayy} = objc;
});
});
test('class exists', t => {
t.true(objc.runtime.classExists('NSString'));
t.false(objc.runtime.classExists('ClassThatDoesntExist'));
});
/*
Framework loading
*/
test('[objc.import] import framework by absolute path', t => {
objc.import('/System/Library/Frameworks/AppKit.framework');
t.true(objc.runtime.classExists('NSApplication'));
});
// TODO find some other framework to import
//test('[objc.import] import framework by name', t => {
// objc.import('CoreData');
// t.true(objc.runtime.classExists('NSManagedObject'));
//})
/*
Class metadata (not yet implemented)
*/
test.skip('Class class methods', t => {
const NSString = objc.NSString;
const classMethods = NSString.__classMethods;
t.is(Array.isArray(classMethods), true);
// Includes methods inherited from NSObject
t.true(classMethods.includes('load'));
t.true(classMethods.includes('init'));
// Includes NSString-specific methods
t.true(classMethods.includes('stringWithCString:'));
t.true(classMethods.includes('stringWithFormat:'));
t.true(classMethods.includes('stringEncodingForData:encodingOptions:convertedString:usedLossyConversion:'));
});
test.skip('Class instance methods', t => {
const NSString = objc.NSString;
const classMethods = NSString.__instanceMethods;
t.is(Array.isArray(classMethods), true);
// Includes methods inherited from NSObject
t.true(classMethods.includes('copy'));
t.true(classMethods.includes('description'));
// Includes NSString-specific methods
t.true(classMethods.includes('length'));
t.true(classMethods.includes('cStringUsingEncoding:'));
t.true(classMethods.includes('compare:options:range:locale:'));
t.true(classMethods.includes('getBytes:maxLength:usedLength:encoding:options:range:remainingRange:'));
});
/*
Object inspection
*/
test('description of class proxy', t => {
const NSDate = objc.NSDate;
const description = util.inspect(NSDate);
t.is(description, '[objc.Instance NSDate]');
});
test('description of instance proxy', t => {
const string = objc.NSString.stringWithString_('the north remembers');
const description = util.inspect(string);
t.is(description, '[objc.Instance the north remembers]');
});
test('description of class method proxy', t => {
const method = objc.NSDate.date;
t.is(util.inspect(method), `[objc.MethodProxy '+[NSDate date]']`);
});
test('description of instance method proxy', t => {
const obj = objc.NSObject.new()
const method = obj.description;
t.is(util.inspect(method), `[objc.MethodProxy '-[NSObject description]']`);
});
test('description of null proxy', t => {
const obj = objc.allocRef();
obj.__ptr = obj.__ptr.deref();
const description = util.inspect(obj);
t.is(description, NULL_DESC);
});
/*
Implicit type conversion
*/
test('string creation', t => {
const NSString = objc.NSString;
const string = NSString.stringWithString_('Hello World');
t.is(String(string), 'Hello World');
});
test('primitive argument types', t => {
const NSNumber = objc.NSNumber;
const number = NSNumber.numberWithInt_(5);
t.is(number.intValue(), 5);
});
test('primitive return values', t => {
const NSString = objc.NSString;
const string = NSString.stringWithString_('I am the doctor');
const length = string.length();
t.is(length, 15);
t.is(typeof length, 'number');
});
test('Null return value', t => {
const NSDictionary = objc.NSDictionary;
const dict = NSDictionary.dictionary();
t.is(null, dict.objectForKey_('key'));
});
test('Automatic array conversion (JS array -> NSArray)', t => {
const NSArray = objc.NSArray;
const inputArray = ['I', 'am', 'the', 'doctor'];
const array = NSArray.arrayWithArray_(inputArray);
inputArray.forEach((object, index) => {
const str1 = String(object);
const str2 = String(array.objectAtIndex_(index));
t.is(str1, str2);
});
});
test('convert NSNumber to Number', t => {
const number = objc.ns(12);
t.is(12, +number);
});
// test.skip('pass primitive w/out objc counterpart', t => {
// console.log('THIS SHOULD NOT BE RUNNING')
// const {NSMutableArray} = objc;
// const array = NSMutableArray.array();
// try {
// array.addObject_(() => {});
// } catch (err) {
// t.is(err.message, 'NSInvalidArgumentException *** -[__NSArrayM insertObject:atIndex:]: object cannot be nil');
// }
// });
/*
Explicit type conversion
*/
// String
test('Type conversion JS -> ObjC: String', t => {
const NSString = objc.NSString;
const input = 'trust me. i am the doctor';
const asNSString = objc.ns(input);
t.true(asNSString.isKindOfClass_(NSString));
});
test('Type conversion ObjC -> JS: String', t => {
const NSString = objc.NSString;
const input = NSString.stringWithString_('trust me. i am the doctor');
const asString = objc.js(input);
t.is(asString, 'trust me. i am the doctor');
});
// Number
test('Type conversion JS -> ObjC: Number', t => {
const NSNumber = objc.NSNumber;
const input = 42;
const asNSNumber = objc.ns(input);
t.true(asNSNumber.isKindOfClass_(NSNumber));
});
test('Type conversion ObjC -> JS: Number', t => {
const NSNumber = objc.NSNumber;
const input = NSNumber.numberWithInt_(42);
const asNumber = objc.js(input);
t.is(asNumber, 42);
});
// Array
test('Type conversion JS -> ObjC: Array', t => {
const NSArray = objc.NSArray;
const input = ['time', 'and', 'relative', 'dimensions', 'in', 'space'];
const asNSArray = objc.ns(input);
t.true(asNSArray.isKindOfClass_(NSArray));
});
test('Type conversion ObjC -> JS: Array', t => {
const NSArray = objc.NSArray;
const items = ['time', 'and', 'relative', 'dimensions', 'in', 'space'];
const input = NSArray.arrayWithArray_(items);
const asArray = objc.js(input);
t.deepEqual(items, asArray);
});
test('Type Conversion: JS Array containing objc objects -> NSArray', t => {
const {NSArray, NSObject} = objc;
const obj1 = NSObject.new();
const obj2 = NSObject.new();
const obj3 = NSObject.new();
const input = [obj1, obj2, obj3];
const asNSArray = objc.ns(input);
t.true(asNSArray.isKindOfClass_(NSArray));
t.is(3, asNSArray.count());
t.true(asNSArray.objectAtIndex_(0).isEqual_(obj1));
t.true(asNSArray.objectAtIndex_(1).isEqual_(obj2));
t.true(asNSArray.objectAtIndex_(2).isEqual_(obj3));
});
// Date
test('Type conversion JS -> ObjC: Date', t => {
const NSDate = objc.NSDate;
const input = new Date('1963-11-23T17:16:20');
const asNSDate = objc.ns(input);
t.true(asNSDate.isKindOfClass_(NSDate));
});
test('Type conversion ObjC -> JS: Date', t => {
const NSDate = objc.NSDate;
const input = NSDate.date();
const asDate = objc.js(input);
t.true(asDate instanceof Date);
});
// Object
test('Type conversion JS -> ObjC: Object', t => {
const input = {firstName: 'Lukas', lastName: 'Kollmer'};
const objcValue = objc.ns(input);
t.true(objcValue.objectForKey_('firstName').isEqualToString_('Lukas'))
t.true(objcValue.objectForKey_('lastName').isEqualToString_('Kollmer'))
});
test('Type conversion ObjC -> JS: Object', t => {
const {NSObject, NSString, NSMutableDictionary} = objc;
// 1: convert a dictionary that contains only objects we can convert to JS
const name = NSMutableDictionary.dictionary();
name.setObject_forKey_('Lukas', 'first');
name.setObject_forKey_('Kollmer', 'last');
const me = NSMutableDictionary.dictionary();
me.setObject_forKey_(name, 'name');
me.setObject_forKey_(19, 'age');
t.deepEqual(objc.js(me), {
age: 19,
name: {
first: 'Lukas',
last: 'Kollmer'
}
});
// 2: add some objects that don't have a JS representation
// We can't use `t.deepEqual` for this because that doesn't work with our proxies (ava seems to use lodash for that)
const obj = NSObject.new();
me.setObject_forKey_(obj, 'obj');
const me_js = objc.js(me);
t.is(19, me_js.age);
t.deepEqual({first: 'Lukas', last: 'Kollmer'}, me_js.name);
t.is(true, obj.isEqual_(me_js.obj));
});
// Selector
test('[selector] create from string', t => {
const sel = new objc.Selector('allocWithCount:')
t.is(sel.name, 'allocWithCount:');
});
test('[selector] create from pointer', t => {
const sel = new objc.Selector(objc.runtime.sel_getUid('newWithValue:'));
t.is(sel.name, 'newWithValue:');
})
test('Type conversion JS -> ObjC: Selector', t => {
const input = 'localizedDescriptionForRegion:completionHandler:';
const sel = objc.ns(input, ':');
t.is(true, sel instanceof objc.Selector)
t.is(input, sel.name);
});
// Unknown
test('Type conversion JS -> ObjC: Unknown', t => {
const input = () => {};
const objcValue = objc.ns(input);
t.is(null, objcValue);
});
test('Type conversion ObjC -> JS: Unknown', t => {
const NSProcessInfo = objc.NSProcessInfo;
const input = NSProcessInfo.processInfo();
const jsValue = objc.js(input);
t.is(null, jsValue);
});
/*
Constants
*/
test('load constant', t => {
objc.import('AppKit');
const {NSFontAttributeName} = objc;
t.is(NSFontAttributeName, 'NSFont');
});
test('load non-existent constant', t => {
objc.import('AppKit');
t.throws(() => {
const {NSFontAttributeNamee} = objc;
});
});
/*
Inout parameters
*/
test('inout parameters 1 (^@)', t => {
const {NSFileManager, NSError} = objc;
const fm = NSFileManager.defaultManager();
const filepath = '/Library/Caches/randomfilenamethatsurelydoesntexist.hey';
fm.createFileAtPath_contents_attributes_(filepath, null, null);
const error1 = objc.allocRef();
const success1 = fm.removeItemAtPath_error_(filepath, error1);
t.is(success1, true);
t.is(util.inspect(error1), NULL_DESC);
t.true(objc.Instance.isNull(error1));
const error2 = objc.allocRef();
const success2 = fm.removeItemAtPath_error_(filepath, error2);
t.is(success2, false);
t.true(error2.isKindOfClass_(NSError));
t.is(error2.code(), 4); // NSFileNoSuchFileError
});
test.skip('inout parameters 2 (^@)', t => {
const {NSDictionary, NSAppleScript} = objc;
const script = NSAppleScript.alloc().initWithSource_('telll application "Safari" to get URL of current tab of window 1');
const error = objc.allocRef();
const success = script.compileAndReturnError_(error);
t.is(success, false);
t.true(error.isKindOfClass_(NSDictionary));
});
test.skip('[inout parameters] `null` if not changed', t => {
const {NSAppleScript} = objc;
const script = NSAppleScript.alloc().initWithSource_(`tell application "System Events" to get name of current user`);
const error = objc.allocRef();
console.log('will run script')
script.executeAndReturnError_(error);
console.log('did run script')
t.is(util.inspect(error), NULL_DESC);
t.true(objc.isNull(error));
t.true(objc.Instance.isNull(error));
});
/*
Selector handling
*/
test('Test calling methods that contain underscores', t => {
const NSDate = objc.NSDate;
const now = NSDate.date();
const web_RFC1123DateString = now._web_RFC1123DateString();
t.is(typeof web_RFC1123DateString, 'object');
t.is(web_RFC1123DateString.isKindOfClass_('NSString'), true);
});
test('Trailing underscores in method names can be omitted', t => {
const NSString = objc.NSString;
const str1 = NSString.stringWithString_('Hello World');
const str2 = NSString.stringWithString('Hello World');
t.is(String(str1), String(str2));
});
test('Test possible selectors for 0 underscores', t => {
const Selector = require('./src/selector');
const selectors = ['date'];
new Selector('date').permutations().forEach((_, index) => {
selectors.splice(index, 1);
});
t.is(selectors.length, 0);
});
test('Test possible selectors for 1 underscore', t => {
const Selector = require('./src/selector');
const selectors = [
'performAction:',
'performAction_'
];
for (let permutation of new Selector('performAction_').permutations().map(s => s.name)) {
t.true(selectors.includes(permutation));
}
});
test('Test possible selectors for 2 underscores', t => {
const Selector = require('./src/selector');
const selectors = [
"performAction:withObject:",
"performAction_withObject:",
"performAction:withObject_",
'performAction_withObject_'
];
for (let permutation of new Selector('performAction_withObject_').permutations().map(s => s.name)) {
t.true(selectors.includes(permutation));
}
});
test('Test possible selectors for 3 underscores', t => {
const Selector = require('./src/selector');
const selectors = [
'performAction:withObject_afterDelay:',
'performAction:withObject_afterDelay_',
'performAction:withObject:afterDelay_',
'performAction_withObject:afterDelay:',
'performAction_withObject:afterDelay_',
'performAction_withObject_afterDelay:',
'performAction:withObject:afterDelay:',
'performAction_withObject_afterDelay_'
];
for (let permutation of new Selector('performAction_withObject_afterDelay_').permutations().map(s => s.name)) {
t.true(selectors.includes(permutation))
}
});
test('Test possible selectors for method with leading underscore and no other underscores', t => {
const Selector = require('./src/selector');
const selectors = [
'_dateString',
':dateString'
];
for (let permutation of new Selector('_dateString').permutations().map(s => s.name)) {
t.true(selectors.includes(permutation));
}
});
test('Test possible selectors for method with leading underscore and other underscores', t => {
const Selector = require('./src/selector');
const selectors = [
'_dateStringForTimeZone_',
'_dateStringForTimeZone:',
':dateStringForTimeZone_',
':dateStringForTimeZone:'
];
for (let permutation of new Selector('_dateStringForTimeZone_').permutations().map(s => s.name)) {
t.true(selectors.includes(permutation));
}
});
/*
Exception handling
*/
test.skip('ObjC exception handling', t => {
const NSMutableArray = objc.NSMutableArray;
const array = NSMutableArray.array();
array.addObject_('Hello');
array.addObject_('World');
t.throws(() => {
array.addObject_(null);
});
});
// test.skip('ObjC exception contains exception info', t => {
// console.log('THIS SHOULD ALSO NOT BE RUNNING')
// const NSMutableArray = objc.NSMutableArray;
// const array = NSMutableArray.array();
// array.addObject_('Hello');
// array.addObject_('World');
// try {
// console.log('hmmm?')
// array.addObject_(null);
// } catch (err) {
// t.is(err.message, 'NSInvalidArgumentException *** -[__NSArrayM insertObject:atIndex:]: object cannot be nil');
// }
// });
/*
Blocks
*/
test('Blocks: Sort NSString* array by length, longest to shortest', t => {
const NSArray = objc.NSArray;
const array = NSArray.arrayWithArray_(['I', 'Am', 'The', 'Doctor']);
const block = new objc.Block((obj1, obj2) => {
obj1 = objc.wrap(obj1);
obj2 = objc.wrap(obj2);
return obj1.length() > obj2.length() ? -1 : 1;
}, 'q', ['@', '@']);
const sortedArray = array.sortedArrayUsingComparator_(block);
t.true(sortedArray.isEqualToArray_(['Doctor', 'The', 'Am', 'I']));
});
test('Blocks: objc.Block throws for missing block type encoding', t => {
t.throws(() => {
const block = new objc.Block(() => {});
});
});
test('Blocks: objc.Block throws for incomplete block type encoding', t => {
t.throws(() => {
const block = new objc.Block(() => {}, 'v');
});
});
test('Blocks: objc.Block passes for full block type encoding', t => {
t.notThrows(() => {
const block = new objc.Block(() => {}, 'v', []);
});
});
test('Blocks: Block w/ struct parameter and inout BOOL*', t => {
const ref = require('ref-napi');
objc.import('AppKit');
const { NSAttributedString, NSMutableAttributedString, NSLinkAttributeName } = objc;
const { id, NSRange } = objc.types;
let attrString = NSMutableAttributedString.new();
attrString.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(
'abc', {
[NSLinkAttributeName]: 'https://example.com'
}
));
attrString.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(
'def', {
[NSLinkAttributeName]: 'https://example.de'
}
));
attrString.appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(
'ghi', {
[NSLinkAttributeName]: 'https://example.net'
}
));
t.is(attrString.description().UTF8String(), `abc{
NSLink = "https://example.com";
}def{
NSLink = "https://example.de";
}ghi{
NSLink = "https://example.net";
}`);
let blockArgs = [];
let block = new objc.Block((arg0, arg1, arg2) => {
const attrs = objc.wrap(arg0);
const range = arg1;
blockArgs.push([objc.js(attrs), {location: range.location, length: range.length}]);
if (range.location === 3 && range.length === 3) {
ref.set(arg2, 0, 1); // uncomment this to have it stop iterating after the first range.
}
return;
}, objc.types.void, [id, NSRange, ref.refType(objc.types.char)]);
attrString.enumerateAttributesInRange_options_usingBlock_(NSRange.new(0, attrString.length()), 0, block);
t.deepEqual(blockArgs, [ // We expect the third pair to be missing, which tells us that stopping the iteration early by setting the *stop param worked.
[{NSLink: 'https://example.com'}, { location: 0, length: 3 }],
[{NSLink: 'https://example.de' }, { location: 3, length: 3 }]
]);
})
/*
Iterators
*/
test('Iterate over a NSArray', t => {
const NSArray = objc.NSArray;
const inputArray = ['hey', 'missy', 'you', 'so', 'fine'];
const array = NSArray.arrayWithArray_(inputArray);
for (const element of array) {
const index = inputArray.indexOf(String(element));
inputArray.splice(index, 1);
}
t.is(inputArray.length, 0);
});
test('Iterate over a NSDictionary', t => {
const {NSDictionary} = objc;
const inputDict = {a: 1, b: 2, c: 3};
const dictionary = NSDictionary.alloc().initWithObjects_forKeys_(['1', '2', '3'], ['a', 'b', 'c'])
for (let key of dictionary) {
key = String(key);
t.is(true, Object.prototype.hasOwnProperty.call(inputDict, key));
delete inputDict[key];
}
t.deepEqual({}, inputDict);
});
test('Iterate over a NSSet', t => {
const {NSSet} = objc;
const items = ['a', 'b', 'c']
const set = NSSet.setWithArray_(items);
for (const element of set) {
const index = items.indexOf(String(element));
items.splice(index, 1);
}
t.is(items.length, 0);
});
test('Iterate over non-enumerable', t => {
const {NSObject} = objc;
const obj = NSObject.new();
t.throws(() => {
for (let element of obj) {
}
});
});
/*
Method swizzling
(in all swizzling tests, we restore the original implementation to make sure it doesn't break any of the other tests)
*/
test('[method swizzling] swizzle class method', t => {
const {NSDate} = objc;
const restore = objc.swizzle(NSDate, 'date', () => {
return NSDate.distantPast();
}, 'class');
t.true(NSDate.date().isEqualToDate_(NSDate.distantPast()));
restore();
});
test('[method swizzling] swizzle instance method (primitive return type)', t => {
const {NSProcessInfo} = objc;
const restore = objc.swizzle(NSProcessInfo, 'processorCount', () => {
return 12;
});
t.is(12, NSProcessInfo.processInfo().processorCount());
restore();
});
test('[method swizzling] swizzle instance method (complex return type)', t => {
const {NSObject} = objc;
const restore = objc.swizzle(NSObject, 'description', () => {
return objc.ns('hello there');
});
t.true(NSObject.new().description().isEqualToString_('hello there'));
restore();
});
test('[method swizzling] swizzle instance method with parameters', t => {
const {NSDate, wrap} = objc;
const restore = objc.swizzle(NSDate, 'dateByAddingTimeInterval:', (self, _cmd, timeInterval) => {
self = wrap(self);
return self.xxx__dateByAddingTimeInterval_(timeInterval * 2);
});
const x = NSDate.alloc().initWithTimeIntervalSince1970_(0);
const y = x.dateByAddingTimeInterval(2);
const z = NSDate.alloc().initWithTimeIntervalSince1970_(4);
t.true(y.isEqualToDate_(z));
restore();
});
test('[method swizzling] instance method: original implementation is still available', t => {
// NSString is a class cluster, which is why we swizzle -[__NSCFString length] instead of `-[NSString length]`
const restore = objc.swizzle('__NSCFString', 'length', () => {
return 42;
});
const string = objc.ns('hello world');
t.is(42, string.length());
t.is(11, string.xxx__length());
restore();
});
test('[method swizzling] class method: original implementation is still available', t => {
const {NSProcessInfo, NSDate} = objc;
const now = NSDate.date();
const restore = objc.swizzle(NSProcessInfo, 'processInfo', () => {
return now;
}, 'class');
const pi = NSProcessInfo.processInfo();
t.true(pi.isKindOfClass_(NSDate));
t.true(pi.isEqualToDate_(now));
t.true(NSProcessInfo.xxx__processInfo().isKindOfClass_(NSProcessInfo));
restore();
});
test('[method swizzling] invalid parameters: method type', t => {
t.throws(() => {
objc.swizzle('NSString', 'length', () => {}, 'foo');
})
});
/*
Creating Classes
*/
test('[custom class] instance methods', t => {
const {NSFileManager} = objc;
const LKClass = objc.createClass('LKClass1', 'NSObject', {
'add::': (self, cmd, a, b) => {
return a + b;
},
'getFileManager': (self, cmd) => {
return NSFileManager.defaultManager();
},
'doesntReturnAnything': (self, cmd) => {
},
_encodings: {
//'add::': ['i24', ['@0', ':8', 'i16', 'i20']],
'add::': ['Q', ['@', ':', 'Q', 'Q']],
'getFileManager': ['@', ['@', ':']],
'doesntReturnAnything': ['v', ['@', ':']],
}
});
let obj = LKClass.new();
t.is(6, obj.add__(1, 5));
t.true(obj.getFileManager().isEqual_(NSFileManager.defaultManager()));
t.is(null, obj.doesntReturnAnything());
})
test('[custom class] class methods', t => {
const LKClass = objc.createClass('LKClass2', 'NSObject', {}, {
'someClassMethodThatReturnsFourtyTwo': (self, cmd) => {
return 42;
},
_encodings: {
'someClassMethodThatReturnsFourtyTwo': ['i', ['@', ':']]
}
});
t.is(42, LKClass.someClassMethodThatReturnsFourtyTwo());
})
test('[custom class] no methods', t => {
t.notThrows(() => {
const LKClass = objc.createClass('LKClass3', 'NSObject');
});
})
/*
Structs
skipping the first two since NSRange is already declared in the objc module
TODO: Find some obscure/rarely used struct in Foundation, use that for the test
*/
test.skip('[struct] use not-yet defined struct', t => {
t.throws(() => {
objc.ns('Hello World').rangeOfString_('Hello');
});
});
test.skip('[struct] define struct', t => {
t.notThrows(() => {
NSRange = objc.defineStruct('_NSRange', {
location: objc.refTypes.ulonglong,
length: objc.refTypes.ulonglong
});
});
t.not(NSRange, null);
t.throws(() => {
objc.defineStruct('_NSRange', {});
});
});
test('[struct] define/use existing struct', t => {
t.throws(() => {
objc.defineStruct('_NSRange', {});
});
t.throws(() => {
coerceType('{LKRange=qq}');
});
})
const {NSRange} = objc.types;
test('[struct] pass struct as parameter', t => {
const range = NSRange.new();
range.location = 3;
range.length = 5;
t.is('lo Wo', String(objc.ns('Hello World').substringWithRange_(range)));
});
test('[struct] pass field values in initializer', t => {
const range = NSRange.new(8, 11);
t.is(8, range.location);
t.is(11, range.length);
t.is('pretty cool', String(objc.ns('This is pretty cool').substringWithRange_(range)));
});
test('[struct] call initializer with invalid arguments', t => {
t.throws(() => {
NSRange.new(1);
});
});
test('[struct] struct as return type', t => {
const string = objc.ns('Hello World');
const range = string.rangeOfString_('lo Wo');
t.is(3, range.location);
t.is(5, range.length);
});
test('[struct] struct defined in objc module works with ffi module', t => {
const ffi = require('ffi-napi');
const libFoundation = new ffi.Library(null, {
NSStringFromRange: ['pointer', [NSRange]]
});
const range = new NSRange();
range.location = 42;
range.length = 12;
const string = objc.wrap(libFoundation.NSStringFromRange(range));
t.is('{42, 12}', String(string));
});
/*
Miscellaneous
*/