-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtools.html
2368 lines (2198 loc) · 132 KB
/
tools.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
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
<!DOCTYPE html>
<html lang="en" ng-app="myModule">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="My Website.">
<meta name="author" content="Chris Parsons">
<link rel="icon" href="/src/imgs/mankey.ico">
<title>Chris Parsons WebSite</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link href='//fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<!-- Custom styles for this template -->
<link href="/src/css/cover.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"><\/script>')</script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<link rel="stylesheet" href="//getbootstrap.com/examples/jumbotron/jumbotron.css">
<script src="/src/js/menuControl.js"></script>
<!--<script src="/MyWebPage/src/js/menuControl.js"></script>-->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( ".accordion" ).accordion({
collapsible: true,
heightStyle: "content",
active: false
});
});
</script>
<script src="/src/syntax/prism.js"></script>
<link rel="stylesheet" href="/src/syntax/prism.css">
<link rel="stylesheet" href="/src/css/mycss.css">
<!--<link rel="stylesheet" href="/MyWebPage/src/css/mycss.css">-->
</head>
<body>
<div>
<div ng-include="'navBar.html'"></div>
</div>
<div class="jumbotron jumbotron-billboard">
<div class="img tools"></div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="my-header2">Tools and Frameworks</h1>
<p>Covering an assortment of tools and frameworks for a range of testing written in a few different languages.</p>
</div>
</div>
</div>
</div>
<div>
<div class="container" align="left">
<div class="row">
<div class="col-md-9">
<br />
<div>
<section class="tab container" ng-controller="myCtrl as tab">
<ul class="nav nav-pills">
<li ng-class="{ active: tab.isSet(1) }">
<a href ng-click="tab.setTab(1)">Jasmine</a></li>
<li ng-class="{ active: tab.isSet(2) }">
<a href ng-click="tab.setTab(2)">Protractor</a></li>
<li ng-class="{ active: tab.isSet(3) }">
<a href ng-click="tab.setTab(3)">Selenium</a></li>
<li ng-class="{ active: tab.isSet(4) }">
<a href ng-click="tab.setTab(4)">UI Automation</a></li>
<li ng-class="{ active: tab.isSet(5) }">
<a href ng-click="tab.setTab(5)">API</a></li>
<li ng-class="{ active: tab.isSet(6) }">
<a href ng-click="tab.setTab(6)">JMeter</a></li>
<li ng-class="{ active: tab.isSet(7) }">
<a href ng-click="tab.setTab(7)">Other Tools</a></li>
</ul>
<h4><br/></h4>
<div ng-show="tab.isSet(1)">
<blockquote>{{tab.selects[0].description}}
<p><br /></p>
<p>Languages: {{tab.selects[0].languages}}</p>
</blockquote>
<div class="accordion">
<div>Example 1</div>
<pre><code class="language-javascript">
describe("SERVICES & FACTORIES - authenticator Test Suite", function() {
"use strict";
// *******************************
// AUTHENTICATOR ANGULAR MODULE
// *******************************
var authenticatedTokenService,myCookies,authenticatorService,httpBackend,$window;
beforeEach(module('authenticator'));
beforeEach(module('ngCookies'));
beforeEach(module(function($provide) {
$window = {location: { replace: jasmine.createSpy()} };
$provide.value('$window', $window);
}));
beforeEach(inject(function($injector) {
authenticatedTokenService = $injector.get('AuthenticatedToken',[myCookies]);
authenticatorService = $injector.get('Authenticator',['$http', authenticatedTokenService, $window]);
myCookies = $injector.get('$cookieStore',[]);
httpBackend = $injector.get('$httpBackend');
}));
// ***********************
// AUTHENTICATOR FACTORY
// ***********************
describe('Authenticator Factory',function() {
// *********
// LOGIN
// *********
describe('login',function() {
it('Check that the login method is defined.',function() {
expect(authenticatorService.login).not.toEqual(undefined);
});
it('Check that when the login method is executed with valid credentials, the successCallback is called.',function() {
var creds, successCallbackSpy, errorCallbackSpy;
creds = {"userName":"administrator","password":"admin"};
successCallbackSpy = jasmine.createSpy();
errorCallbackSpy = jasmine.createSpy();
httpBackend.expectPOST('/tokens/', creds, function(headers) {
return headers['Content-Type'] === 'application/json';
}).respond(200, 'HELLO');
authenticatorService.login(creds, successCallbackSpy, errorCallbackSpy);
httpBackend.flush();
expect(successCallbackSpy).toHaveBeenCalled();
});
it('Check that when the login method is executed with invalid credentials, the errorCallback is called.',function() {
var invalidcreds, successCallbackSpy, errorCallbackSpy;
invalidcreds = {"userName":"admin2","password":"admin2"};
successCallbackSpy = jasmine.createSpy();
errorCallbackSpy = jasmine.createSpy();
httpBackend.expectPOST('/tokens/', invalidcreds, function(headers) {
return headers['Content-Type'] === 'application/json';
}).respond(500, 'BOO');
authenticatorService.login(invalidcreds, successCallbackSpy, errorCallbackSpy);
httpBackend.flush();
expect(errorCallbackSpy).toHaveBeenCalled();
});
});
});
});</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[0].example1}}</p>
<p><br/></p>
<div class="accordion">
<div>Example 2</div>
<pre><code class="language-javascript">
describe('CONTROLLERS - Settings Admin Test Cases', function() {
"use strict";
// **********************************************
// MYAPP CONTROLLER ANGULAR MODULE
// **********************************************
var scope,myAppCtrl,toaster,$window,loaderState,state,event;
beforeEach(module(
'myappctrl',
'toaster',
'flow',
'loaderstate',
));
beforeEach(module(function($provide) {
$window = {open: function(url) { return url;} };
$provide.value('$window', $window);
}));
beforeEach(inject(function($injector,$controller,$rootScope) {
scope = $rootScope.$new();
state = { go: function() {}};
event = {"bubbles":true,"cancelBubble":false,"isTrusted":true,"returnValue":true,"type":"change"};
toaster = $injector.get('toaster',[]);
loaderState = $injector.get('LoaderState');
myAppCtrl = $controller('MyAppCtrl',{
$scope:scope,
LoaderState:loaderState,
toaster:toaster,
$window:$window,
$state:state
});
}));
// ********
// added
// ********
describe('added',function() {
it('Check that execution of the added method returns true if getExtension returns txt.',function() {
var $flow = {"support":true,"supportDirectory":true,"files":[],"defaults":{"chunkSize":1048576,"forceChunkSize":false,"simultaneousUploads":3,"singleFile":false,"fileParameterName":"file","progressCallbacksInterval":500,"speedSmoothingFactor":0.1,"query":{},"headers":{},"withCredentials":false,"preprocess":null,"method":"multipart","testMethod":"GET","uploadMethod":"POST","prioritizeFirstAndLastChunk":false,"target":"/","testChunks":true,"generateUniqueIdentifier":null,"maxChunkRetries":0,"chunkRetryInterval":null,"permanentErrors":[404,415,500,501],"successStatuses":[200,201,202],"onDropStopPropagation":false},"opts":{"chunkSize":209715200,"forceChunkSize":false,"simultaneousUploads":3,"singleFile":true,"fileParameterName":"file","progressCallbacksInterval":500,"speedSmoothingFactor":0.1,"query":{},"headers":{},"withCredentials":false,"preprocess":null,"method":"octet","testMethod":"GET","uploadMethod":"PUT","prioritizeFirstAndLastChunk":false,"testChunks":false,"generateUniqueIdentifier":null,"maxChunkRetries":0,"chunkRetryInterval":null,"permanentErrors":[404,500,501],"successStatuses":[200,201,202],"onDropStopPropagation":false,"minFileSize":0},"events":{"catchall":[null]}};
var flowFile = {"name":"myFakeFile.txt","getExtension":function() {return "txt"}};
var toasterSpy = spyOn(toaster,'pop');
expect(scope.added(event, $flow, flowFile)).toBe(true);
expect(toasterSpy).not.toHaveBeenCalled();
});
});
});</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[0].example2}}</p>
<p><br/></p>
</div>
<div ng-show="tab.isSet(2)">
<blockquote ng-cloak>{{tab.selects[1].description}}
<p><br /></p>
<p>Languages: {{tab.selects[1].languages}}</p>
</blockquote>
<div class="accordion">
<div>Example 1</div>
<pre>
<code class="language-javascript">
// Import the methods.
var myServiceMethods = require("./libs/my-service-methods.js");
// Import the objects
var homePage = require("./pageobjs/homePage.js");
var commonBase;
describe("First Test Suite", function() {
"use strict";
beforeEach(function() {
myServiceMethods.login("admin","admin");
commonBase= new Date().getTime();
});
it('Check that the content of both tabs is correct.',function() {
// Add a new tree node.
myServiceMethods.createNewNode(commonBase + "_rootNode", commonBase + "_baseNode", "New_"
+ commonBase + "_testNode", true);
// Check that both tabs are shown.
expect(homePage.tab1.isDisplayed() && homePage.tab2.isDisplayed()).toBeTruthy();
// Click on tab1
homePage.tab1.click();
// Check that description and title stuff are shown.
expect(homePage.titleInputField.isDisplayed()
&& homePage.descriptionInputField.isDisplayed()).toBeTruthy();
// Click on tab2
homePage.tab2.click();
// Check that the root node part is shown.
expect(homePage.treeRoot().isDisplayed()).toBeTruthy();
});
});
</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[1].example1}}</p>
<p><br/></p>
</div>
<div ng-show="tab.isSet(3)">
<blockquote>{{tab.selects[2].description}}
<p><br /></p>
<p>Languages: {{tab.selects[2].languages}}</p>
</blockquote>
<div class="accordion">
<div>Example 1</div>
<pre><code class="language-java">
public class TestClass {
// Set up general variables
private static WebDriver driver;
private static AuthenticationFlow authenticationFlow;
private static HomePage homePage;
private String commonBase;
private static MyMethods myMethods;
// Add test specific variables
private final Date d = new Date();
@Rule
public final TestRule watcher = new TestWatcher() {
@Override
protected void starting(Description description) {
System.out.println("Starting test: " + description.getMethodName());
TabPageTree.setTestName(description.getMethodName());
}
@Override
protected void failed(Throwable e, Description description) {
myMethods.takeAScreenShot(TabPageTree.getTestName());
}
};
@Before
public void initializeDriver() {
// Go to the index page.
authenticationFlow.getToStartPosition();
commonBase = String.valueOf(d.getTime());
}
@BeforeClass
public static void installService() {
// Create the driver
driver = CreateDriver.setupDriver(AuthenticationFlow.runOnBrowser);
// Login
authenticationFlow = new AuthenticationFlow(driver);
authenticationFlow.login(AuthenticationFlow.USERNAME, AuthenticationFlow.PASSWORD);
homePage = new HomePage(driver);
myMethods = new MyMethods(driver);
// Wait for the page to load.
WebDriverWait wait = new WebDriverWait(driver, 6);
wait.until(ExpectedConditions.titleIs("My Web Service"));
new HTTPRequests(driver).addWorkingServicesAndSchemas();
}
@AfterClass
public static void closeTheDriver() {
driver.quit();
}
@After
public void killContent() {
HTTPRequests chris = new HTTPRequests(driver);
chris.deleteResource("/appconfig/content");
}
@Test
public void checkContentOfBothTabs() {
// Add a new node.
myMethods.createNewNode(commonBase + "_rootNode", commonBase + "_baseNode", "New_"
+ commonBase + "_testNode", true);
// Check that both tabs are shown.
assertTrue(homePage.tab1.isDisplayed() && homePage.tab2.isDisplayed());
// Click on tab1
homePage.tab1.click();
// Check that description and title stuff are shown.
assertTrue(homePage.titleInputField.isDisplayed()
&& homePage.descriptionInputField.isDisplayed());
// Click on tab2
homePage.tab2.click();
// Check that the root node part is shown.
assertTrue(homePage.treeRoot().isDisplayed());
}
}
</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[2].example1}}</p>
<p><br/></p>
<div class="accordion">
<div>Example 2</div>
<pre><code class="language-java">
public void login(String username, String password) {
webDriver.get(LOGIN_URL);
webDriver.manage().window().setSize(new Dimension(1040,744));
if(runOnBrowser.equals("ie") && !webDriver.getTitle().contains("My WebPage")) {
// Needed for IE certification issue only.
webDriver.get("javascript:document.getElementById('overridelink').click();");
}
assertThat(webDriver.getTitle(), is("My WebPage - Login"));
loginPage.setUserName(username);
loginPage.setPassword(password);
loginPage.clickLogin();
}
</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[2].example2}}</p>
<p><br/></p>
<div class="accordion">
<div>Python Create Driver</div>
<pre>
<code class="language-python">
# CREATE DRIVER #
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import *
from selenium.webdriver.support import expected_conditions
class CreateDriver(object):
def __init__(self):
print "new CreateDriver"
@staticmethod
def setupdriver(browser):
###############
# FIREFOX SETUP
##############
if browser == "firefox":
ffprofile = webdriver.FirefoxProfile()
ffprofile.set_preference("browser.helperApps.neverAsk.saveToDisk",
"application/zip,text/json")
ffprofile.set_preference("browser.download.folderList", 2)
ffprofile.set_preference("app.update.enabled", False)
driver = webdriver.Firefox(ffprofile)
##############
# CHROME SETUP
##############
else:
prefs = {"download.default_directory": "C:\\Chrome_Download_Dir"}
chromeopts = webdriver.ChromeOptions()
chromeopts.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome("C:\\chromedriver.exe", chrome_options=chromeopts)
return driver
def main():
driver = CreateDriver().setupdriver("chrome")
driver.get("//www.google.com")
search_button = WebDriverWait(driver, 5).until(
expected_conditions.visibility_of_element_located((By.XPATH, "//input[contains(@value, 'Feeling Lucky')]")))
search_button.click()
WebDriverWait(driver, 10).until(expected_conditions.title_is("Google Doodles"))
if __name__ == "__main__":
main()
</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[2].pythondriver}}</p>
<p><br/></p>
<div class="accordion">
<div>Python Page Objects</div>
<pre>
<code class="language-python">
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import *
from selenium.webdriver.support import expected_conditions
class AuthenticationObjects(object):
def __init__(self, driver):
self.driver = driver
def username_text_box(self):
return WebDriverWait(self.driver, 10).until(
expected_conditions.presence_of_element_located((By.XPATH, "//input[@placeholder='username']")))
def password_text_box(self):
return WebDriverWait(self.driver, 10).until(
expected_conditions.presence_of_element_located((By.XPATH, "//input[@placeholder='password']")))
def submit_button(self):
return WebDriverWait(self.driver, 10).until(
expected_conditions.presence_of_element_located((By.XPATH, "//button[@type='submit']")))
def fail_popup(self):
return WebDriverWait(self.driver, 10).until(
expected_conditions.presence_of_element_located((By.XPATH,
"//div[contains(@class,'pop-up-box')][contains(text(),'Invalid Credentials.')]")))
</code></pre>
</div>
<div class="accordion">
<div>Python Methods</div>
<pre>
<code class="language-python">
from AuthenticationObjects import AuthenticationObjects
import time
class LoginFlow(object):
def __init__(self, driver):
self.driver = driver
def send_user_name(self, username_string):
AuthenticationObjects(self.driver).username_text_box().send_keys(username_string)
def send_password(self, password_string):
AuthenticationObjects(self.driver).password_text_box().send_keys(password_string)
def click_submit(self):
AuthenticationObjects(self.driver).submit_button().click()
def check_for_popup(self, fail_bool):
if fail_bool:
AuthenticationObjects(self.driver).fail_popup().click()
else:
pass
def wait_for_string_to_be_url(self, url_string, time_to_wait):
count = 0
while url_string not in self.driver.current_url:
if count != time_to_wait:
time.sleep(1)
count = + 1
else:
raise Exception("Test failed because", url_string,
"was not found after ", time_to_wait, "seconds.")</code></pre>
</div>
<div class="accordion">
<div>Python Tests</div>
<pre>
<code class="language-python">
import unittest
from Libs.Methods.create_driver import CreateDriver
from Libs.Methods.login_flow import *
class AuthenticationTestSuite(unittest.TestCase):
def setUp(self):
self.driver = CreateDriver().setupdriver("firefox")
self.login_flow = LoginFlow(self.driver)
self.login_address = "//chrisp1985.ddns.net:9998/login.html"
def tearDown(self):
self.driver.quit()
def login_succeeds_if_password_and_user_are_correct_test(self):
# Get the login page.
self.driver.get(self.login_address)
# Send the user/password and press submit.
self.login_flow.send_user_name("admin")
self.login_flow.send_password("admin")
self.login_flow.click_submit()
# Wait for the url to contain the search string.
self.login_flow.wait_for_string_to_be_url("index", 10)
# Check that the title of the page is correct.
self.assertIn("Chris Parsons Website", self.driver.title)
def login_fails_if_password_is_incorrect_test(self):
# Get the login page.
self.driver.get(self.login_address)
# Send the user/password and press submit.
self.login_flow.send_user_name("admin")
self.login_flow.send_password("noob")
self.login_flow.click_submit()
# Check for the error popup
self.login_flow.check_for_popup(True)
def login_fails_if_username_is_incorrect_test(self):
self.driver.get(self.login_address)
self.login_flow.send_user_name("noob")
self.login_flow.send_password("admin")
self.login_flow.click_submit()
# Check for the error popup
self.login_flow.check_for_popup(True)
def login_fails_if_username_and_password_are_incorrect_test(self):
# Get the login page.
self.driver.get(self.login_address)
# Send the user/password and press submit.
self.login_flow.send_user_name("noob")
self.login_flow.send_password("noob")
self.login_flow.click_submit()
# Check for the error popup
self.login_flow.check_for_popup(True)</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[2].python1}}</p>
<p><br/></p>
</div>
<div ng-show="tab.isSet(4)">
<blockquote>{{tab.selects[3].description}}
<p><br /></p>
<p>Languages: {{tab.selects[3].languages}}</p>
</blockquote>
<div class="accordion">
<div>Example 1</div>
<pre><code class="language-csharp">
/**
* *** WAIT FOR AN OBJECT ***
* This waits for an object to appear in the application by constantly polling the available objects.
*
* @param winRoot
* The AutomationElement from which to start the search. If it's left blank, it'll query objects from the very top level.
*
* @param node
* A blank treenode to fill out the childTreeNode stuff.
*
* @param timeToWait
* The time to wait for the object to appear. If the timer exceeds this time, the method will fail.
*
* @param elementName
* The name of the element by the Page Objects method. Eg, to find the completion of the progress bar, this is 'progressBarComplete'.
*
* @param args
* The arguments required by the element as in the Page Objects.
*
* @return
* Returns the found object.
*/
public AutomationElement waitForObject(AutomationElement winRoot, TreeNode node, double timeToWait, String elementName, object[] args)
{
// Set the time.
DateTime timeAtStart = DateTime.Now;
DateTime now = new DateTime(1985, 10, 26, 13, 15, 00); // Back to the Future Day - Oct 26th 1985.
// Set the returned element to be null (so if the element isn't found, null is returned).
AutomationElement returnedEle = null;
// While the timer hasn't expired...
while (now.Subtract(timeAtStart).TotalSeconds < timeToWait)
{
try
{
// Create the object here.
MethodInfo method = typeof(PageObjects).GetMethod(elementName);
AutomationElement root = null;
if (winRoot == null)
{
root = AutomationElement.RootElement.FindChildByProcessId(AutomationMethods.processId);
}
else
{
root = winRoot;
}
// Invoke the element through reflection.
AutomationElement newEle = (AutomationElement)method.Invoke(new PageObjects(), args);
if (newEle.GetCurrentPropertyValue(AutomationElement.IsEnabledProperty).Equals(true))
{
// OMG, you found the element.
returnedEle = newEle;
break;
}
}
catch
{
// Just carry on.
}
// Reset the time.
now = DateTime.Now;
}
// Has the timer expired?
if (now.Subtract(timeAtStart).TotalSeconds > timeToWait)
{
Assert.Fail("Wait time was exceeded for element so test failed.");
}
// Return the element.
return returnedEle;
}
</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[3].example1}}</p>
<p><br/></p>
<div class="accordion">
<div>Example 2</div>
<pre><code class="language-csharp">
/*
* *** STOP A SERVICE ***
* This can stop the process to allow for checking that valid errors are displayed when a connection is lost.
*
* @param stop
* If stop is true, the service is stopped. If it's false, it's started.
*
* @param service
* This is the name of the service to stop.
*/
public void stopASpecificService(bool stop, String serviceName)
{
// Set services, and then get them.
ServiceController[] scServices;
scServices = ServiceController.GetServices();
// Iterate over the available services until...
foreach (ServiceController scTemp in scServices)
{
// ... you have found metadata service!
if (scTemp.ServiceName.Equals(serviceName))
{
if (stop)
{
// Stop the service and wait until it's stopped.
scTemp.Stop();
scTemp.WaitForStatus(ServiceControllerStatus.Stopped);
}
else
{
// Start the service and wait until it's started.
scTemp.Start();
scTemp.WaitForStatus(ServiceControllerStatus.Running);
}
// Wait until the service has stopped/started.
Thread.Sleep(2000);
}
}
}</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[3].example2}}</p>
<p><br/></p>
<div class="accordion">
<div>Example 3</div>
<pre><code class="language-csharp">
[Test]
public void Test1()
{
/*
* SUMMARY: Disconnect the service and check that valid error messages are displayed to the user when attempting to use the service.
*
* Test Steps
* 1. Add data to the application.
* 2. Disconnect the service.
* 3. Attempt to execute the run task.
*
* Expected Outcomes
* 1. The data is added successfully and all of the nodes are populated in the application.
* 2. The service is disconnected.
* 3. A popup is displayed, informing the user that the request cannot be processed.
*/
Console.WriteLine("Starting Test 1");
// Run the stuff before the test.
beforeTest();
int processId = MyApp_AutomationMethods.processId;
// Set the Main Window.
TreeNode node = new TreeNode();
MyApp_AutomationMethods ext = new MyApp_AutomationMethods();
UIAutomationMethods meths = new UIAutomationMethods();
// 2. Disconnect the service.
try {
meths.stopASpecificService(true, "MyCompany:MyApplication");
// 3. Attempt to execute the ‘Run’ task.
AutomationElement mainWindow = AutomationElement.RootElement.FindChildByProcessId(processId);
ext.clickRun();
// Check for the error and dismiss it.
new MyApp_AutomationMethods().readAndDismissError(AutomationElement.RootElement.FindChildByProcessId(processId),
node, "Could not execute the task. Please check if the application is running.");
Console.WriteLine("Test 1 Passed!");
}
finally
{
// Restart the service.
meths.stopASpecificService(false, "MyCompany:MyApplication");
}
}
</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[3].example3}}</p>
<p><br/></p>
</div>
<div ng-show="tab.isSet(5)">
<blockquote>{{tab.selects[4].description}}
<p><br /></p>
<p>Languages: {{tab.selects[4].languages}}</p>
</blockquote>
<div class="accordion">
<div>RestAssured</div>
<pre><code class="language-java">
/**
* *** GET TOKEN VIA REST-ASSURED ***
* This creates a request for a token, and returns the string response.
*
* @param username
* The user of the service.
* @param password
* The password of the user of the service.
* @return A string of the token response to use embedded in cookies.
*/
public String getTokenRestAssured(String username, String password)
{
return RestAssured.given().relaxedHTTPSValidation().contentType(ContentType.JSON).request()
.body("{\n" + " userName:\"" + username + "\",\n" + " password:\"" + password + "\"\n" + " }")
.when().post("//localhost:7753/tokenPath/").asString();
}
/**
* *** GET REQUEST VIA REST-ASSURED ***
* This creates a request to a resource location, and returns the response.
*
* @param resourceLocation
* The resource location to get.
* @return The response as a Rest Assured response, allowing further
* querying of status codes, messages etc.
*/
public Response getRequest(String resourceLocation)
{
return RestAssured.given().relaxedHTTPSValidation()
.cookie("customAuthToken", getTokenRestAssured("administrator", "admin")).when().get(resourceLocation);
}
/**
* *** PUT REQUEST VIA REST-ASSURED ***
* This creates a PUT request for a resource, and returns the response.
*
* @param bodyText
* The body of text to add to the request.
* @param resourceLocation
* The resource location to get.
* @return The response as a Rest Assured response, allowing further
* querying of status codes, messages etc.
*/
public Response putRequest(String bodyText, String resourceLocation)
{
return RestAssured.given().relaxedHTTPSValidation()
.cookie("customAuthToken", getTokenRestAssured("administrator", "admin")).request().body(bodyText).when()
.put(resourceLocation);
}
@Test
public void validGetRequestRestAssured()
{
// Add the resource
putRequest(
"trialText",
credsBasedRequest.URLString + "path/to/my/content/" + commonBase
+ "_validGetRequest").then().assertThat().statusCode(200);
// Check the contents
assertTrue(getRequest(
credsBasedRequest.URLString + "path/to/my/content/" + commonBase
+ "_validGetRequest").asString().contains("trialText"));
}
@Test
public void getInvalidURLRestAssured()
{
getRequest(credsBasedRequest.URLString + "path/to/my/con").then()
.assertThat().statusCode(404);
}
</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[4].restassured}}</p>
<p><br/></p>
<div class="accordion">
<div>RestSharp</div>
<pre><code class="language-csharp">
* *** GET THE TOKEN ***
* Executes a 'POST' command to get a token string back, which can then be used in cookies for further requests.
*
* @param userName
* This is the name of the ... user... for the metadata service.
*
* @param passWord
* This is the password that the user logs into the web service with.
*/
public String getAToken(String userName, String passWord)
{
// This needs to be set to avoid SSL issues.
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
// Set the Client and the Request.
var client = new RestClient("//localhost:7753");
var request = new RestRequest("tokens", Method.POST);
// Add the details and get the token string.
request.AddParameter("application/json", "{userName:\"" + userName + "\",password:\"" + passWord + "\"}", ParameterType.RequestBody);
return client.Execute(request).Content;
}
/**
* *** GET WHATEVER ***
* Executes a 'GET' command for the request path supplied.
*
* @param requestPath
* This is the URI for the request.
*
* @return
* This is the returned content from the response as a string.
*/
public String getWhatever(String requestPath)
{
// This needs to be set to avoid SSL issues.
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
// Set the Client and the Request.
RestClient client = new RestClient("//localhost:7753");
RestRequest request = new RestRequest(requestPath, Method.GET);
// Add the token and the pathToFile to the request.
request.AddCookie("customAuthToken", getAToken("administrator","admin"));
// Execute and return the response as a string.
return client.Execute(request).Content;
}
</code></pre>
</div>
<p><br/></p>
<p>{{tab.selects[4].restsharp}}</p>
<p><br/></p>
<div class="accordion">
<div>Mocha</div>
<pre><code class="language-javascript">
var should = require('C:\\Users\\parsonsc\\AppData\\Roaming\\npm\\node_modules\\should');
var request = require('C:\\Users\\parsonsc\\AppData\\Roaming\\npm\\node_modules\\supertest');
describe('Mocha Tests', function() {
// GENERAL
var url = '//mylocalservice:7753';
// USERS
var testUser = 'admin';
describe('2.3.1.2 PUT /path/to/user/{username}', function() {
it('PUTUSER-1', function(done) {
// *******************************************************
// Summary
// Confirm that the API accepts HTTP PUT requests for creating users when all mandatory fields are set in the body.
// Preconditions
// Fully Operable WebService is available.
// WebService is fully licensed.
// *******************************************************
request(url)
.put('/path/to/user/'+testUser) // Set the URI you're trying to PUT.
.set('Authorization', 'Basic c2VwdXJhLW9wZW5pZDpwYXNzd29yZA==') // set the Custom Header.
.set('Content-Type', 'application/json') // Set the Content Type header.
.send({
'authtype':'oauth2',
'id':testUser,
'password':testUser,
'name':testUser,
'type':'admin',
'role':'Manager',
'description':'TRIAL USER',
'defaultlanguage':'en'
}) // Send the Data that is contained within the body of the command.
.end(function(err, res) {
if (err) {
throw err;