diff --git a/lambda/MAS.Tests/Feeds/multiple-items.json b/lambda/MAS.Tests/Feeds/all-items.json similarity index 100% rename from lambda/MAS.Tests/Feeds/multiple-items.json rename to lambda/MAS.Tests/Feeds/all-items.json diff --git a/lambda/MAS.Tests/Feeds/daily-items-single.json b/lambda/MAS.Tests/Feeds/daily-items-single.json new file mode 100644 index 00000000..e1537f99 --- /dev/null +++ b/lambda/MAS.Tests/Feeds/daily-items-single.json @@ -0,0 +1,42 @@ +[ + { + "_id": "5daf1aa18a34d4bb8405b5e0", + "slug": "testing-789", + "source": { + "_id": "5de526fc43e373581b7810c8", + "oldEPiServerId": 2, + "title": "ACP Journal Club", + "__v": 0 + }, + "shortSummary": "testing", + "resourceLinks": "http://localhost:3010/keystone/items", + "url": "https://www.nhs.uk/", + "title": "Wonder Drug", + "__v": 0, + "comment": "

A

", + "publicationDate": "2019-11-25T13:48:36.000Z", + "createdDate": "2019-10-22T15:05:05.927Z", + "specialities": [ + { + "_id": "5e0e4331200a585f718e1ee5", + "key": "be1c2e2f-745e-4a82-b5aa-d4cef4d31a1b", + "title": "Anaesthesia and pain", + "__v": 0 + }, + { + "_id": "5e0e4331200a58dead8e1ee8", + "key": "53fc67a4-46d8-4171-9447-7fcf216c8749", + "title": "Complementary and alternative therapies", + "__v": 0 + } + ], + "evidenceType": { + "_id": "5df7abf383138898ee1f67ef", + "title": "Safety alerts", + "key": "mas_evidence_types:Safety%20alerts", + "oldEPiServerId": 778708, + "__v": 0 + }, + "isInitial": false + } +] \ No newline at end of file diff --git a/lambda/MAS.Tests/Feeds/daily-items.json b/lambda/MAS.Tests/Feeds/daily-items.json new file mode 100644 index 00000000..ef0788d5 --- /dev/null +++ b/lambda/MAS.Tests/Feeds/daily-items.json @@ -0,0 +1,162 @@ +[ + { + "_id": "5daf1aa18a34d4bb8405b5e0", + "slug": "testing-789", + "source": { + "_id": "5de526fc43e373581b7810c8", + "oldEPiServerId": 2, + "title": "ACP Journal Club", + "__v": 0 + }, + "shortSummary": "testing", + "resourceLinks": "http://localhost:3010/keystone/items", + "url": "https://www.nhs.uk/", + "title": "Wonder Drug", + "__v": 0, + "comment": "

A

", + "publicationDate": "2019-11-25T13:48:36.000Z", + "createdDate": "2019-10-22T15:05:05.927Z", + "specialities": [ + { + "_id": "5e0e4331200a585f718e1ee5", + "key": "be1c2e2f-745e-4a82-b5aa-d4cef4d31a1b", + "title": "Anaesthesia and pain", + "__v": 0 + }, + { + "_id": "5e0e4331200a58dead8e1ee8", + "key": "53fc67a4-46d8-4171-9447-7fcf216c8749", + "title": "Complementary and alternative therapies", + "__v": 0 + } + ], + "evidenceType": { + "_id": "5df7abf383138898ee1f67ef", + "title": "Safety alerts", + "key": "mas_evidence_types:Safety%20alerts", + "oldEPiServerId": 778708, + "__v": 0 + }, + "isInitial": false + }, + { + "_id": "5db02d6d8a34d43bde05b5e1", + "slug": "my-medicine", + "source": { + "_id": "5de5261b8ce66f142e44cd08", + "oldEPiServerId": 1394, + "title": "ADHD Awareness Month", + "__v": 0 + }, + "shortSummary": "this is my medicine", + "resourceLinks": "http://localhost:3010/keystone/items", + "url": "https://www.nice.org.uk/", + "title": "MY MEDICINE", + "__v": 0, + "comment": "

this is my comment

", + "publicationDate": "2019-11-23T13:48:36.000Z", + "createdDate": "2019-10-23T10:38:43.000Z", + "specialities": [ + { + "_id": "5e0e4331200a585f718e1ee5", + "key": "be1c2e2f-745e-4a82-b5aa-d4cef4d31a1b", + "title": "Anaesthesia and pain", + "__v": 0 + }, + { + "_id": "5e0e4331200a58dead8e1ee8", + "key": "53fc67a4-46d8-4171-9447-7fcf216c8749", + "title": "Complementary and alternative therapies", + "__v": 0 + } + ], + "evidenceType": { + "_id": "5df7abf383138898ee1f67ef", + "title": "Safety alerts", + "key": "mas_evidence_types:Safety%20alerts", + "oldEPiServerId": 778708, + "__v": 0 + }, + "isInitial": false + }, + { + "_id": "5db031d78a34d4a69905b5e3", + "slug": "hello-world", + "source": { + "_id": "5de52a02c676eee677e97f41", + "oldEPiServerId": 2, + "title": "Substance Misuse Management in General Practice", + "__v": 0 + }, + "shortSummary": "test", + "resourceLinks": "http://localhost:3010/keystone/items", + "url": "https://www.bbc.co.uk/", + "title": "Hello world", + "__v": 0, + "comment": "

comment

", + "publicationDate": "2019-10-23T00:00:00.000Z", + "createdDate": "2019-10-23T10:56:40.000Z", + "specialities": [ + { + "_id": "5e0e4331200a585f718e1ee5", + "key": "be1c2e2f-745e-4a82-b5aa-d4cef4d31a1b", + "title": "Anaesthesia and pain", + "__v": 0 + }, + { + "_id": "5e0e4331200a58dead8e1ee8", + "key": "53fc67a4-46d8-4171-9447-7fcf216c8749", + "title": "Complementary and alternative therapies", + "__v": 0 + } + ], + "evidenceType": { + "_id": "5df7abf383138898ee1f67ef", + "title": "Safety alerts", + "key": "mas_evidence_types:Safety%20alerts", + "oldEPiServerId": 778708, + "__v": 0 + }, + "isInitial": false + }, + { + "_id": "5db6cbcc8a34d4ca5905b5e4", + "slug": "hello-there", + "source": { + "_id": "5de52a01c676ee589ae97d2a", + "oldEPiServerId": 2, + "title": "Journal of Surgical Oncology", + "__v": 0 + }, + "shortSummary": "hello", + "resourceLinks": "http://localhost:3010/keystone/items", + "url": "https://www.google.com/", + "title": "A Placebo", + "__v": 0, + "comment": "

test

", + "publicationDate": "2019-10-28T00:00:00.000Z", + "createdDate": "2019-10-28T11:07:11.000Z", + "specialities": [ + { + "_id": "5e0e4331200a585f718e1ee5", + "key": "be1c2e2f-745e-4a82-b5aa-d4cef4d31a1b", + "title": "Anaesthesia and pain", + "__v": 0 + }, + { + "_id": "5e0e4331200a58dead8e1ee8", + "key": "53fc67a4-46d8-4171-9447-7fcf216c8749", + "title": "Complementary and alternative therapies", + "__v": 0 + } + ], + "evidenceType": { + "_id": "5df7abf383138898ee1f67ef", + "title": "Safety alerts", + "key": "mas_evidence_types:Safety%20alerts", + "oldEPiServerId": 778708, + "__v": 0 + }, + "isInitial": false + } +] \ No newline at end of file diff --git a/lambda/MAS.Tests/Infrastructure/MASWebApplicationFactory.cs b/lambda/MAS.Tests/Infrastructure/MASWebApplicationFactory.cs new file mode 100644 index 00000000..38b75bca --- /dev/null +++ b/lambda/MAS.Tests/Infrastructure/MASWebApplicationFactory.cs @@ -0,0 +1,46 @@ +using MAS.Configuration; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; + +namespace MAS.Tests.Infrastructure +{ + /// + /// See https://github.com/aspnet/AspNetCore.Docs/issues/7063#issuecomment-414661566 + /// + public class MASWebApplicationFactory : WebApplicationFactory + { + protected override IWebHostBuilder CreateWebHostBuilder() + { + return WebHost.CreateDefaultBuilder() + .UseStartup() + .UseLambdaServer(); + } + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + var projectDir = Directory.GetCurrentDirectory(); + + builder.ConfigureAppConfiguration((context, conf) => + { + conf.AddJsonFile(Path.Combine(projectDir, "appsettings.test.json")); + }); + + builder.ConfigureTestServices(services => { + AppSettings.CMSConfig.BaseUrl = new Uri("file://" + projectDir + "/Feeds").ToString(); + }); + + base.ConfigureWebHost(builder); + } + } +} diff --git a/lambda/MAS.Tests/Infrastructure/TestAppSettings.cs b/lambda/MAS.Tests/Infrastructure/TestAppSettings.cs index ef2d8fae..1fb859af 100644 --- a/lambda/MAS.Tests/Infrastructure/TestAppSettings.cs +++ b/lambda/MAS.Tests/Infrastructure/TestAppSettings.cs @@ -4,22 +4,36 @@ namespace MAS.Tests.Infrastructure { - public class TestAppSettings + /// + /// Use this in integration tests to override CMS config per test e.g. AppSettings.CMSConfig = TestAppSettings.CMS.InvalidURI; + /// + public static class TestAppSettings { - public static CMSConfig GetInvalidURI() + public static class CMS { - return new CMSConfig() + public static CMSConfig Default { - BaseUrl = new Uri("file://" + Directory.GetCurrentDirectory() + "/Feeds/nonexistanturl").ToString() - }; - } + get + { + return new CMSConfig() + { + BaseUrl = new Uri("file://" + Directory.GetCurrentDirectory() + "/Feeds").ToString(), + AllItemsPath = "/all-items.json", + DailyItemsPath = "/daily-items.json", + }; + } + } - public static CMSConfig GetMultipleItemsFeed() - { - return new CMSConfig() + public static CMSConfig InvalidURI { - BaseUrl = new Uri("file://" + Directory.GetCurrentDirectory() + "/Feeds/multiple-items.json").ToString() - }; + get + { + return new CMSConfig() + { + BaseUrl = new Uri("file://" + Directory.GetCurrentDirectory() + "/Feeds/nonexistanturl").ToString() + }; + } + } } } } diff --git a/lambda/MAS.Tests/Infrastructure/TestBase.cs b/lambda/MAS.Tests/Infrastructure/TestBase.cs index b952e0d4..bec7c97b 100644 --- a/lambda/MAS.Tests/Infrastructure/TestBase.cs +++ b/lambda/MAS.Tests/Infrastructure/TestBase.cs @@ -6,55 +6,41 @@ using System; using System.Net.Http; using Microsoft.Extensions.DependencyInjection; +using Xunit; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection.Extensions; namespace MAS.Tests.Infrastructure { - public class TestBase : IDisposable + public abstract class TestBase : IDisposable { - protected readonly IWebHostBuilder _builder; - protected readonly TestServer _server; - protected readonly HttpClient _client; - //protected readonly IConfigurationRoot _config; + protected readonly MASWebApplicationFactory _factory; public TestBase() { - //_config = new ConfigurationBuilder() - // .AddJsonFile("appsettings.json") - // //.AddUserSecrets("adafe3d8-65fb-49fd-885e-03341a36dc88") - // .Build(); - - //var builder = new WebHostBuilder() - _builder = WebHost.CreateDefaultBuilder(new string[0]) - .UseContentRoot("../../../../MAS") - .ConfigureServices(services => - { - //AppSettings.Configure(services, _config); - }) - .UseEnvironment("Production") - .UseStartup(typeof(Startup)); - - _server = new TestServer(_builder); - _client = _server.CreateClient(); - //_client.BaseAddress = new Uri("http://localhost:5000"); + _factory = new MASWebApplicationFactory(); } - protected void WithImplementation() - where TService : class where TImplementation : class, TService + protected WebApplicationFactory WithImplementation(TService implementation) { - _builder.ConfigureServices(serviceCollection => serviceCollection.AddTransient()); - } + return _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + var serviceProvider = services.BuildServiceProvider(); - protected void WithImplementation(TService implementation) - where TService : class - { - _builder.ConfigureServices(serviceCollection => serviceCollection.AddTransient(serviceProvier => implementation)); + var descriptor = + new ServiceDescriptor( + typeof(TService), implementation); + + services.Replace(descriptor); + }); + }); } public virtual void Dispose() { - // Do "global" teardown here; Called after every test method. - _client.Dispose(); - _server.Dispose(); + _factory.Dispose(); } } } diff --git a/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.EmailBodyHtmlMatchesApproved.approved.txt b/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.EmailBodyHtmlMatchesApproved.approved.txt new file mode 100644 index 00000000..aed03a43 --- /dev/null +++ b/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.EmailBodyHtmlMatchesApproved.approved.txt @@ -0,0 +1,53 @@ + +

DailyEmail

+ + +
+ Safety alerts + +
+ Wonder Drug +
+ ACP Journal Club +
+ Anaesthesia and pain | Complementary and alternative therapies +
+ testing +
+ SPS Comment +
+
+ MY MEDICINE +
+ ADHD Awareness Month +
+ Anaesthesia and pain | Complementary and alternative therapies +
+ this is my medicine +
+ SPS Comment +
+
+ Hello world +
+ Substance Misuse Management in General Practice +
+ Anaesthesia and pain | Complementary and alternative therapies +
+ test +
+ SPS Comment +
+
+ A Placebo +
+ Journal of Surgical Oncology +
+ Anaesthesia and pain | Complementary and alternative therapies +
+ hello +
+ SPS Comment +
+
+ diff --git a/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.EmailBodyHtmlMatchesApprovedForSingleItem.approved.txt b/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.EmailBodyHtmlMatchesApprovedForSingleItem.approved.txt new file mode 100644 index 00000000..634797a8 --- /dev/null +++ b/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.EmailBodyHtmlMatchesApprovedForSingleItem.approved.txt @@ -0,0 +1,20 @@ + +

DailyEmail

+ + +
+ Safety alerts + +
+ Wonder Drug +
+ ACP Journal Club +
+ Anaesthesia and pain | Complementary and alternative therapies +
+ testing +
+ SPS Comment +
+
+ diff --git a/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.cs b/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.cs new file mode 100644 index 00000000..53c57ce1 --- /dev/null +++ b/lambda/MAS.Tests/IntegrationTests/DailyEmailTests.cs @@ -0,0 +1,93 @@ +using MailChimp.Net.Core; +using MailChimp.Net.Interfaces; +using MailChimp.Net.Models; +using MAS.Configuration; +using MAS.Models; +using MAS.Services; +using MAS.Tests.Infrastructure; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Moq; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Web.Mvc; +using Xunit; +using Source = MAS.Models.Source; + +namespace MAS.Tests.IntegrationTests +{ + public class TestMailService : IMailService + { + public Task CreateAndSendDailyAsync(string subject, string previewText, string body) + { + throw new NotImplementedException(); + } + } + + public class DailyEmailTests : TestBase + { + [Fact] + public async void EmailBodyHtmlMatchesApproved() + { + // Arrange + var fakeMailService = new Mock(); + + string bodyHtml = string.Empty; + fakeMailService.Setup(s => s.CreateAndSendDailyAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((subject, previewText, body) => bodyHtml = body) + .ReturnsAsync("1234"); + + var client = WithImplementation(fakeMailService.Object).CreateClient(); + + // Act + var response = await client.PutAsync("/api/mail/daily", null); + + // Assert + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var responseText = await response.Content.ReadAsStringAsync(); + responseText.ShouldBe("1234"); + + bodyHtml.ShouldMatchApproved(); + } + + [Fact] + public async void EmailBodyHtmlMatchesApprovedForSingleItem() + { + // Arrange + var fakeMailService = new Mock(); + + string bodyHtml = string.Empty; + fakeMailService.Setup(s => s.CreateAndSendDailyAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((subject, previewText, body) => bodyHtml = body) + .ReturnsAsync("1234"); + + var client = WithImplementation(fakeMailService.Object).CreateClient(); + + AppSettings.CMSConfig.DailyItemsPath = "/daily-items-single.json"; + + // Act + var response = await client.PutAsync("/api/mail/daily", null); + + // Assert + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var responseText = await response.Content.ReadAsStringAsync(); + responseText.ShouldBe("1234"); + + bodyHtml.ShouldMatchApproved(); + } + } +} diff --git a/lambda/MAS.Tests/IntegrationTests/MailControllerTests.cs b/lambda/MAS.Tests/IntegrationTests/MailControllerTests.cs new file mode 100644 index 00000000..9616a263 --- /dev/null +++ b/lambda/MAS.Tests/IntegrationTests/MailControllerTests.cs @@ -0,0 +1,44 @@ +using System.Threading.Tasks; +using Xunit; +using Shouldly; +using MAS.Tests.Infrastructure; +using System.Text; +using System; +using MAS.Configuration; +using System.Net.Http.Headers; +using System.Net.Http; +using MailChimp.Net.Models; +using Newtonsoft.Json; + +namespace MAS.Tests.IntegrationTests.Mail +{ + //public class MailControllerTests : TestBase + //{ + // [Fact] + // public async Task PutRequestCreatesAndSendsCampaign() + // { + // //Arrange + // const string mailChimpCampaignsURI = "https://us5.api.mailchimp.com/3.0/campaigns/"; + + // var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"anystring:{AppSettings.MailConfig.ApiKey}"))); + // var client = new HttpClient() + // { + // DefaultRequestHeaders = { Authorization = authValue } + // }; + + // //Act + // var response = await _client.PutAsync("/api/mail/daily", null); + + // //Get campaign to check if it saved + // var campaignId = await response.Content.ReadAsStringAsync(); + // var campaign = await client.GetAsync(mailChimpCampaignsURI + campaignId); + // var campaignJson = await campaign.Content.ReadAsStringAsync(); + // var campaignResult = JsonConvert.DeserializeObject(campaignJson); + + // // Assert + // response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + // campaignResult.Status.ShouldNotBeNull(); + // campaignResult.Status.ShouldNotBe("Draft"); + // } + //} +} diff --git a/lambda/MAS.Tests/IntergrationTests/ContentControllerTests.PutCMSItemSavesItemIntoS3.approved.txt b/lambda/MAS.Tests/IntegrationTests/StaticContentTests.PutCMSItemSavesItemIntoS3.approved.txt similarity index 96% rename from lambda/MAS.Tests/IntergrationTests/ContentControllerTests.PutCMSItemSavesItemIntoS3.approved.txt rename to lambda/MAS.Tests/IntegrationTests/StaticContentTests.PutCMSItemSavesItemIntoS3.approved.txt index 4f56ef60..d1a2aef8 100644 --- a/lambda/MAS.Tests/IntergrationTests/ContentControllerTests.PutCMSItemSavesItemIntoS3.approved.txt +++ b/lambda/MAS.Tests/IntegrationTests/StaticContentTests.PutCMSItemSavesItemIntoS3.approved.txt @@ -18,10 +18,10 @@ - + - + diff --git a/lambda/MAS.Tests/IntegrationTests/StaticContentTests.cs b/lambda/MAS.Tests/IntegrationTests/StaticContentTests.cs new file mode 100644 index 00000000..39b8957a --- /dev/null +++ b/lambda/MAS.Tests/IntegrationTests/StaticContentTests.cs @@ -0,0 +1,68 @@ +using System.Threading.Tasks; +using Xunit; +using MAS.Tests.Infrastructure; +using Shouldly; +using Amazon.S3; +using Amazon; +using MAS.Configuration; +using System.IO; +using MAS.Models; +using Amazon.S3.Model; +using Newtonsoft.Json; +using System.Text; +using System.Net.Http; +using Microsoft.AspNetCore.Mvc.Testing; +using Moq; +using System.Threading; + +namespace MAS.Tests.IntegrationTests +{ + public class StaticContentTests : TestBase + { + private Item item = new Item() + { + Id = "1234", + Slug = "effect-of-vit-d", + URL = "www.website.com", + Title = "Effect of Vitamin D and Omega-3 Fatty Acid Supplementation on Kidney Function in Patients With Type 2 Diabetes: A Randomized Clinical Trial", + ShortSummary = "RCT (n=1,312) found that among adults with type 2 diabetes, supplementation with vitamin D3 or omega-3 fatty acids, compared with placebo, resulted in no significant difference in change in eGFR at 5 years.", + Source = new Source() + { + Id = "789", + Title = "Journal of the American Medical Association" + }, + EvidenceType = new EvidenceType + { + Key = "mas_evidence_types:Safety%20alerts", + Title = "Safety alerts" + }, + Comment = "A related editorial discusses this research and details previous epidemiological studies that suggest improved outcomes with vitamin D supplementation in various clinical scenarios. It states that contrasting the results of this study and its predecessor vitamin D trials with the impressive body of epidemiological research that implicated vitamin D deficiency in various adverse health outcomes offers a stark lesson on the chasm between association and causation. Editorial authors highlight that it now seems safe to conclude that many prior epidemiological associations between vitamin D deficiency and adverse health outcomes were driven by unmeasured residual confounding or reverse causality.", + ResourceLinks = "

Vitamin D and Health Outcomes - Then Came the Randomized Clinical Trials

\r\n

Link 2

" + + }; + + [Fact] + public async Task PutCMSItemSavesItemIntoS3() + { + // Arrange + var fakeS3Service = new Mock(); + + PutObjectRequest putObjectRequest = null; + fakeS3Service.Setup(s => s.PutObjectAsync(It.IsAny(), default(CancellationToken))) + .Callback((pOR, cT) => putObjectRequest = pOR) + .ReturnsAsync(new PutObjectResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); + + var client = WithImplementation(fakeS3Service.Object).CreateClient(); + var content = new StringContent(JsonConvert.SerializeObject(item), Encoding.UTF8, "application/json"); + + // Act + var response = await client.PutAsync("/api/content/", content); + + // Assert + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + putObjectRequest.Key.ShouldBe("effect-of-vit-d.html"); + putObjectRequest.ContentBody.ShouldMatchApproved(); + } + + } +} diff --git a/lambda/MAS.Tests/IntergrationTests/ContentControllerTests.cs b/lambda/MAS.Tests/IntergrationTests/ContentControllerTests.cs deleted file mode 100644 index 2dc7100b..00000000 --- a/lambda/MAS.Tests/IntergrationTests/ContentControllerTests.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System.Threading.Tasks; -using Xunit; -using MAS.Tests.Infrastructure; -using Shouldly; -using Amazon.S3; -using Amazon; -using MAS.Configuration; -using System.IO; -using MAS.Models; -using Amazon.S3.Model; -using Newtonsoft.Json; -using System.Text; -using System.Net.Http; - -namespace MAS.Tests.IntergrationTests.Content -{ - public class ContentControllerTests : TestBase - { - [Fact] - public async Task PutCMSItemSavesItemIntoS3() - { - //Arrange - AmazonS3Config config = new AmazonS3Config() - { - RegionEndpoint = RegionEndpoint.EUWest1, - ServiceURL = AppSettings.AWSConfig.ServiceURL, - ForcePathStyle = true - }; - AmazonS3Client s3Client = new AmazonS3Client(AppSettings.AWSConfig.AccessKey, AppSettings.AWSConfig.SecretKey, config); - - Item item = new Item() - { - Id = "1234", - Slug = "Effect-of-vit-d", - URL = "www.website.com", - Title = "Effect of Vitamin D and Omega-3 Fatty Acid Supplementation on Kidney Function in Patients With Type 2 Diabetes: A Randomized Clinical Trial", - ShortSummary = "RCT (n=1,312) found that among adults with type 2 diabetes, supplementation with vitamin D3 or omega-3 fatty acids, compared with placebo, resulted in no significant difference in change in eGFR at 5 years.", - Source = new Source() - { - Id = "789", - Title = "Journal of the American Medical Association" - }, - EvidenceType = new EvidenceType - { - Key = "mas_evidence_types:Safety%20alerts", - Title = "Safety alerts" - }, - Comment = "A related editorial discusses this research and details previous epidemiological studies that suggest improved outcomes with vitamin D supplementation in various clinical scenarios. It states that contrasting the results of this study and its predecessor vitamin D trials with the impressive body of epidemiological research that implicated vitamin D deficiency in various adverse health outcomes offers a stark lesson on the chasm between association and causation. Editorial authors highlight that it now seems safe to conclude that many prior epidemiological associations between vitamin D deficiency and adverse health outcomes were driven by unmeasured residual confounding or reverse causality.", - ResourceLinks = "

Vitamin D and Health Outcomes - Then Came the Randomized Clinical Trials

\r\n

Link 2

" - - }; - - var content = new StringContent(JsonConvert.SerializeObject(item), Encoding.UTF8, "application/json"); - - //Act - var response = await _client.PutAsync("/api/content/", content); - - // Assert - response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); - - using (var bucketItem = await s3Client.GetObjectAsync(AppSettings.AWSConfig.BucketName, "Effect-of-vit-d.html")) - { - using (StreamReader reader = new StreamReader(bucketItem.ResponseStream)) - { - string contents = reader.ReadToEnd(); - contents.ShouldMatchApproved(); - } - } - } - - } -} diff --git a/lambda/MAS.Tests/IntergrationTests/DailyEmailTests.cs b/lambda/MAS.Tests/IntergrationTests/DailyEmailTests.cs deleted file mode 100644 index 271d0f9a..00000000 --- a/lambda/MAS.Tests/IntergrationTests/DailyEmailTests.cs +++ /dev/null @@ -1,173 +0,0 @@ -using MailChimp.Net.Core; -using MailChimp.Net.Interfaces; -using MailChimp.Net.Models; -using MAS.Models; -using MAS.Services; -using MAS.Tests.Infrastructure; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.ViewFeatures; -using Microsoft.AspNetCore.Routing; -using Microsoft.Extensions.Logging; -using Moq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Web.Mvc; -using Xunit; -using Source = MAS.Models.Source; - -namespace MAS.Tests.IntergrationTests -{ - //public class FakeMailChimpManager : IMailChimpManager - //{ - - //} - - public class DailyEmailTests : TestBase - { - - - public DailyEmailTests() - { - } - - Item exampleItem = new Item() - { - Id = "123", - Title = "Some Title", - Slug = "abc", - ShortSummary = "Some short summary", - ResourceLinks = "", - Comment = "", - Specialities = new List - { - new Speciality() - { - Key = "1a", - Title = "Some speciality", - - } - }, - EvidenceType = new EvidenceType() - { - Key = "1b", - Title = "Some evidence type" - }, - Source = new Source() - { - Id = "1c", - Title = "Some source" - } - }; - Item exampleItem2 = new Item() - { - Id = "123", - Title = "Some Title", - Slug = "abc", - ShortSummary = "Some short summary", - ResourceLinks = "", - Comment = "", - Specialities = new List - { - new Speciality() - { - Key = "1a", - Title = "Some speciality 2", - - } - }, - EvidenceType = new EvidenceType() - { - Key = "1c", - Title = "Some evidence type 2" - }, - Source = new Source() - { - Id = "1c", - Title = "Some source" - } - }; - - [Fact] - public async void SomeTest() - { - var fakeMailService = new Mock(); - - string bodyHtml = string.Empty; - fakeMailService.Setup(s => s.CreateAndSendDailyAsync(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((subject, previewText, body) => bodyHtml = body) - .ReturnsAsync("1234"); - - WithImplementation(fakeMailService); - - await _client.PutAsync("/api/mail/daily", null); - - bodyHtml.ShouldMatchApproved(); - } - - - - - - - - - - - //[Fact] - //public void CanCreateSingleItemEmail() - //{ - - // var items = new List { exampleItem }; - // var actualHtml = this.MailService.CreateDailyEmailBody(items, mockController.Object); - - // actualHtml.ShouldMatchApproved(); - - //} - - //[Fact] - //public void CanCreateEmailWithTwoItemsSharingEvidenceType() - //{ - // var items = new List { exampleItem, exampleItem }; - // var actualHtml = this.MailService.CreateDailyEmailBody(items, new FakeController()); - - // actualHtml.ShouldMatchApproved(); - - //} - - //[Fact] - //public void CanCreateEmailWithTwoItemsDifferentEvidenceType() - //{ - // var items = new List { exampleItem, exampleItem2 }; - // var actualHtml = ""; - // try - // { - // actualHtml = this.MailService.CreateDailyEmailBody(items, new FakeController()); - // } - // catch(Exception e) - // { - // var p = e.Message; - // } - - - // actualHtml.ShouldMatchApproved(); - - //} - - //[Fact] - //public void ItemsWithManySpecialitiesRenderCorrectly() - //{ - // exampleItem.Specialities.Add(new Speciality() { Key = "abcd", Title = "Another speciality" }); - // var items = new List { exampleItem }; - // var actualHtml = this.MailService.CreateDailyEmailBody(items, new FakeController()); - - // actualHtml.ShouldMatchApproved(); - - //} - - } -} diff --git a/lambda/MAS.Tests/IntergrationTests/MailControllerTests.cs b/lambda/MAS.Tests/IntergrationTests/MailControllerTests.cs deleted file mode 100644 index 096ce967..00000000 --- a/lambda/MAS.Tests/IntergrationTests/MailControllerTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Threading.Tasks; -using Xunit; -using Shouldly; -using MAS.Tests.Infrastructure; -using System.Text; -using System; -using MAS.Configuration; -using System.Net.Http.Headers; -using System.Net.Http; -using MailChimp.Net.Models; -using Newtonsoft.Json; - -namespace MAS.Tests.IntergrationTests.Mail -{ - public class MailControllerTests : TestBase - { - [Fact] - public async Task PutRequestCreatesAndSendsCampaign() - { - //Arrange - const string mailChimpCampaignsURI = "https://us5.api.mailchimp.com/3.0/campaigns/"; - AppSettings.CMSConfig = TestAppSettings.GetMultipleItemsFeed(); - - var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"anystring:{AppSettings.MailConfig.ApiKey}"))); - var client = new HttpClient() - { - DefaultRequestHeaders = { Authorization = authValue } - }; - - //Act - var response = await _client.PutAsync("/api/mail/daily", null); - - //Get campaign to check if it saved - var campaignId = await response.Content.ReadAsStringAsync(); - var campaign = await client.GetAsync(mailChimpCampaignsURI + campaignId); - var campaignJson = await campaign.Content.ReadAsStringAsync(); - var campaignResult = JsonConvert.DeserializeObject(campaignJson); - - // Assert - response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); - campaignResult.Status.ShouldNotBeNull(); - campaignResult.Status.ShouldNotBe("Draft"); - } - } -} diff --git a/lambda/MAS.Tests/MAS.Tests.csproj b/lambda/MAS.Tests/MAS.Tests.csproj index 2a80da57..19dee507 100644 --- a/lambda/MAS.Tests/MAS.Tests.csproj +++ b/lambda/MAS.Tests/MAS.Tests.csproj @@ -10,14 +10,27 @@ - + + + + + - - Always - + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + @@ -25,7 +38,8 @@ - + + diff --git a/lambda/MAS.Tests/UnitTests/Controllers/MailControllerTests.cs b/lambda/MAS.Tests/UnitTests/Controllers/MailControllerTests.cs index d7b4f480..e339839d 100644 --- a/lambda/MAS.Tests/UnitTests/Controllers/MailControllerTests.cs +++ b/lambda/MAS.Tests/UnitTests/Controllers/MailControllerTests.cs @@ -57,7 +57,7 @@ public async void RendersDailyViewWithContentItems() await mailController.PutMailAsync(); //Assert - mockViewRenderer.Verify(mock => mock.RenderViewAsync(mailController, "~/Views/MAD.cshtml", items, false), Times.Once()); + mockViewRenderer.Verify(mock => mock.RenderViewAsync(mailController, "~/Views/DailyEmail.cshtml", items, false), Times.Once()); } } } diff --git a/lambda/MAS.Tests/UnitTests/Services/ContentServiceTests.cs b/lambda/MAS.Tests/UnitTests/Services/ContentServiceTests.cs index d63be9e9..c60ae0aa 100644 --- a/lambda/MAS.Tests/UnitTests/Services/ContentServiceTests.cs +++ b/lambda/MAS.Tests/UnitTests/Services/ContentServiceTests.cs @@ -11,7 +11,7 @@ namespace MAS.Tests.UnitTests { - public class ContentServiceTests : TestBase + public class ContentServiceTests { [Fact] public async Task ReadMultipleItems() @@ -19,7 +19,7 @@ public async Task ReadMultipleItems() //Arrange var mockLogger = new Mock>(); - AppSettings.CMSConfig = TestAppSettings.GetMultipleItemsFeed(); + AppSettings.CMSConfig = TestAppSettings.CMS.Default; var contentService = new ContentService(mockLogger.Object); //Act @@ -39,7 +39,7 @@ public async Task InvalidURIThrowsError() //Arrange var mockLogger = new Mock>(); - AppSettings.CMSConfig = TestAppSettings.GetInvalidURI(); + AppSettings.CMSConfig = TestAppSettings.CMS.InvalidURI; var contentService = new ContentService(mockLogger.Object); //Act + Assert diff --git a/lambda/MAS.Tests/UnitTests/Services/MailServiceTests.cs b/lambda/MAS.Tests/UnitTests/Services/MailServiceTests.cs index 0403f3be..98c6bde0 100644 --- a/lambda/MAS.Tests/UnitTests/Services/MailServiceTests.cs +++ b/lambda/MAS.Tests/UnitTests/Services/MailServiceTests.cs @@ -13,7 +13,7 @@ namespace MAS.Tests.UnitTests { - public class MailServiceTests : TestBase + public class MailServiceTests { [Fact] public void CreateCampaignAndSendToMailChimp() @@ -28,6 +28,8 @@ public void CreateCampaignAndSendToMailChimp() var mailService = new MailService(mockMailChimpManager.Object, mockLogger.Object); + AppSettings.MailConfig = Mock.Of(); + //Act var response = mailService.CreateAndSendDailyAsync("Test Subject", "Preview Text", "Body Text"); diff --git a/lambda/MAS.Tests/appsettings.test.json b/lambda/MAS.Tests/appsettings.test.json new file mode 100644 index 00000000..8f0b8bf5 --- /dev/null +++ b/lambda/MAS.Tests/appsettings.test.json @@ -0,0 +1,15 @@ +{ + "AppSettings": { + "Environment": { + "Name": "tests" + } + }, + "AWS": { + "StaticUrl": "http://mas-integration-tests/" + }, + "CMS": { + "BaseUrl": "We override this in test setup to point to the Feeds folder on the filesystem", + "AllItemsPath": "/all-items.json", + "DailyItemsPath": "/daily-items.json" + } +} diff --git a/lambda/MAS/Controllers/MailController.cs b/lambda/MAS/Controllers/MailController.cs index 1f0172a3..5d0752b8 100644 --- a/lambda/MAS/Controllers/MailController.cs +++ b/lambda/MAS/Controllers/MailController.cs @@ -29,7 +29,7 @@ public async Task PutMailAsync(DateTime? date = null) { var items = await _contentService.GetDailyItemsAsync(date); - var body = await _viewRenderer.RenderViewAsync(this, "~/Views/MAD.cshtml", items.ToList()); + var body = await _viewRenderer.RenderViewAsync(this, "~/Views/DailyEmail.cshtml", items.ToList()); var subject = "MAS Email"; var previewText = "This MAS email was created " + DateTime.Now.ToShortDateString(); diff --git a/lambda/MAS/Views/DailyEmail.cshtml b/lambda/MAS/Views/DailyEmail.cshtml index 58765bd9..197d0e4b 100644 --- a/lambda/MAS/Views/DailyEmail.cshtml +++ b/lambda/MAS/Views/DailyEmail.cshtml @@ -2,7 +2,7 @@ @model List @{ ViewData["Title"] = "DailyEmail"; - Layout = "~/Views/Shared/_EmailLayout.cshtml"; + //Layout = "~/Views/Shared/_EmailLayout.cshtml"; var groupedItems = Model.GroupBy(x => x.EvidenceType.Title).ToList(); }