Menu

[r1466]: / trunk / UnitTests / GoogleAPITests.cs  Maximize  Restore  History

Download this file

631 lines (511 with data), 24.4 kB

  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
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.People.v1;
using Google.Apis.PeopleService.v1.Data;
using Google.Apis.Util.Store;
using NodaTime;
using NUnit.Framework;
using Serilog;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace GoContactSyncMod.UnitTests
{
[TestFixture]
public class GoogleAPITests
{
private EventsResource eventsService = null;
private CalendarListEntry primaryCalendar = null;
[OneTimeSetUp]
public void Init()
{
LoadSettings(out var gmailUsername, out _);
var scopes = new List<string>();
//Contacts-Scope
scopes.Add(Google.Apis.People.v1.PeopleService.Scope.Contacts);
//Calendar-Scope
scopes.Add(CalendarService.Scope.Calendar);
UserCredential credential;
var jsonSecrets = Properties.Resources.client_secrets;
using (var stream = new MemoryStream(jsonSecrets))
{
var Folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GoContactSyncMOD\\";
var AuthFolder = Folder + "\\Auth\\";
var fDS = new FileDataStore(AuthFolder, true);
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets, scopes, gmailUsername, CancellationToken.None,
fDS).Result;
var initializer = new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credential
};
var CalendarRequest = new CalendarService(initializer);
var list = CalendarRequest.CalendarList.List().Execute().Items;
foreach (var calendar in list)
{
if (calendar.Primary != null && calendar.Primary.Value)
{
primaryCalendar = calendar;
break;
}
}
if (primaryCalendar == null)
{
throw new Exception("Primary Calendar not found");
}
eventsService = CalendarRequest.Events;
}
}
[Test]
public void CreateNewPerson()
{
LoadSettings(out var gmailUsername, out _);
PeopleService service;
var scopes = new List<string>();
//Contacts-Scope
scopes.Add(Google.Apis.People.v1.PeopleService.Scope.Contacts);
//Calendar-Scope
scopes.Add(CalendarService.Scope.Calendar);
UserCredential credential;
var jsonSecrets = Properties.Resources.client_secrets;
using (var stream = new MemoryStream(jsonSecrets))
{
var Folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GoContactSyncMOD\\";
var AuthFolder = Folder + "\\Auth\\";
var fDS = new FileDataStore(AuthFolder, true);
var clientSecrets = GoogleClientSecrets.Load(stream);
credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
clientSecrets.Secrets,
scopes.ToArray(),
gmailUsername,
CancellationToken.None,
fDS).
Result;
var initializer = new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credential
};
//var parameters = new OAuth2Parameters
//{
// ClientId = clientSecrets.Secrets.ClientId,
// ClientSecret = clientSecrets.Secrets.ClientSecret,
// // Note: AccessToken is valid only for 60 minutes
// AccessToken = credential.Token.AccessToken,
// RefreshToken = credential.Token.RefreshToken
//};
//var settings = new RequestSettings("GoContactSyncMod", parameters);
service = GoogleServices.CreatePeopleService(initializer);
}
#region Delete previously created test contact.
var peopleResource = new Google.Apis.PeopleService.v1.PeopleResource(service);
var query = peopleResource.Connections.List("people/me");
//{
// NumberToRetrieve = 500;
//};
var feed = query.Execute();
Log.Information("Loaded Google contacts");
foreach (var entry in feed.Connections)
{
var pm = ContactPropertiesUtils.GetGoogleContactPrimaryEmail(entry);
if (pm != null && pm.Value == "johndoe@example.com")
{
peopleResource.CreateContact(entry).Execute();
Log.Information("Deleted Google contact");
//break;
}
}
#endregion
var newEntry = new Person();
var name = ContactPropertiesUtils.GetGoogleContactName(newEntry);
if (name == null)
{
name = new Name();
newEntry.Names.Add(name);
}
name.UnstructuredName = "John Doe";
var primaryEmail = new EmailAddress
{
Value = "johndoe@example.com",
Metadata = new FieldMetadata
{
Primary = true
},
Type = "work"
};
newEntry.EmailAddresses.Add(primaryEmail);
var phoneNumber = new PhoneNumber
{
Value = "555-555-5551",
Metadata = new FieldMetadata
{
Primary = true
},
Type = "mobile"
};
newEntry.PhoneNumbers.Add(phoneNumber);
var address = new Address
{
StreetAddress = "123 somewhere lane",
Metadata = new FieldMetadata
{
Primary = true
},
Type = "home"
};
newEntry.Addresses.Add(address);
newEntry.Biographies.Add(new Biography { Value = "Who is this guy?" });
//var feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
var createdEntry = peopleResource.CreateContact(newEntry).Execute();
Log.Information("Created Google contact");
Assert.IsNotNull(createdEntry.ResourceName);
_ = peopleResource.UpdateContact(createdEntry, createdEntry.ResourceName).Execute();
Log.Information("Updated Google contact");
//delete test contacts
peopleResource.DeleteContact(createdEntry.ResourceName).Execute();
Log.Information("Deleted Google contact");
}
[Test]
public void CreateNewAppointment()
{
#region Delete previously created test contact.
var query = eventsService.List(primaryCalendar.Id);
query.MaxResults = 500;
query.TimeMin = DateTime.Now.AddDays(-10);
query.TimeMax = DateTime.Now.AddDays(10);
var feed = query.Execute();
Log.Information("Loaded Google appointments");
foreach (var entry in feed.Items)
{
if (entry.Summary != null && entry.Summary.Contains("GCSM Test Appointment") && !entry.Status.Equals("cancelled"))
{
Log.Information("Deleting Google appointment:" + entry.Summary + " - " + entry.Start.DateTime.ToString());
eventsService.Delete(primaryCalendar.Id, entry.Id);
Log.Information("Deleted Google appointment");
//break;
}
}
#endregion
var newEntry = Factory.NewEvent();
newEntry.Summary = "GCSM Test Appointment";
newEntry.Start.DateTime = DateTime.Now;
newEntry.End.DateTime = DateTime.Now;
var createdEntry = eventsService.Insert(newEntry, primaryCalendar.Id).Execute();
Log.Information("Created Google appointment");
Assert.IsNotNull(createdEntry.Id);
var updatedEntry = eventsService.Update(createdEntry, primaryCalendar.Id, createdEntry.Id).Execute();
Log.Information("Updated Google appointment");
//delete test contacts
eventsService.Delete(primaryCalendar.Id, updatedEntry.Id).Execute();
Log.Information("Deleted Google appointment");
}
[Test]
public void Test_OldRecurringAppointment()
{
#region Delete previously created test contact.
var query = eventsService.List(primaryCalendar.Id);
query.MaxResults = 500;
query.TimeMin = DateTime.Now.AddDays(-10);
query.TimeMax = DateTime.Now.AddDays(10);
//query.Q = "GCSM Test Appointment";
var feed = query.Execute();
Log.Information("Loaded Google appointments");
foreach (var entry in feed.Items)
{
if (entry.Summary != null && entry.Summary.Contains("GCSM Test Appointment") && !entry.Status.Equals("cancelled"))
{
Log.Information("Deleting Google appointment:" + entry.Summary + " - " + entry.Start.DateTime.ToString());
eventsService.Delete(primaryCalendar.Id, entry.Id);
Log.Information("Deleted Google appointment");
//break;
}
}
#endregion
var zone = DateTimeZoneProviders.Tzdb["Europe/Warsaw"];
var e1_start = new LocalDateTime(1970, 10, 14, 10, 0, 0);
var e1_start_zoned = e1_start.InZoneLeniently(zone);
var e1_start_utc = e1_start_zoned.ToDateTimeUtc();
_ = new LocalDateTime(1970, 10, 14, 11, 0, 0);
_ = e1_start.InZoneLeniently(zone);
var e1_end_utc = e1_start_zoned.ToDateTimeUtc();
var s = new EventDateTime
{
DateTime = e1_start_utc,
TimeZone = "Europe/Warsaw"
};
var e = new EventDateTime
{
DateTime = e1_end_utc,
TimeZone = "Europe/Warsaw"
};
var e1 = new Google.Apis.Calendar.v3.Data.Event()
{
Summary = "Birthday 1",
Start = s,
End = e,
Recurrence = new string[] { "RRULE:FREQ=YEARLY;BYMONTHDAY=14;BYMONTH=10" }
};
Assert.AreEqual("1970-10-14T09:00:00.000Z", e1.Start.DateTimeRaw);
var c1 = eventsService.Insert(e1, primaryCalendar.Id).Execute();
Assert.AreEqual("1970-10-14T10:00:00+01:00", c1.Start.DateTimeRaw);
var e2_start = new LocalDateTime(2000, 10, 14, 10, 0, 0);
var e2_start_zoned = e2_start.InZoneLeniently(zone);
var e2_start_utc = e2_start_zoned.ToDateTimeUtc();
_ = new LocalDateTime(2000, 10, 14, 11, 0, 0);
_ = e2_start.InZoneLeniently(zone);
var e2_end_utc = e2_start_zoned.ToDateTimeUtc();
var ss = new EventDateTime
{
DateTime = e2_start_utc,
TimeZone = "Europe/Warsaw"
};
var ee = new EventDateTime
{
DateTime = e2_end_utc,
TimeZone = "Europe/Warsaw"
};
var e2 = new Google.Apis.Calendar.v3.Data.Event()
{
Summary = "Birthday 2",
Start = ss,
End = ee,
Recurrence = new string[] { "RRULE:FREQ=YEARLY;BYMONTHDAY=14;BYMONTH=10" }
};
Assert.AreEqual("2000-10-14T08:00:00.000Z", e2.Start.DateTimeRaw);
var c2 = eventsService.Insert(e2, primaryCalendar.Id).Execute();
Assert.AreEqual("2000-10-14T10:00:00+02:00", c2.Start.DateTimeRaw);
Log.Information("Created Google appointment");
Assert.IsNotNull(c1.Id);
//delete test contacts
eventsService.Delete(primaryCalendar.Id, c1.Id).Execute();
eventsService.Delete(primaryCalendar.Id, c2.Id).Execute();
Log.Information("Deleted Google appointment");
}
[Test]
public void Test_RetrieveRecurrenceInstance()
{
var e = new Google.Apis.Calendar.v3.Data.Event()
{
Summary = "AN_OUTLOOK_TEST_APPOINTMENT",
Start = new EventDateTime()
{
DateTime = new DateTime(2020, 6, 3, 15, 0, 0),
TimeZone = "Europe/Warsaw"
},
End = new EventDateTime()
{
DateTime = new DateTime(2020, 6, 3, 16, 0, 0),
TimeZone = "Europe/Warsaw"
},
Recurrence = new string[] { "RRULE:FREQ=WEEKLY;UNTIL=20200625;BYDAY=WE" }
};
e = eventsService.Insert(e, primaryCalendar.Id).Execute();
Assert.IsNotNull(e.Id);
var r = eventsService.Instances(primaryCalendar.Id, e.Id);
var dt = new DateTime(2020, 6, 10, 13, 0, 0, DateTimeKind.Utc);
var s = dt.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:sszzz");
Assert.AreEqual("2020-06-10T15:00:00+02:00", s);
r.OriginalStart = "2020-06-10T15:00:00+02:00";
var instances = r.Execute();
Assert.IsNotNull(instances);
Assert.AreEqual(1, instances.Items.Count);
//delete test contacts
eventsService.Delete(primaryCalendar.Id, e.Id).Execute();
Log.Information("Deleted Google appointment");
}
[Test]
public void CreateContactWithLargeNotes()
{
LoadSettings(out var gmailUsername, out _);
PeopleService service;
var scopes = new List<string>();
//Contacts-Scope
scopes.Add(Google.Apis.People.v1.PeopleService.Scope.Contacts);
//Calendar-Scope
scopes.Add(CalendarService.Scope.Calendar);
UserCredential credential;
var jsonSecrets = Properties.Resources.client_secrets;
using (var stream = new MemoryStream(jsonSecrets))
{
var Folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\GoContactSyncMOD\\";
var AuthFolder = Folder + "\\Auth\\";
var fDS = new FileDataStore(AuthFolder, true);
var clientSecrets = GoogleClientSecrets.Load(stream);
credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
clientSecrets.Secrets,
scopes.ToArray(),
gmailUsername,
CancellationToken.None,
fDS).
Result;
var initializer = new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credential
};
/*var parameters = new OAuth2Parameters
{
ClientId = clientSecrets.Secrets.ClientId,
ClientSecret = clientSecrets.Secrets.ClientSecret,
// Note: AccessToken is valid only for 60 minutes
AccessToken = credential.Token.AccessToken,
RefreshToken = credential.Token.RefreshToken
};
var settings = new RequestSettings("GoContactSyncMod", parameters);*/
service = GoogleServices.CreatePeopleService(initializer);
}
#region Delete previously created test contact.
var peopleResource = new Google.Apis.PeopleService.v1.PeopleResource(service);
var query = peopleResource.Connections.List("people/me");
//{
// NumberToRetrieve = 500
//};
var feed = query.Execute();
Log.Information("Loaded Google contacts");
foreach (var entry in feed.Connections)
{
var pm = ContactPropertiesUtils.GetGoogleContactPrimaryEmail(entry);
if (pm != null && pm.Value == "johndoe@example.com")
{
peopleResource.DeleteContact(entry.ResourceName).Execute();
Log.Information("Deleted Google contact");
//break;
}
}
#endregion
var newEntry = new Person();
var name = ContactPropertiesUtils.GetGoogleContactName(newEntry);
if (name == null)
{
name = new Name();
newEntry.Names.Add(name);
}
name.UnstructuredName = "John Doe";
var primaryEmail = new EmailAddress
{
Value = "johndoe@example.com",
Metadata = new FieldMetadata { Primary = true },
Type = "work"
};
newEntry.EmailAddresses.Add(primaryEmail);
var phoneNumber = new PhoneNumber
{
Value = "555-555-5551",
Metadata = new FieldMetadata { Primary = true },
Type = "mobile"
};
newEntry.PhoneNumbers.Add(phoneNumber);
var address = new Address
{
StreetAddress = "123 somewhere lane",
Metadata = new FieldMetadata { Primary = true },
Type = "home"
};
newEntry.Addresses.Add(address);
newEntry.Biographies.Add(new Biography { Value = new string('*', 150000) });
//var feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));
try
{
var createdEntry = peopleResource.CreateContact(newEntry).Execute();
Log.Information("Created Google contact");
Assert.IsNotNull(createdEntry.ResourceName);
_ = peopleResource.UpdateContact(createdEntry, createdEntry.ResourceName).Execute();
Log.Information("Updated Google contact");
//delete test contacts
peopleResource.DeleteContact(createdEntry.ResourceName).Execute();
}
catch (Google.GoogleApiException ex) when (ex.Error != null && ex.Error.ErrorResponseContent.Contains("Request data is too large."))
{
Log.Information(ex,"Exception");
}
Log.Information("Deleted Google contact");
}
internal static void LoadSettings(out string gmailUsername, out string syncProfile, out string syncContactsFolder, out string syncAppointmentsFolder)
{
var regKeyAppRoot = LoadSettings(out gmailUsername, out syncProfile);
syncContactsFolder = "";
syncAppointmentsFolder = "";
Synchronizer.SyncAppointmentsGoogleFolder = "";
//First, check if there is a folder called GCSMTestContacts available, if yes, use them
var outlookContactFolders = new ArrayList();
var outlookAppointmentFolders = new ArrayList();
var folders = Synchronizer.OutlookNameSpace.Folders;
foreach (Microsoft.Office.Interop.Outlook.Folder folder in folders)
{
try
{
SettingsForm.GetOutlookMAPIFolders(outlookContactFolders, outlookAppointmentFolders, folder);
}
catch (Exception e)
{
Log.Warning("Error getting available Outlook folders: " + e.Message);
}
}
foreach (OutlookFolder folder in outlookContactFolders)
{
if (folder.FolderName.ToUpper().Contains("GCSMTestContacts".ToUpper()))
{
Log.Information("Uses Test folder: " + folder.DisplayName);
syncContactsFolder = folder.FolderID;
break;
}
}
foreach (OutlookFolder folder in outlookAppointmentFolders)
{
if (folder.FolderName.ToUpper().Contains("GCSMTestAppointments".ToUpper()))
{
Log.Information("Uses Test folder: " + folder.DisplayName);
syncAppointmentsFolder = folder.FolderID;
break;
}
}
if (string.IsNullOrEmpty(syncContactsFolder))
{
if (regKeyAppRoot.GetValue("SyncContactsFolder") != null)
{
syncContactsFolder = regKeyAppRoot.GetValue("SyncContactsFolder") as string;
}
}
if (string.IsNullOrEmpty(syncAppointmentsFolder))
{
if (regKeyAppRoot.GetValue("SyncAppointmentsFolder") != null)
{
syncAppointmentsFolder = regKeyAppRoot.GetValue("SyncAppointmentsFolder") as string;
}
}
if (string.IsNullOrEmpty(Synchronizer.SyncAppointmentsGoogleFolder))
{
if (regKeyAppRoot.GetValue("SyncAppointmentsGoogleFolder") != null)
{
Synchronizer.SyncAppointmentsGoogleFolder = regKeyAppRoot.GetValue("SyncAppointmentsGoogeFolder") as string;
}
}
}
private static Microsoft.Win32.RegistryKey LoadSettings(out string gmailUsername, out string syncProfile)
{
//sync.LoginToGoogle(ConfigurationManager.AppSettings["Gmail.Username"], ConfigurationManager.AppSettings["Gmail.Password"]);
//ToDo: Reading the username and config from the App.Config file doesn't work. If it works, consider special characters like & = &amp; in the XML file
//ToDo: Maybe add a common Test account to the App.config and read it from there, encrypt the password
//For now, read the userName from the Registry (same settings as for GoogleContactsSync Application
gmailUsername = "";
const string appRootKey = SettingsForm.AppRootKey;
var regKeyAppRoot = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(appRootKey);
syncProfile = "Default Profile";
if (regKeyAppRoot.GetValue("SyncProfile") != null)
{
syncProfile = regKeyAppRoot.GetValue("SyncProfile") as string;
}
regKeyAppRoot = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(appRootKey + (syncProfile != null ? ('\\' + syncProfile) : ""));
if (regKeyAppRoot.GetValue("Username") != null)
{
gmailUsername = regKeyAppRoot.GetValue("Username") as string;
}
return regKeyAppRoot;
}
private void Logger_LogUpdated(string message)
{
Console.WriteLine(message);
}
}
}
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.