-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPITest.php
6705 lines (5978 loc) · 192 KB
/
APITest.php
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
<?php
/**
* Tests for the ConvertKit_API class.
*
* @since 1.0.0
*/
class APITest extends \Codeception\TestCase\WPTestCase
{
/**
* The testing implementation.
*
* @var \WpunitTester.
*/
protected $tester;
/**
* Holds the ConvertKit API class.
*
* @since 1.0.0
*
* @var ConvertKit_API
*/
private $api;
/**
* Holds the expected WP_Error code.
*
* @since 1.0.0
*
* @var string
*/
private $errorCode = 'convertkit_api_error';
/**
* Custom Field IDs to delete on teardown of a test.
*
* @since 2.0.0
*
* @var array<int, int>
*/
protected $custom_field_ids = [];
/**
* Subscriber IDs to unsubscribe on teardown of a test.
*
* @since 2.0.0
*
* @var array<int, int>
*/
protected $subscriber_ids = [];
/**
* Broadcast IDs to delete on teardown of a test.
*
* @since 2.0.0
*
* @var array<int, int>
*/
protected $broadcast_ids = [];
/**
* Webhook IDs to delete on teardown of a test.
*
* @since 2.0.0
*
* @var array<int, int>
*/
protected $webhook_ids = [];
/**
* Performs actions before each test.
*
* @since 1.0.0
*/
public function setUp(): void
{
parent::setUp();
// Include class from /src to test.
require_once 'src/class-convertkit-api-traits.php';
require_once 'src/class-convertkit-api-v4.php';
require_once 'src/class-convertkit-log.php';
// Initialize the classes we want to test.
$this->api = new ConvertKit_API_V4(
$_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
$_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
$_ENV['CONVERTKIT_OAUTH_ACCESS_TOKEN'],
$_ENV['CONVERTKIT_OAUTH_REFRESH_TOKEN']
);
$this->api_no_data = new ConvertKit_API_V4(
$_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
$_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
$_ENV['CONVERTKIT_OAUTH_ACCESS_TOKEN_NO_DATA'],
$_ENV['CONVERTKIT_OAUTH_REFRESH_TOKEN_NO_DATA']
);
// Wait a second to avoid hitting a 429 rate limit.
sleep(1);
}
/**
* Performs actions after each test.
*
* @since 1.0.0
*/
public function tearDown(): void
{
// Delete any Custom Fields.
foreach ($this->custom_field_ids as $id) {
$this->api->delete_custom_field($id);
}
// Unsubscribe any Subscribers.
foreach ($this->subscriber_ids as $id) {
$this->api->unsubscribe($id);
}
// Delete any Webhooks.
foreach ($this->webhook_ids as $id) {
$this->api->delete_webhook($id);
}
// Delete any Broadcasts.
foreach ($this->broadcast_ids as $id) {
$this->api->delete_broadcast($id);
}
parent::tearDown();
}
/**
* Test that a log directory and file are created in the expected location, with .htaccess
* and index.html protection, and that the name and email addresses are masked.
*
* @since 1.4.2
*/
public function testLog()
{
// Define location for log file.
define( 'CONVERTKIT_PLUGIN_PATH', $_ENV['WP_ROOT_FOLDER'] . '/wp-content/uploads' );
// Create a log.txt file.
$this->tester->writeToFile(CONVERTKIT_PLUGIN_PATH . '/log.txt', 'historical log file');
// Initialize API with logging enabled.
$api = new ConvertKit_API_V4(
$_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
$_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
$_ENV['CONVERTKIT_OAUTH_ACCESS_TOKEN'],
$_ENV['CONVERTKIT_OAUTH_REFRESH_TOKEN'],
true
);
// Perform actions that will write sensitive data to the log file.
$api->form_subscribe(
$_ENV['CONVERTKIT_API_FORM_ID'],
$_ENV['CONVERTKIT_API_SUBSCRIBER_EMAIL'],
'First Name',
array(
'last_name' => 'Last',
)
);
$api->profile($_ENV['CONVERTKIT_API_SIGNED_SUBSCRIBER_ID']);
// Confirm the historical log.txt file has been deleted.
$this->assertFileDoesNotExist(CONVERTKIT_PLUGIN_PATH . '/log.txt');
// Confirm the .htaccess and index.html files exist.
$this->assertDirectoryExists(CONVERTKIT_PLUGIN_PATH . '/log');
$this->assertFileExists(CONVERTKIT_PLUGIN_PATH . '/log/.htaccess');
$this->assertFileExists(CONVERTKIT_PLUGIN_PATH . '/log/index.html');
$this->assertFileExists(CONVERTKIT_PLUGIN_PATH . '/log/log.txt');
// Confirm the contents of the log file have masked the email address, name and signed subscriber ID.
$this->tester->openFile(CONVERTKIT_PLUGIN_PATH . '/log/log.txt');
$this->tester->seeInThisFile('API: POST subscribers: {"email_address":"o****@n********.c**","first_name":"******Name","state":"active","fields":{"last_name":"Last"}}');
$this->tester->seeInThisFile('API: GET profile/*****************************************');
$this->tester->dontSeeInThisFile($_ENV['CONVERTKIT_API_SUBSCRIBER_EMAIL']);
$this->tester->dontSeeInThisFile('First Name');
$this->tester->dontSeeInThisFile($_ENV['CONVERTKIT_API_SIGNED_SUBSCRIBER_ID']);
// Cleanup test.
$this->tester->cleanDir(CONVERTKIT_PLUGIN_PATH . '/log');
$this->tester->deleteDir(CONVERTKIT_PLUGIN_PATH . '/log');
}
/**
* Test that a 401 unauthorized error gracefully returns a WP_Error.
*
* @since 1.3.2
*/
public function test401Unauthorized()
{
$api = new ConvertKit_API_V4(
$_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
$_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
'not-a-real-access-token',
'not-a-real-refresh-token'
);
$result = $api->get_account();
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
$this->assertEquals($result->get_error_message(), 'The access token is invalid');
$this->assertEquals($result->get_error_data($result->get_error_code()), 401);
}
/**
* Test that a 429 internal server error gracefully returns a WP_Error.
*
* @since 1.0.0
*/
public function test429RateLimitHit()
{
// Force WordPress HTTP classes and functions to return a 429 error.
$this->mockResponses(
429,
'Rate limit hit'
);
$result = $this->api->get_account(); // The API function we use doesn't matter, as mockResponse forces a 429 error.
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
$this->assertEquals($result->get_error_message(), 'ConvertKit API Error: Rate limit hit.');
$this->assertEquals($result->get_error_data($result->get_error_code()), 429);
}
/**
* Test that a 500 internal server error gracefully returns a WP_Error.
*
* @since 1.0.0
*/
public function test500InternalServerError()
{
// Force WordPress HTTP classes and functions to return a 500 error.
$this->mockResponses( 500, 'Internal server error.' );
$result = $this->api->get_account(); // The API function we use doesn't matter, as mockResponse forces a 500 error.
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
$this->assertEquals($result->get_error_message(), 'ConvertKit API Error: Internal server error.');
$this->assertEquals($result->get_error_data($result->get_error_code()), 500);
}
/**
* Test that a 502 bad gateway gracefully returns a WP_Error.
*
* @since 1.0.0
*/
public function test502BadGateway()
{
// Force WordPress HTTP classes and functions to return a 502 error.
$this->mockResponses( 502, 'Bad gateway.' );
$result = $this->api->get_account(); // The API function we use doesn't matter, as mockResponse forces a 502 error.
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
$this->assertEquals($result->get_error_message(), 'ConvertKit API Error: Bad gateway.');
$this->assertEquals($result->get_error_data($result->get_error_code()), 502);
}
/**
* Test that the User Agent string is in the expected format when
* a context is provided.
*
* @since 1.2.0
*/
public function testUserAgentWithContext()
{
// When an API call is made, inspect the user-agent argument.
add_filter(
'http_request_args',
function($args, $url) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
$this->assertStringContainsString(';context/TestContext', $args['user-agent']);
return $args;
},
10,
2
);
// Perform a request.
$api = new ConvertKit_API_V4(
$_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
$_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
$_ENV['CONVERTKIT_OAUTH_ACCESS_TOKEN'],
$_ENV['CONVERTKIT_OAUTH_REFRESH_TOKEN'],
false,
'TestContext'
);
$result = $api->get_account();
}
/**
* Test that the User Agent string is in the expected format when
* no context is provided.
*
* @since 1.2.0
*/
public function testUserAgentWithoutContext()
{
// When an API call is made, inspect the user-agent argument.
add_filter(
'http_request_args',
function($args, $url) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter
$this->assertStringNotContainsString(';context/TestContext', $args['user-agent']);
return $args;
},
10,
2
);
// Perform a request.
$result = $this->api->get_account();
}
/**
* Test that get_oauth_url() returns the correct URL to begin the OAuth process.
*
* @since 2.0.0
*
* @return void
*/
public function testGetOAuthURL()
{
// Confirm the OAuth URL returned is correct.
$this->assertEquals(
$this->api->get_oauth_url(),
'https://app.kit.com/oauth/authorize?' . http_build_query(
[
'client_id' => $_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
'response_type' => 'code',
'redirect_uri' => $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
'code_challenge' => $this->api->generate_code_challenge( $this->api->get_code_verifier() ),
'code_challenge_method' => 'S256',
]
)
);
}
/**
* Test that get_oauth_url() returns the correct URL to begin the OAuth process
* when a state parameter is supplied.
*
* @since 2.0.0
*
* @return void
*/
public function testGetOAuthURLWithState()
{
// Confirm the OAuth URL returned is correct.
$this->assertEquals(
$this->api->get_oauth_url( 'https://example.com' ),
'https://app.kit.com/oauth/authorize?' . http_build_query(
[
'client_id' => $_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
'response_type' => 'code',
'redirect_uri' => $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
'code_challenge' => $this->api->generate_code_challenge( $this->api->get_code_verifier() ),
'code_challenge_method' => 'S256',
'state' => $this->api->base64_urlencode(
wp_json_encode(
array(
'return_to' => 'https://example.com',
'client_id' => $_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
)
)
),
]
)
);
}
/**
* Test that get_oauth_url() returns the correct URL to begin the OAuth process
* when a tenant_name parameter is supplied.
*
* @since 2.0.5
*
* @return void
*/
public function testGetOAuthURLWithTenantName()
{
// Confirm the OAuth URL returned is correct.
$this->assertEquals(
$this->api->get_oauth_url( false, 'https://example.com' ),
'https://app.kit.com/oauth/authorize?' . http_build_query(
[
'client_id' => $_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
'response_type' => 'code',
'redirect_uri' => $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
'code_challenge' => $this->api->generate_code_challenge( $this->api->get_code_verifier() ),
'code_challenge_method' => 'S256',
'tenant_name' => 'https://example.com',
]
)
);
}
/**
* Test that get_access_token() returns the expected data.
*
* @since 2.0.0
*
* @return void
*/
public function testGetAccessToken()
{
// Define response parameters.
$params = array(
'access_token' => 'example-access-token',
'refresh_token' => 'example-refresh-token',
'token_type' => 'Bearer',
'created_at' => strtotime('now'),
'expires_in' => strtotime('+3 days'),
'scope' => 'public',
);
// Mock the API response.
$this->mockResponses( 200, 'OK', wp_json_encode( $params ) );
// Send request.
$result = $this->api->get_access_token( 'auth-code' );
// Inspect response.
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('refresh_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('created_at', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('scope', $result);
$this->assertEquals($result['access_token'], $params['access_token']);
$this->assertEquals($result['refresh_token'], $params['refresh_token']);
$this->assertEquals($result['created_at'], $params['created_at']);
$this->assertEquals($result['expires_in'], $params['expires_in']);
}
/**
* Test that supplying an invalid auth code when fetching an access token returns a WP_Error.
*
* @since 2.0.0
*
* @return void
*/
public function testGetAccessTokenWithInvalidAuthCode()
{
$result = $this->api->get_access_token( 'not-a-real-auth-code' );
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), 'convertkit_api_error');
}
/**
* Test that refresh_token() returns the expected data.
*
* @since 2.0.0
*
* @return void
*/
public function testRefreshToken()
{
// Add mock handler for this API request, as this results in a new
// access and refresh token being provided, which would result in
// other tests breaking due to changed tokens.
$this->mockResponses(
200,
'OK',
wp_json_encode(
array(
'access_token' => $_ENV['CONVERTKIT_OAUTH_ACCESS_TOKEN'],
'refresh_token' => $_ENV['CONVERTKIT_OAUTH_REFRESH_TOKEN'],
'token_type' => 'bearer',
'created_at' => strtotime( 'now' ),
'expires_in' => 10000,
'scope' => 'public',
)
)
);
// Send request.
$result = $this->api->refresh_token();
// Inspect response.
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('access_token', $result);
$this->assertArrayHasKey('refresh_token', $result);
$this->assertArrayHasKey('token_type', $result);
$this->assertArrayHasKey('created_at', $result);
$this->assertArrayHasKey('expires_in', $result);
$this->assertArrayHasKey('scope', $result);
$this->assertEquals($result['access_token'], $_ENV['CONVERTKIT_OAUTH_ACCESS_TOKEN']);
$this->assertEquals($result['refresh_token'], $_ENV['CONVERTKIT_OAUTH_REFRESH_TOKEN']);
}
/**
* Test that supplying an invalid refresh token when refreshing an access token returns a WP_Error.
*
* @since 2.0.0
*
* @return void
*/
public function testRefreshTokenWithInvalidToken()
{
// Setup API.
$api = new ConvertKit_API_V4(
$_ENV['CONVERTKIT_OAUTH_CLIENT_ID'],
$_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'],
$_ENV['CONVERTKIT_OAUTH_ACCESS_TOKEN'],
'not-a-real-refresh-token'
);
$result = $api->refresh_token();
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), 'convertkit_api_error');
}
/**
* Test that making a call with an expired access token results in refresh_token()
* not being automatically called, when the WordPress site isn't a production site.
*
* @since 2.0.2
*
* @return void
*/
public function testRefreshTokenWhenAccessTokenExpiredErrorOnNonProductionSite()
{
// If the refresh token action in the libraries is triggered when calling get_account(), the test failed.
add_action(
'convertkit_api_refresh_token',
function() {
$this->fail('`convertkit_api_refresh_token` was triggered when calling `get_account` with an expired access token on a non-production site.');
}
);
// Filter requests to mock the token expiry and refreshing the token.
add_filter( 'pre_http_request', array( $this, 'mockAccessTokenExpiredResponse' ), 10, 3 );
add_filter( 'pre_http_request', array( $this, 'mockRefreshTokenResponse' ), 10, 3 );
// Run request, which will trigger the above filters as if the token expired and refreshes automatically.
$result = $this->api->get_account();
}
/**
* Test that supplying no API credentials to the API class returns a WP_Error.
*
* @since 2.0.2
*/
public function testNoAPICredentials()
{
$api = new ConvertKit_API_V4( $_ENV['CONVERTKIT_OAUTH_CLIENT_ID'], $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'] );
$result = $api->get_account();
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
$this->assertEquals($result->get_error_message(), 'Authentication Failed');
}
/**
* Test that supplying invalid API credentials to the API class returns a WP_Error.
*
* @since 1.0.0
*/
public function testInvalidAPICredentials()
{
$api = new ConvertKit_API_V4( $_ENV['CONVERTKIT_OAUTH_CLIENT_ID'], $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'], 'fakeAccessToken', 'fakeRefreshToken' );
$result = $api->get_account();
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
$this->assertEquals($result->get_error_message(), 'The access token is invalid');
}
/**
* Test that fetching an Access Token using a valid API Key and Secret returns the expected data.
*
* @since 2.0.0
*/
public function testGetAccessTokenByAPIKeyAndSecret()
{
$api = new ConvertKit_API_V4( $_ENV['CONVERTKIT_OAUTH_CLIENT_ID'], $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'] );
$result = $api->get_access_token_by_api_key_and_secret(
$_ENV['CONVERTKIT_API_KEY'],
$_ENV['CONVERTKIT_API_SECRET']
);
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('oauth', $result);
$this->assertArrayHasKey('access_token', $result['oauth']);
$this->assertArrayHasKey('refresh_token', $result['oauth']);
$this->assertArrayHasKey('expires_at', $result['oauth']);
}
/**
* Test that fetching an Access Token using an invalid API Key and Secret returns a WP_Error.
*
* @since 2.0.0
*/
public function testGetAccessTokenByInvalidAPIKeyAndSecret()
{
$api = new ConvertKit_API_V4( $_ENV['CONVERTKIT_OAUTH_CLIENT_ID'], $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'] );
$result = $api->get_access_token_by_api_key_and_secret(
'invalid-api-key',
'invalid-api-secret'
);
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
$this->assertEquals('Authorization Failed: API Secret not valid', $result->get_error_message());
}
/**
* Test that fetching an Access Token using an invalid client ID returns a WP_Error.
*
* @since 2.0.7
*/
public function testGetAccessTokenByAPIKeyAndSecretWithInvalidClientID()
{
$api = new ConvertKit_API_V4( 'invalidClientID', $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'] );
$result = $api->get_access_token_by_api_key_and_secret(
$_ENV['CONVERTKIT_API_KEY'],
$_ENV['CONVERTKIT_API_SECRET']
);
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
}
/**
* Test that fetching an Access Token using a blank client ID returns a WP_Error.
*
* @since 2.0.7
*/
public function testGetAccessTokenByAPIKeyAndSecretWithBlankClientID()
{
$api = new ConvertKit_API_V4( '', $_ENV['CONVERTKIT_OAUTH_REDIRECT_URI'] );
$result = $api->get_access_token_by_api_key_and_secret(
$_ENV['CONVERTKIT_API_KEY'],
$_ENV['CONVERTKIT_API_SECRET']
);
$this->assertInstanceOf(WP_Error::class, $result);
$this->assertEquals($result->get_error_code(), $this->errorCode);
}
/**
* Test that supplying valid API credentials to the API class returns the expected account information.
*
* @since 1.0.0
*/
public function testGetAccount()
{
$result = $this->api->get_account();
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('user', $result);
$this->assertArrayHasKey('account', $result);
$this->assertArrayHasKey('name', $result['account']);
$this->assertArrayHasKey('plan_type', $result['account']);
$this->assertArrayHasKey('primary_email_address', $result['account']);
$this->assertEquals('[email protected]', $result['account']['primary_email_address']);
}
/**
* Test that get_account_colors() returns the expected data.
*
* @since 2.0.0
*
* @return void
*/
public function testGetAccountColors()
{
$result = $this->api->get_account_colors();
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('colors', $result);
$this->assertIsArray($result['colors']);
}
/**
* Test that update_account_colors() updates the account's colors.
*
* @since 2.0.0
*
* @return void
*/
public function testUpdateAccountColors()
{
$result = $this->api->update_account_colors(
[
'#111111',
]
);
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('colors', $result);
$this->assertIsArray($result['colors']);
$this->assertEquals($result['colors'][0], '#111111');
}
/**
* Test that get_creator_profile() returns the expected data.
*
* @since 2.0.0
*
* @return void
*/
public function testGetCreatorProfile()
{
$result = $this->api->get_creator_profile();
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('name', $result['profile']);
$this->assertArrayHasKey('byline', $result['profile']);
$this->assertArrayHasKey('bio', $result['profile']);
$this->assertArrayHasKey('image_url', $result['profile']);
$this->assertArrayHasKey('profile_url', $result['profile']);
}
/**
* Test that get_email_stats() returns the expected data.
*
* @since 2.0.0
*
* @return void
*/
public function testGetEmailStats()
{
$result = $this->api->get_email_stats();
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('sent', $result['stats']);
$this->assertArrayHasKey('clicked', $result['stats']);
$this->assertArrayHasKey('opened', $result['stats']);
$this->assertArrayHasKey('email_stats_mode', $result['stats']);
$this->assertArrayHasKey('open_tracking_enabled', $result['stats']);
$this->assertArrayHasKey('click_tracking_enabled', $result['stats']);
$this->assertArrayHasKey('starting', $result['stats']);
$this->assertArrayHasKey('ending', $result['stats']);
}
/**
* Test that get_growth_stats() returns the expected data.
*
* @since 2.0.0
*
* @return void
*/
public function testGetGrowthStats()
{
$result = $this->api->get_growth_stats();
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
$this->assertArrayHasKey('cancellations', $result['stats']);
$this->assertArrayHasKey('net_new_subscribers', $result['stats']);
$this->assertArrayHasKey('new_subscribers', $result['stats']);
$this->assertArrayHasKey('subscribers', $result['stats']);
$this->assertArrayHasKey('starting', $result['stats']);
$this->assertArrayHasKey('ending', $result['stats']);
}
/**
* Test that get_growth_stats() returns the expected data
* when a start date is specified.
*
* @since 2.0.0
*
* @return void
*/
public function testGetGrowthStatsWithStartDate()
{
// Define start and end dates.
$starting = new DateTime('now');
$starting->modify('-7 days');
$ending = new DateTime('now');
// Send request.
$result = $this->api->get_growth_stats($starting);
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
// Confirm response object contains expected keys.
$this->assertArrayHasKey('cancellations', $result['stats']);
$this->assertArrayHasKey('net_new_subscribers', $result['stats']);
$this->assertArrayHasKey('new_subscribers', $result['stats']);
$this->assertArrayHasKey('subscribers', $result['stats']);
$this->assertArrayHasKey('starting', $result['stats']);
$this->assertArrayHasKey('ending', $result['stats']);
// Assert start and end dates were honored.
$timezone = ( new DateTime() )->setTimezone(new DateTimeZone('America/New_York'))->format('P'); // Gets timezone offset for New York (-04:00 during DST, -05:00 otherwise).
$this->assertEquals($result['stats']['starting'], $starting->format('Y-m-d') . 'T00:00:00' . $timezone);
$this->assertEquals($result['stats']['ending'], $ending->format('Y-m-d') . 'T23:59:59' . $timezone);
}
/**
* Test that get_growth_stats() returns the expected data
* when an end date is specified.
*
* @since 2.0.0
*
* @return void
*/
public function testGetGrowthStatsWithEndDate()
{
// Define start and end dates.
$starting = new DateTime('now');
$starting->modify('-90 days');
$ending = new DateTime('now');
$ending->modify('-7 days');
// Send request.
$result = $this->api->get_growth_stats(null, $ending);
$this->assertNotInstanceOf(WP_Error::class, $result);
$this->assertIsArray($result);
// Confirm response object contains expected keys.
$this->assertArrayHasKey('cancellations', $result['stats']);
$this->assertArrayHasKey('net_new_subscribers', $result['stats']);
$this->assertArrayHasKey('new_subscribers', $result['stats']);
$this->assertArrayHasKey('subscribers', $result['stats']);
$this->assertArrayHasKey('starting', $result['stats']);
$this->assertArrayHasKey('ending', $result['stats']);
// Assert start and end dates were honored.
$timezone = ( new DateTime() )->setTimezone(new DateTimeZone('America/New_York'))->format('P'); // Gets timezone offset for New York (-04:00 during DST, -05:00 otherwise).
$this->assertEquals($result['stats']['starting'], $starting->format('Y-m-d') . 'T00:00:00' . $timezone);
$this->assertEquals($result['stats']['ending'], $ending->format('Y-m-d') . 'T23:59:59' . $timezone);
}
/**
* Test that get_forms() returns the expected data.
*
* @since 1.0.0
*
* @return void
*/
public function testGetForms()
{
$result = $this->api->get_forms();
// Assert forms and pagination exist.
$this->assertDataExists($result, 'forms');
$this->assertPaginationExists($result);
// Iterate through each form, confirming no landing pages were included.
foreach ($result['forms'] as $form) {
// Assert shape of object is valid.
$this->assertArrayHasKey('id', $form);
$this->assertArrayHasKey('name', $form);
$this->assertArrayHasKey('created_at', $form);
$this->assertArrayHasKey('type', $form);
$this->assertArrayHasKey('format', $form);
$this->assertArrayHasKey('embed_js', $form);
$this->assertArrayHasKey('embed_url', $form);
$this->assertArrayHasKey('archived', $form);
// Assert form is not a landing page i.e embed.
$this->assertEquals($form['type'], 'embed');
// Assert form is not archived.
$this->assertFalse($form['archived']);
}
}
/**
* Test that get_forms() returns the expected data when
* the status is set to archived.
*
* @since 2.0.0
*
* @return void
*/
public function testGetFormsWithArchivedStatus()
{
$result = $this->api->get_forms('archived');
// Assert forms and pagination exist.
$this->assertDataExists($result, 'forms');
$this->assertPaginationExists($result);
// Iterate through each form, confirming no landing pages were included.
foreach ($result['forms'] as $form) {
// Assert shape of object is valid.
$this->assertArrayHasKey('id', $form);
$this->assertArrayHasKey('name', $form);
$this->assertArrayHasKey('created_at', $form);
$this->assertArrayHasKey('type', $form);
$this->assertArrayHasKey('format', $form);
$this->assertArrayHasKey('embed_js', $form);
$this->assertArrayHasKey('embed_url', $form);
$this->assertArrayHasKey('archived', $form);
// Assert form is not a landing page i.e embed.
$this->assertEquals($form['type'], 'embed');
// Assert form is archived.
$this->assertTrue($form['archived']);
}
}
/**
* Test that get_forms() returns the expected data
* when the total count is included.
*
* @since 2.0.0
*
* @return void
*/
public function testGetFormsWithTotalCount()
{
$result = $this->api->get_forms('active', true);
// Assert forms and pagination exist.
$this->assertDataExists($result, 'forms');
$this->assertPaginationExists($result);
// Assert total count is included.
$this->assertArrayHasKey('total_count', $result['pagination']);
$this->assertGreaterThan(0, $result['pagination']['total_count']);
}
/**
* Test that get_forms() returns the expected data when pagination parameters
* and per_page limits are specified.
*
* @since 2.0.0
*
* @return void
*/
public function testGetFormsPagination()
{
// Return one form.
$result = $this->api->get_forms('active', false, '', '', 1);
// Assert forms and pagination exist.
$this->assertDataExists($result, 'forms');
$this->assertPaginationExists($result);
// Assert a single form was returned.
$this->assertCount(1, $result['forms']);
// Assert has_previous_page and has_next_page are correct.
$this->assertFalse($result['pagination']['has_previous_page']);
$this->assertTrue($result['pagination']['has_next_page']);
// Use pagination to fetch next page.
$result = $this->api->get_forms('active', false, $result['pagination']['end_cursor'], '', 1);
// Assert forms and pagination exist.
$this->assertDataExists($result, 'forms');
$this->assertPaginationExists($result);
// Assert a single form was returned.
$this->assertCount(1, $result['forms']);
// Assert has_previous_page and has_next_page are correct.
$this->assertTrue($result['pagination']['has_previous_page']);
$this->assertTrue($result['pagination']['has_next_page']);
// Use pagination to fetch previous page.
$result = $this->api->get_forms('active', false, '', $result['pagination']['start_cursor'], 1);
// Assert forms and pagination exist.
$this->assertDataExists($result, 'forms');
$this->assertPaginationExists($result);
// Assert a single form was returned.
$this->assertCount(1, $result['forms']);
// Assert has_previous_page and has_next_page are correct.
$this->assertFalse($result['pagination']['has_previous_page']);
$this->assertTrue($result['pagination']['has_next_page']);
}
/**
* Test that get_legacy_forms() returns the expected data.
*
* @since 2.0.0
*
* @return void
*/
public function testGetLegacyForms()
{
$result = $this->api->get_legacy_forms();
// Assert forms and pagination exist.
$this->assertDataExists($result, 'legacy_landing_pages');
$this->assertPaginationExists($result);
// Iterate through each form, confirming no landing pages were included.
foreach ($result['legacy_landing_pages'] as $form) {
// Assert shape of object is valid.
$this->assertArrayHasKey('id', $form);
$this->assertArrayHasKey('name', $form);
$this->assertArrayHasKey('created_at', $form);
$this->assertArrayHasKey('type', $form);
$this->assertArrayHasKey('url', $form);
// Assert form is not a landing page i.e it is an embed.