Skip to content

Commit

Permalink
Enable Nullable Reference Types (NRT) (#30)
Browse files Browse the repository at this point in the history
* Migrate project MailMergeLib
* MailMergeMessage_Exceptions: Allow null for inner Exception
* Migrate project MailMergeLib.Tests
  • Loading branch information
axunonb committed Jan 14, 2023
1 parent 756924d commit 6ed181a
Show file tree
Hide file tree
Showing 49 changed files with 571 additions and 563 deletions.
2 changes: 1 addition & 1 deletion Src/MailMergeLib.Tests/EmailValidatorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,6 @@ public void TestValidInternationalAddresses()
[Test]
public void TestThrowsExceptionIfNull()
{
Assert.Throws<ArgumentNullException>(() => EmailValidator.Validate(null, true, true), "Null Address");
Assert.Throws<ArgumentNullException>(() => EmailValidator.Validate(null!, true, true), "Null Address");
}
}
22 changes: 11 additions & 11 deletions Src/MailMergeLib.Tests/FakeSmtpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ public FakeSmtpClient()
prop?.SetValue(this, SmtpCapabilities.Authentication);
}

public Exception AuthenticateException { get; set; } = null;
public Exception ConnectException { get; set; } = null;
public Exception SendException { get; set; } = null;
public Exception? AuthenticateException { get; set; } = null;
public Exception? ConnectException { get; set; } = null;
public Exception? SendException { get; set; } = null;

public override Task AuthenticateAsync(SaslMechanism mechanism, CancellationToken cancellationToken = new CancellationToken())
{
Expand Down Expand Up @@ -77,13 +77,13 @@ public override Task ConnectAsync(Stream stream, string host, int port = 0, Secu
}

public override Task<string> SendAsync(FormatOptions options, MimeMessage message,
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress? progress = null)
{
throw new NotImplementedException();
}

public override Task<string> SendAsync(FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable<MailboxAddress> recipients,
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress? progress = null)
{
throw new NotImplementedException();
}
Expand Down Expand Up @@ -163,14 +163,14 @@ protected override void OnRecipientNotAccepted(MimeMessage message, MailboxAddre
}

public override string Send(FormatOptions options, MimeMessage message, CancellationToken cancellationToken = new CancellationToken(),
ITransferProgress progress = null)
ITransferProgress? progress = null)
{
if (SendException != null) throw SendException;
return string.Empty;
}

public override string Send(FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable<MailboxAddress> recipients,
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress? progress = null)
{
if (SendException != null) throw SendException;
return string.Empty;
Expand All @@ -187,29 +187,29 @@ public override string Send(FormatOptions options, MimeMessage message, MailboxA
*/

public override string Send(MimeMessage message, CancellationToken cancellationToken = new CancellationToken(),
ITransferProgress progress = null)
ITransferProgress? progress = null)
{
if (SendException != null) throw SendException; // in use
return string.Empty;
}

public override Task<string> SendAsync(MimeMessage message, CancellationToken cancellationToken = new CancellationToken(),
ITransferProgress progress = null)
ITransferProgress? progress = null)
{
if (SendException != null) throw SendException;

return Task.FromResult(string.Empty);
}

public override string Send(MimeMessage message, MailboxAddress sender, IEnumerable<MailboxAddress> recipients,
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress? progress = null)
{
if (SendException != null) throw SendException;
return string.Empty;
}

public override Task<string> SendAsync(MimeMessage message, MailboxAddress sender, IEnumerable<MailboxAddress> recipients,
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress progress = null)
CancellationToken cancellationToken = new CancellationToken(), ITransferProgress? progress = null)
{
if (SendException != null) throw SendException;

Expand Down
4 changes: 2 additions & 2 deletions Src/MailMergeLib.Tests/FileMessageInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ public void CompareFileMessageInfo()
[Test]
public void CompareNullFileMessageInfo()
{
var info = new MailMergeLib.MessageStore.FileMessageInfo { Id = 1, Category = null, Comments = null, Description = "No description", Data = "Some data hint", MessageEncoding = null, MessageFile = null };
var otherInfo = new MailMergeLib.MessageStore.FileMessageInfo { Id = 1, Category = null, Comments = null, Description = "No description", Data = "Some data hint", MessageEncoding = null, MessageFile = null };
var info = new MailMergeLib.MessageStore.FileMessageInfo { Id = 1, Category = null, Comments = null, Description = "No description", Data = "Some data hint", MessageEncoding = null!, MessageFile = null! };
var otherInfo = new MailMergeLib.MessageStore.FileMessageInfo { Id = 1, Category = null, Comments = null, Description = "No description", Data = "Some data hint", MessageEncoding = null!, MessageFile = null! };

Assert.AreEqual(info, otherInfo);
Assert.IsFalse(info.Equals(null));
Expand Down
2 changes: 0 additions & 2 deletions Src/MailMergeLib.Tests/FileMessageStore_Serialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@ public void StreamSerialization()
Assert.True(fms.Equals(restoredFms));

Assert.AreEqual(fms.GetHashCode(), restoredFms.GetHashCode());
Assert.False(fms.Equals(null));
Assert.True(fms.Equals(fms));
Assert.False(fms.Equals(new object()));
}
}
4 changes: 2 additions & 2 deletions Src/MailMergeLib.Tests/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ internal class Helper
/// <returns></returns>
public static string GetCodeBaseDirectory()
{
return Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().Location).LocalPath);
return Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().Location).LocalPath)!;
}

internal static int Compare(Stream a, Stream b)
internal static int Compare(Stream? a, Stream? b)
{
if (a == null && b == null) return 0;

Expand Down
14 changes: 7 additions & 7 deletions Src/MailMergeLib.Tests/HtmlBodyBuilderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public void SetHtmlBuilderDocBaseUri_UriFormatException(string baseUri)
{
var mmm = new MailMergeMessage("subject", "plain text",
"<html><head><base href=\"\" /></head><body></body></html>");
var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
Assert.Throws<UriFormatException>(() => hbb.DocBaseUri = baseUri);
}

Expand All @@ -26,7 +26,7 @@ public void SetHtmlBuilderDocBaseUri_NoException(string baseUri)
{
var mmm = new MailMergeMessage("subject", "plain text",
"<html><head><base href=\"\" /></head><body></body></html>");
var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
Assert.DoesNotThrow(() => hbb.DocBaseUri = baseUri);
}

Expand All @@ -35,7 +35,7 @@ public void ScriptTagRemoved()
{
var mmm = new MailMergeMessage("subject_to_set", "plain text",
"<html><head><script>var x='x';</script><script>var y='y';</script></head><body>some body</body></html>");
var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
var html = hbb.GetBodyPart();
Assert.IsTrue(html.ToString().Contains("some body"));
Assert.IsTrue(!html.ToString().Contains("script"));
Expand All @@ -47,7 +47,7 @@ public void ExistingTitleTagSetWithSubject()
var subjectToSet = "subject_to_set";
var mmm = new MailMergeMessage(subjectToSet, "plain text",
"<html><head><title>abc</title></head><body></body></html>");
var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
var html = hbb.GetBodyPart();
Assert.IsTrue(html.ToString().Contains(subjectToSet));
}
Expand All @@ -57,7 +57,7 @@ public void NonExistingTitleTagSetWithSubject()
{
var subjectToSet = "subject_to_set";
var mmm = new MailMergeMessage(subjectToSet, "plain text", "<html><head></head><body></body></html>");
var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
var html = hbb.GetBodyPart();
Assert.IsTrue(!html.ToString().Contains(subjectToSet));
}
Expand All @@ -69,7 +69,7 @@ public void EmbeddedDataImage_ShouldNotBeTouched()
var imageTag = $"<img width=\"10\" height=\"10\" alt=\"1Pixel\" src=\"{image}\">";
var mmm = new MailMergeMessage("", "plain text",
$"<html><body>{imageTag}</body></html>");
var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
var html = hbb.GetBodyPart();
Assert.That(html.ToString(), Does.Contain(imageTag));
}
Expand All @@ -85,7 +85,7 @@ public void LargeEmbeddedDataImage_ShouldNotThrow()
var imageTag = $"<img width=\"10\" height=\"10\" alt=\"1Pixel\" src=\"{image}\">";
var mmm = new MailMergeMessage("", "plain text",
$"<html><body>{imageTag}</body></html>");
var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
Assert.That(code: () => hbb.GetBodyPart(), Throws.Nothing);
}
}
2 changes: 1 addition & 1 deletion Src/MailMergeLib.Tests/MailMergeLib.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<SignAssembly>true</SignAssembly>
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<IsTestProject>true</IsTestProject>
<Nullable>disable</Nullable>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
</PropertyGroup>

Expand Down
2 changes: 0 additions & 2 deletions Src/MailMergeLib.Tests/MessageInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public void ReadAndCompareInfo()
// MessageInfo
var deserializedInfo = MailMergeLib.MessageStore.MessageInfoBase.Read(xml);
Assert.AreEqual(info, deserializedInfo);
Assert.IsFalse(info.Equals(null));
Assert.IsTrue(info.Equals(info));
Assert.IsFalse(info.Equals(new object()));
Assert.AreEqual(info.GetHashCode(), deserializedInfo.GetHashCode());
Expand All @@ -44,7 +43,6 @@ public void ReadAndCompareEmptyInfo()
// MessageInfo
var deserializedInfo = MailMergeLib.MessageStore.MessageInfoBase.Read(xml);
Assert.AreEqual(info, deserializedInfo);
Assert.IsFalse(info.Equals(null));
Assert.IsTrue(info.Equals(info));
Assert.IsFalse(info.Equals(new object()));
Assert.AreEqual(info.GetHashCode(), deserializedInfo.GetHashCode());
Expand Down
10 changes: 5 additions & 5 deletions Src/MailMergeLib.Tests/Message_Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,19 +69,19 @@ public void FileBaseDirectory_must_be_full_path_when_processing_the_message(stri
[TestCase("noFullPath", null)]
[TestCase("..\\..\\relativePath", null, ExcludePlatform = nameof(OpSys.Linux) + "," + nameof(OpSys.MacOsX))]
[TestCase("../../relativePath", null, IncludePlatform = nameof(OpSys.Linux) + "," + nameof(OpSys.MacOsX))]
public void HtmlBodyBuilderDocBaseUri_vs_MessageConfig_FileBaseDirectory(string path, string expected)
public void HtmlBodyBuilderDocBaseUri_vs_MessageConfig_FileBaseDirectory(string path, string? expected)
{
var mmm = new MailMergeMessage("subject", "plain text", "<html><body></body></html>");
mmm.Config.FileBaseDirectory = path;

HtmlBodyBuilder hbb;
if (expected == null)
{
Assert.Throws<UriFormatException>(() => { hbb = new HtmlBodyBuilder(mmm, (object) null); });
Assert.Throws<UriFormatException>(() => { hbb = new HtmlBodyBuilder(mmm, null); });
}
else
{
hbb = new HtmlBodyBuilder(mmm, (object) null);
hbb = new HtmlBodyBuilder(mmm, null);
Assert.AreEqual(expected, hbb.DocBaseUri);
}
}
Expand All @@ -93,7 +93,7 @@ public void MessageConfig_FileBaseDirectory_cannot_be_changed_by_Html_Base_Tag()
"<html><head><base href=\"\" /></head><body></body></html>");
mmm.Config.FileBaseDirectory = Path.GetTempPath();

var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
Assert.AreEqual( new Uri(mmm.Config.FileBaseDirectory), hbb.DocBaseUri);
}

Expand All @@ -105,7 +105,7 @@ public void Empty_MessageConfig_FileBaseDirectory_is_changed_by_Html_Base_Tag()
$"<html><head><base href=\"{baseTagHref}\" /></head><body></body></html>");
mmm.Config.FileBaseDirectory = string.Empty;

var hbb = new HtmlBodyBuilder(mmm, (object) null);
var hbb = new HtmlBodyBuilder(mmm, null);
hbb.GetBodyPart();
Assert.AreEqual(baseTagHref, hbb.DocBaseUri);
}
Expand Down
2 changes: 0 additions & 2 deletions Src/MailMergeLib.Tests/Message_Equality.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ public void MailMergeAddressCollectionEquality()

addrColl2.Add(_addr3);
Assert.False(addrColl1.Equals(addrColl2));
Assert.False(addrColl1.Equals(null));
}

[TestCase(MailAddressType.To)]
Expand Down Expand Up @@ -128,7 +127,6 @@ public void MailMergeMessage()
mmm3.MailMergeAddresses.RemoveAt(0);
Assert.IsFalse(mmm1.Equals(mmm3));

Assert.IsFalse(mmm1.Equals(default(object)));
Assert.IsTrue(mmm1.Equals(mmm1));
Assert.IsFalse(mmm1.Equals(new object()));
}
Expand Down
9 changes: 4 additions & 5 deletions Src/MailMergeLib.Tests/Message_Html.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ public void HtmlStreamAttachments()
Assert.IsTrue(mmm.StreamAttachments.Count == 1);
mmm.StreamAttachments.Clear();
Assert.IsTrue(mmm.StreamAttachments.Count == 0);
mmm.StreamAttachments = null;
Assert.IsTrue(mmm.StreamAttachments != null && mmm.StreamAttachments.Count == 0);

mmm.StreamAttachments = streamAttachments;
Assert.IsTrue(mmm.StreamAttachments.Count == 2);
}
Expand All @@ -154,7 +153,7 @@ public void HtmlMailMergeWithStreamAttachment()
mmm.StreamAttachments.Clear();
mmm.StringAttachments.Clear();

using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(text ?? string.Empty));
using var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(text));
mmm.StreamAttachments.Add(new StreamAttachment(stream, streamAttFilename, "text/plain"));

var msg = mmm.GetMimeMessage(dataItem);
Expand Down Expand Up @@ -291,7 +290,7 @@ public void ConvertHtmlToPlainText()
[TestCase("{Name} {SenderAddr}", "John [email protected]")]
[TestCase("{Name {SenderAddr}", "{Name {SenderAddr}")] // parsing error
[TestCase("{NotExisting}", "{NotExisting}")] // formatting error
[TestCase(null, null)]
[TestCase("", "")]
public void SearchAndReplace(string text, string expected)
{
var dataItem = new
Expand All @@ -310,7 +309,7 @@ public void SearchAndReplace(string text, string expected)
[TestCase("{Name} {SenderAddr}", "John [email protected]")]
[TestCase("{Name {SenderAddr}", "{Name {SenderAddr}")] // parsing error
[TestCase("{NotExisting}", "{NotExisting}")] // formatting error
[TestCase(null, null)]
[TestCase("", "")]
public void SearchAndReplaceFilename(string text, string expected)
{
var dataItem = new
Expand Down
2 changes: 2 additions & 0 deletions Src/MailMergeLib.Tests/Message_Serialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using MailMergeLib.Templates;
using MimeKit;
using NUnit.Framework;

namespace MailMergeLib.Tests;
Expand Down
4 changes: 2 additions & 2 deletions Src/MailMergeLib.Tests/Message_SmartFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public void PlaceholderCaseSensitivityTest()
public void DataTypeTests()
{
// ******** Initialize ********
string result;
string? result;
string expected;
object dataItem;
var culture = CultureInfo.GetCultureInfo("en-US");
Expand Down Expand Up @@ -171,7 +171,7 @@ public void DataTypeTests()
catch (MailMergeMessage.MailMergeMessageException ex)
{
// will throw because of incomplete mail addresses, but Subject should contain placeholders replaced with content
result = ex.MimeMessage.Subject;
result = ex.MimeMessage?.Subject;
}

expected = text.Replace("{Email}", "[email protected]").Replace("{Continent}", "Europe");
Expand Down
6 changes: 1 addition & 5 deletions Src/MailMergeLib.Tests/Message_Templates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,10 @@ public void TemplateTest()
});
Assert.Throws<TemplateException>(() => t.Key = "This-is-definitely-an-illegal-Key-not-existing-in-any-Part");

Assert.False(t.Equals(null));
Assert.True(t.Equals(t));
Assert.False(t.Equals(new object()));

// Equality with null members
t.Name = t.Key = t.DefaultKey = null;
Assert.False(t.Equals(null));
Assert.True(t.Equals(t));
t.Key = t.DefaultKey = null;
Assert.False(t.Equals(new object()));
}
}
18 changes: 9 additions & 9 deletions Src/MailMergeLib.Tests/Message_VariableExceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,22 +46,22 @@ public void MissingVariableAndAttachmentsExceptions()
foreach (var ex in exceptions.InnerExceptions.Where(ex => !(ex is MailMergeMessage
.AttachmentException)))
{
if (ex is MailMergeMessage.VariableException)
if (ex is MailMergeMessage.VariableException exception)
{
Assert.AreEqual(9, (ex as MailMergeMessage.VariableException).MissingVariable.Count);
Assert.AreEqual(9, exception.MissingVariable.Count);
Console.WriteLine($"{nameof(MailMergeMessage.VariableException)} thrown successfully:");
Console.WriteLine("Missing variables: " +
string.Join(", ",
(ex as MailMergeMessage.VariableException).MissingVariable));
exception.MissingVariable));
Console.WriteLine();
}
if (ex is MailMergeMessage.AddressException)
if (ex is MailMergeMessage.AddressException addressException)
{
Console.WriteLine($"{nameof(MailMergeMessage.AddressException)} thrown successfully:");
Console.WriteLine((ex as MailMergeMessage.AddressException).Message);
Console.WriteLine(addressException.Message);
Console.WriteLine();
Assert.That((ex as MailMergeMessage.AddressException).Message == "No recipients." ||
(ex as MailMergeMessage.AddressException).Message == "No from address.");
Assert.That(addressException.Message == "No recipients." ||
addressException.Message == "No from address.");
}
}

Expand All @@ -73,9 +73,9 @@ public void MissingVariableAndAttachmentsExceptions()
{
Console.WriteLine($"{nameof(MailMergeMessage.AttachmentException)} thrown successfully:");
Console.WriteLine("Missing files: " +
string.Join(", ", (ex as MailMergeMessage.AttachmentException).BadAttachment));
string.Join(", ", (ex as MailMergeMessage.AttachmentException)?.BadAttachment!));
Console.WriteLine();
Assert.AreEqual(1, (ex as MailMergeMessage.AttachmentException).BadAttachment.Count);
Assert.AreEqual(1, (ex as MailMergeMessage.AttachmentException)?.BadAttachment.Count);
}
}

Expand Down
Loading

0 comments on commit 6ed181a

Please sign in to comment.