Skip to content

Commit

Permalink
Added unit test for SmtpClient .cctor
Browse files Browse the repository at this point in the history
  • Loading branch information
jstedfast committed Jan 15, 2024
1 parent 8b9bfd0 commit 0bb3367
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 21 deletions.
46 changes: 25 additions & 21 deletions MailKit/Net/Smtp/SmtpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,32 +92,36 @@ enum SmtpCommand {
bool secure;
Uri uri;

static SmtpClient ()
internal static string GetSafeHostName (string hostName)
{
string hostName;

try {
hostName = IPGlobalProperties.GetIPGlobalProperties ().HostName;
var idn = new IdnMapping ();

if (!string.IsNullOrEmpty (hostName)) {
hostName = hostName.Replace ('_', '-');
var idn = new IdnMapping ();

try {
hostName = idn.GetAscii (hostName);
} catch (ArgumentException) {
// This can happen if the hostName contains illegal unicode characters.
var ascii = new StringBuilder ();
for (int i = 0; i < hostName.Length; i++) {
if (hostName[i] <= 0x7F)
ascii.Append (hostName[i]);
}
if (!string.IsNullOrEmpty (hostName)) {
hostName = hostName.Replace ('_', '-');

hostName = ascii.Length > 0 ? ascii.ToString () : null;
try {
return idn.GetAscii (hostName);
} catch (ArgumentException) {
// This can happen if the hostName contains illegal unicode characters.
var ascii = new StringBuilder ();
for (int i = 0; i < hostName.Length; i++) {
if (hostName[i] <= 0x7F)
ascii.Append (hostName[i]);
}
} else {
hostName = null;

return ascii.Length > 0 ? ascii.ToString () : null;
}
} else {
return null;
}
}

static SmtpClient ()
{
string hostName;

try {
hostName = GetSafeHostName (IPGlobalProperties.GetIPGlobalProperties ().HostName);
} catch {
hostName = null;
}
Expand Down
22 changes: 22 additions & 0 deletions UnitTests/Net/Smtp/SmtpClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,28 @@ public void TestArgumentExceptions ()
}
}

[Test]
public void TestGetSafeHostName ()
{
string safe;

safe = SmtpClient.GetSafeHostName (null);
Assert.That (safe, Is.Null);

safe = SmtpClient.GetSafeHostName ("domain.com");
Assert.That (safe, Is.EqualTo ("domain.com"));

safe = SmtpClient.GetSafeHostName ("underscore_domain.com");
Assert.That (safe, Is.EqualTo ("underscore-domain.com"));

safe = SmtpClient.GetSafeHostName ("名がドメイン.com");
Assert.That (safe, Is.EqualTo ("xn--v8jxj3d1dzdz08w.com"));

var toolong = new string ('a', 256) + '.' + new string ('b', 256) + '.' + "com";
safe = SmtpClient.GetSafeHostName (toolong);
Assert.That (safe, Is.EqualTo (toolong));
}

static void AssertDefaultValues (string host, int port, SecureSocketOptions options, Uri expected)
{
SmtpClient.ComputeDefaultValues (host, ref port, ref options, out Uri uri, out bool starttls);
Expand Down

0 comments on commit 0bb3367

Please sign in to comment.