You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Tests.cs 19 kB

10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. using Discord.Rest;
  2. using Microsoft.VisualStudio.TestTools.UnitTesting;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace Discord.Tests
  9. {
  10. // these tests are really bad
  11. // we're never going to look at them again
  12. // but in case i do decide to look at them again they are still here
  13. /*
  14. [TestClass]
  15. public class Tests
  16. {
  17. private const int EventTimeout = 10000; //Max time in milliseconds to wait for an event response from our test actions
  18. private static DiscordSocketClient _hostBot, _targetBot, _observerBot;
  19. private static Guild _testGuild;
  20. private static TextChannel _testGuildChannel;
  21. private static Random _random;
  22. private static PublicInvite _testGuildInvite;
  23. private static TestContext _context;
  24. private static string _hostToken;
  25. private static string _observerToken;
  26. private static string _targetToken;
  27. private static string GetRandomText()
  28. {
  29. lock (_random)
  30. return $"test_{_random.Next()}";
  31. }
  32. #region Initialization
  33. [ClassInitialize]
  34. public static void Initialize(TestContext testContext)
  35. {
  36. _context = testContext;
  37. _hostToken = Environment.GetEnvironmentVariable("discord-unit-host_token");
  38. _observerToken = Environment.GetEnvironmentVariable("discord-unit-observer_token");
  39. _targetToken = Environment.GetEnvironmentVariable("discord-unit-target_token");
  40. }
  41. [TestMethod]
  42. [Priority(1)]
  43. public async Task TestInitialize()
  44. {
  45. _context.WriteLine("Initializing.");
  46. _random = new Random();
  47. _hostBot = new DiscordSocketClient(_hostToken);
  48. _targetBot = new DiscordSocketClient(_targetToken);
  49. _observerBot = new DiscordSocketClient(_observerToken);
  50. await _hostBot.Login();
  51. await Task.Delay(3000);
  52. //Cleanup existing Guilds
  53. (await _hostBot.GetGuilds()).Select(x => x.Owner.Id == _hostBot.CurrentUser.Id ? x.Delete() : x.Leave());
  54. //Create new Guild and invite the other bots to it
  55. _testGuild = await _hostBot.CreateGuild("Discord.Net Testing", _hostBot.GetOptimalVoiceRegion());
  56. await Task.Delay(1000);
  57. PublicInvite invite = await _testGuild.CreateInvite(60, 3, false, false);
  58. _testGuildInvite = invite;
  59. _context.WriteLine($"Host: {_hostBot.CurrentUser.Username} in {(await _hostBot.GetGuilds()).Count()}");
  60. }
  61. [TestMethod]
  62. [Priority(2)]
  63. public async Task TestTokenLogin_Ready()
  64. {
  65. AssertEvent(
  66. "READY never received",
  67. async () => await _observerBot.Login(),
  68. x => _observerBot.Connected += x,
  69. x => _observerBot.Connected -= x,
  70. null,
  71. true);
  72. (await _observerBot.GetGuilds()).Select(x => x.Owner.Id == _observerBot.CurrentUser.Id ? x.Delete() : x.Leave());
  73. await _observerBot.RestClient.Send(new API.Rest.AcceptInviteRequest(_testGuildInvite.Code));
  74. }
  75. [TestMethod]
  76. [Priority(2)]
  77. public async Task TestReady()
  78. {
  79. AssertEvent(
  80. "READY never received",
  81. async () => await _targetBot.Login(),
  82. x => _targetBot.Connected += x,
  83. x => _targetBot.Connected -= x,
  84. null,
  85. true);
  86. (await _targetBot.GetGuilds()).Select(x => x.Owner.Id == _targetBot.CurrentUser.Id ? x.Delete() : x.Leave());
  87. _testGuildChannel = _testGuild.DefaultChannel;
  88. }
  89. #endregion
  90. // Guilds
  91. #region Guild Tests
  92. [TestMethod]
  93. [Priority(3)]
  94. public void TestJoinedGuild()
  95. {
  96. AssertEvent<GuildEventArgs>(
  97. "Never Got JoinedGuild",
  98. async () => await _targetBot.RestClient.Send(new API.Rest.AcceptInviteRequest(_testGuildInvite.Code)),
  99. x => _targetBot.JoinedGuild += x,
  100. x => _targetBot.JoinedGuild -= x);
  101. }
  102. #endregion
  103. #region Channel Tests
  104. //Channels
  105. [TestMethod]
  106. public void TestCreateTextChannel()
  107. {
  108. GuildChannel channel = null;
  109. string name = GetRandomText();
  110. AssertEvent<ChannelEventArgs>(
  111. "ChannelCreated event never received",
  112. async () => channel = await _testGuild.CreateTextChannel(name),
  113. x => _targetBot.ChannelCreated += x,
  114. x => _targetBot.ChannelCreated -= x,
  115. (s, e) => e.Channel.Id == channel.Id);
  116. AssertEvent<ChannelEventArgs>(
  117. "ChannelDestroyed event never received",
  118. async () => await channel.Delete(),
  119. x => _targetBot.ChannelDestroyed += x,
  120. x => _targetBot.ChannelDestroyed -= x,
  121. (s, e) => e.Channel.Id == channel.Id);
  122. }
  123. [TestMethod]
  124. public void TestCreateVoiceChannel()
  125. {
  126. GuildChannel channel = null;
  127. string name = GetRandomText();
  128. AssertEvent<ChannelEventArgs>(
  129. "ChannelCreated event never received",
  130. async () => channel = await _testGuild.CreateVoiceChannel(name),
  131. x => _targetBot.ChannelCreated += x,
  132. x => _targetBot.ChannelCreated -= x,
  133. (s, e) => e.Channel.Id == channel.Id);
  134. AssertEvent<ChannelEventArgs>(
  135. "ChannelDestroyed event never received",
  136. async () => await channel.Delete(),
  137. x => _targetBot.ChannelDestroyed += x,
  138. x => _targetBot.ChannelDestroyed -= x,
  139. (s, e) => e.Channel.Id == channel.Id);
  140. }
  141. [TestMethod]
  142. [ExpectedException(typeof(Net.HttpException))]
  143. public async Task TestCreateChannel_NoName()
  144. {
  145. await _testGuild.CreateTextChannel($"");
  146. }
  147. [TestMethod]
  148. public async Task Test_CreateGetChannel()
  149. {
  150. var name = GetRandomText();
  151. var channel = await _testGuild.CreateTextChannel(name);
  152. var get_channel = _testGuild.GetChannel(channel.Id);
  153. Assert.AreEqual(channel.Id, get_channel.Id, "ID of Channel and GetChannel were not equal.");
  154. }
  155. [TestMethod]
  156. public void TestSendTyping()
  157. {
  158. var channel = _testGuildChannel;
  159. AssertEvent<TypingEventArgs>(
  160. "UserUpdated event never fired.",
  161. async () => await channel.TriggerTyping(),
  162. x => _targetBot.UserIsTyping += x,
  163. x => _targetBot.UserIsTyping -= x);
  164. }
  165. [TestMethod]
  166. public void TestEditChannel()
  167. {
  168. var channel = _testGuildChannel;
  169. AssertEvent<ChannelUpdatedEventArgs>(
  170. "ChannelUpdated Never Received",
  171. async () => await channel.Modify(x =>
  172. {
  173. x.Name = GetRandomText();
  174. x.Topic = $"topic - {GetRandomText()}";
  175. x.Position = 26;
  176. }),
  177. x => _targetBot.ChannelUpdated += x,
  178. x => _targetBot.ChannelUpdated -= x);
  179. }
  180. [TestMethod]
  181. public void TestChannelMention()
  182. {
  183. var channel = _testGuildChannel;
  184. Assert.AreEqual($"<#{channel.Id}>", channel.Mention, "Generated channel mention was not the expected channel mention.");
  185. }
  186. [TestMethod]
  187. public void TestChannelUserCount()
  188. {
  189. Assert.AreEqual(3, _testGuildChannel.Users.Count(), "Read an incorrect number of users in a channel");
  190. }
  191. #endregion
  192. #region Message Tests
  193. //Messages
  194. [TestMethod]
  195. public async Task TestMessageEvents()
  196. {
  197. string name = GetRandomText();
  198. var channel = await _testGuild.CreateTextChannel(name);
  199. _context.WriteLine($"Channel Name: {channel.Name} / {channel.Guild.Name}");
  200. string text = GetRandomText();
  201. Message message = null;
  202. AssertEvent<MessageEventArgs>(
  203. "MessageCreated event never received",
  204. async () => message = await channel.SendMessage(text),
  205. x => _targetBot.MessageReceived += x,
  206. x => _targetBot.MessageReceived -= x,
  207. (s, e) => e.Message.Text == text);
  208. AssertEvent<MessageUpdatedEventArgs>(
  209. "MessageUpdated event never received",
  210. async () => await message.Modify(x =>
  211. {
  212. x.Content = text + " updated";
  213. }),
  214. x => _targetBot.MessageUpdated += x,
  215. x => _targetBot.MessageUpdated -= x,
  216. (s, e) => e.Before.Text == text && e.After.Text == text + " updated");
  217. AssertEvent<MessageEventArgs>(
  218. "MessageDeleted event never received",
  219. async () => await message.Delete(),
  220. x => _targetBot.MessageDeleted += x,
  221. x => _targetBot.MessageDeleted -= x,
  222. (s, e) => e.Message.Id == message.Id);
  223. }
  224. [TestMethod]
  225. public async Task TestDownloadMessages()
  226. {
  227. string name = GetRandomText();
  228. var channel = await _testGuild.CreateTextChannel(name);
  229. for (var i = 0; i < 10; i++) await channel.SendMessage(GetRandomText());
  230. while (channel.Discord.MessageQueue.Count > 0) await Task.Delay(100);
  231. var messages = await channel.GetMessages(10);
  232. Assert.AreEqual(10, messages.Count(), "Expected 10 messages in downloaded array, did not see 10.");
  233. }
  234. [TestMethod]
  235. public async Task TestSendTTSMessage()
  236. {
  237. var channel = await _testGuild.CreateTextChannel(GetRandomText());
  238. AssertEvent<MessageEventArgs>(
  239. "MessageCreated event never fired",
  240. async () => await channel.SendMessage(GetRandomText(), true),
  241. x => _targetBot.MessageReceived += x,
  242. x => _targetBot.MessageReceived -= x,
  243. (s, e) => e.Message.IsTTS);
  244. }
  245. #endregion
  246. #region User Tests
  247. [TestMethod]
  248. public async Task TestUserMentions()
  249. {
  250. var user = (await _targetBot.GetGuild(_testGuild.Id)).CurrentUser;
  251. Assert.AreEqual($"<@{user.Id}>", user.Mention);
  252. }
  253. [TestMethod]
  254. public void TestUserEdit()
  255. {
  256. var user = _testGuild.GetUser(_targetBot.CurrentUser.Id);
  257. AssertEvent<UserUpdatedEventArgs>(
  258. "UserUpdated never fired",
  259. async () => await user.Modify(x =>
  260. {
  261. x.Deaf = true;
  262. x.Mute = true;
  263. }),
  264. x => _targetBot.UserUpdated += x,
  265. x => _targetBot.UserUpdated -= x);
  266. }
  267. [TestMethod]
  268. public void TestEditSelf()
  269. {
  270. throw new NotImplementedException();
  271. /*var name = RandomText
  272. AssertEvent<UserUpdatedEventArgs>(
  273. "UserUpdated never fired",
  274. async () => await _targetBot.CurrentUser.Modify(TargetPassword, name),
  275. x => _obGuildBot.UserUpdated += x,
  276. x => _obGuildBot.UserUpdated -= x,
  277. (s, e) => e.After.Username == name);
  278. }*/
  279. /*
  280. [TestMethod]
  281. public void TestSetStatus()
  282. {
  283. AssertEvent<UserUpdatedEventArgs>(
  284. "UserUpdated never fired",
  285. async () => await SetStatus(_targetBot, UserStatus.Idle),
  286. x => _observerBot.UserUpdated += x,
  287. x => _observerBot.UserUpdated -= x,
  288. (s, e) => e.After.Status == UserStatus.Idle);
  289. }
  290. private Task SetStatus(DiscordClient _client, UserStatus status)
  291. {
  292. throw new NotImplementedException();
  293. /*_client.SetStatus(status);
  294. await Task.Delay(50);
  295. }*/
  296. /*
  297. [TestMethod]
  298. public void TestSetGame()
  299. {
  300. AssertEvent<UserUpdatedEventArgs>(
  301. "UserUpdated never fired",
  302. async () => await SetGame(_targetBot, "test game"),
  303. x => _observerBot.UserUpdated += x,
  304. x => _observerBot.UserUpdated -= x,
  305. (s, e) => _targetBot.CurrentUser.CurrentGame == "test game");
  306. }
  307. private Task SetGame(DiscordClient _client, string game)
  308. {
  309. throw new NotImplementedException();
  310. //_client.SetGame(game);
  311. //await Task.Delay(5);
  312. }
  313. #endregion
  314. #region Permission Tests
  315. // Permissions
  316. [TestMethod]
  317. public async Task Test_AddGet_PermissionsRule()
  318. {
  319. var channel = await _testGuild.CreateTextChannel(GetRandomText());
  320. var user = _testGuild.GetUser(_targetBot.CurrentUser.Id);
  321. var perms = new OverwritePermissions(sendMessages: PermValue.Deny);
  322. await channel.UpdatePermissionOverwrite(user, perms);
  323. var resultPerms = channel.GetPermissionOverwrite(user);
  324. Assert.IsNotNull(resultPerms, "Perms retrieved from Guild were null.");
  325. }
  326. [TestMethod]
  327. public async Task Test_AddRemove_PermissionsRule()
  328. {
  329. var channel = await _testGuild.CreateTextChannel(GetRandomText());
  330. var user = _testGuild.GetUser(_targetBot.CurrentUser.Id);
  331. var perms = new OverwritePermissions(sendMessages: PermValue.Deny);
  332. await channel.UpdatePermissionOverwrite(user, perms);
  333. await channel.RemovePermissionOverwrite(user);
  334. await Task.Delay(200);
  335. Assert.AreEqual(PermValue.Inherit, channel.GetPermissionOverwrite(user)?.SendMessages);
  336. }
  337. [TestMethod]
  338. public async Task Test_Permissions_Event()
  339. {
  340. var channel = await _testGuild.CreateTextChannel(GetRandomText());
  341. var user = _testGuild.GetUser(_targetBot.CurrentUser.Id);
  342. var perms = new OverwritePermissions(sendMessages: PermValue.Deny);
  343. AssertEvent<ChannelUpdatedEventArgs>
  344. ("ChannelUpdatedEvent never fired.",
  345. async () => await channel.UpdatePermissionOverwrite(user, perms),
  346. x => _targetBot.ChannelUpdated += x,
  347. x => _targetBot.ChannelUpdated -= x,
  348. (s, e) => e.Channel == channel && (e.After as GuildChannel).PermissionOverwrites.Count() != (e.Before as GuildChannel).PermissionOverwrites.Count());
  349. }
  350. [TestMethod]
  351. [ExpectedException(typeof(Net.HttpException))]
  352. public async Task Test_Affect_Permissions_Invalid_Channel()
  353. {
  354. var channel = await _testGuild.CreateTextChannel(GetRandomText());
  355. var user = _testGuild.GetUser(_targetBot.CurrentUser.Id);
  356. var perms = new OverwritePermissions(sendMessages: PermValue.Deny);
  357. await channel.Delete();
  358. await channel.UpdatePermissionOverwrite(user, perms);
  359. }
  360. #endregion
  361. [ClassCleanup]
  362. public static async Task Cleanup()
  363. {
  364. WaitMany(
  365. (await _hostBot.GetGuilds()).Select(x => x.Owner.Id == _hostBot.CurrentUser.Id ? x.Delete() : x.Leave()),
  366. (await _targetBot.GetGuilds()).Select(x => x.Owner.Id == _targetBot.CurrentUser.Id ? x.Delete() : x.Leave()),
  367. (await _observerBot.GetGuilds()).Select(x => x.Owner.Id == _observerBot.CurrentUser.Id ? x.Delete() : x.Leave()));
  368. WaitAll(
  369. _hostBot.Disconnect(),
  370. _targetBot.Disconnect(),
  371. _observerBot.Disconnect());
  372. }
  373. #region Helpers
  374. // Task Helpers
  375. private static void AssertEvent<TArgs>(string msg, Func<Task> action, Action<EventHandler<TArgs>> addEvent, Action<EventHandler<TArgs>> removeEvent, Func<object, TArgs, bool> test = null)
  376. {
  377. AssertEvent(msg, action, addEvent, removeEvent, test, true);
  378. }
  379. private static void AssertNoEvent<TArgs>(string msg, Func<Task> action, Action<EventHandler<TArgs>> addEvent, Action<EventHandler<TArgs>> removeEvent, Func<object, TArgs, bool> test = null)
  380. {
  381. AssertEvent(msg, action, addEvent, removeEvent, test, false);
  382. }
  383. private static void AssertEvent<TArgs>(string msg, Func<Task> action, Action<EventHandler<TArgs>> addEvent, Action<EventHandler<TArgs>> removeEvent, Func<object, TArgs, bool> test, bool assertTrue)
  384. {
  385. ManualResetEventSlim trigger = new ManualResetEventSlim(false);
  386. bool result = false;
  387. EventHandler<TArgs> handler = (s, e) =>
  388. {
  389. if (test != null)
  390. {
  391. result |= test(s, e);
  392. trigger.Set();
  393. }
  394. else
  395. result = true;
  396. };
  397. addEvent(handler);
  398. var task = action();
  399. trigger.Wait(EventTimeout);
  400. task.Wait();
  401. removeEvent(handler);
  402. Assert.AreEqual(assertTrue, result, msg);
  403. }
  404. private static void AssertEvent(string msg, Func<Task> action, Action<EventHandler> addEvent, Action<EventHandler> removeEvent, Func<object, bool> test, bool assertTrue)
  405. {
  406. ManualResetEventSlim trigger = new ManualResetEventSlim(false);
  407. bool result = false;
  408. EventHandler handler = (s, e) =>
  409. {
  410. if (test != null)
  411. {
  412. result |= test(s);
  413. trigger.Set();
  414. }
  415. else
  416. result = true;
  417. };
  418. addEvent(handler);
  419. var task = action();
  420. trigger.Wait(EventTimeout);
  421. task.Wait();
  422. removeEvent(handler);
  423. Assert.AreEqual(assertTrue, result, msg);
  424. }
  425. private static void WaitAll(params Task[] tasks)
  426. {
  427. Task.WaitAll(tasks);
  428. }
  429. private static void WaitAll(IEnumerable<Task> tasks)
  430. {
  431. Task.WaitAll(tasks.ToArray());
  432. }
  433. private static void WaitMany(params IEnumerable<Task>[] tasks)
  434. {
  435. Task.WaitAll(tasks.Where(x => x != null).SelectMany(x => x).ToArray());
  436. }
  437. #endregion
  438. }*/
  439. }