1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2024-10-29 23:12:39 +01:00
This commit is contained in:
Qstick 2021-08-03 00:43:28 -04:00 committed by Mark McDowall
parent 878d1561aa
commit 1c22a1ec0d
1201 changed files with 5620 additions and 4303 deletions

View File

@ -69,6 +69,7 @@ dotnet_diagnostic.SA1406.severity = suggestion
dotnet_diagnostic.SA1410.severity = suggestion dotnet_diagnostic.SA1410.severity = suggestion
dotnet_diagnostic.SA1411.severity = suggestion dotnet_diagnostic.SA1411.severity = suggestion
dotnet_diagnostic.SA1413.severity = none dotnet_diagnostic.SA1413.severity = none
dotnet_diagnostic.SA1512.severity = none
dotnet_diagnostic.SA1516.severity = none dotnet_diagnostic.SA1516.severity = none
dotnet_diagnostic.SA1600.severity = none dotnet_diagnostic.SA1600.severity = none
dotnet_diagnostic.SA1601.severity = none dotnet_diagnostic.SA1601.severity = none

1
.gitignore vendored
View File

@ -84,7 +84,6 @@ TestResults
[Tt]est[Rr]esult* [Tt]est[Rr]esult*
*.Cache *.Cache
ClientBin ClientBin
[Ss]tyle[Cc]op.*
~$* ~$*
*.dbmdl *.dbmdl
Generated_Code #added for RIA/Silverlight projects Generated_Code #added for RIA/Silverlight projects

View File

@ -104,6 +104,16 @@
<EnableNETAnalyzers>false</EnableNETAnalyzers> <EnableNETAnalyzers>false</EnableNETAnalyzers>
</PropertyGroup> </PropertyGroup>
<!-- Set up stylecop -->
<ItemGroup Condition="'$(SonarrProject)'=='true' and '$(EnableAnalyzers)'!='false'">
<!-- StyleCop analysis -->
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<AdditionalFiles Include="$(SolutionDir)stylecop.json" />
</ItemGroup>
<!-- <!--
Set runtime identifier to local system type if not specified Set runtime identifier to local system type if not specified
--> -->

View File

@ -16,7 +16,6 @@ namespace NzbDrone.Api.Test.ClientSchemaTests
schema.Should().HaveCount(2); schema.Should().HaveCount(2);
} }
[Test] [Test]
public void schema_should_have_proper_fields() public void schema_should_have_proper_fields()
{ {
@ -32,7 +31,6 @@ namespace NzbDrone.Api.Test.ClientSchemaTests
schema.Should().Contain(c => c.Order == 0 && c.Name == "firstName" && c.Label == "First Name" && c.HelpText == "Your First Name" && (string)c.Value == "Bob"); schema.Should().Contain(c => c.Order == 0 && c.Name == "firstName" && c.Label == "First Name" && c.HelpText == "Your First Name" && (string)c.Value == "Bob");
} }
[Test] [Test]
public void schema_should_have_nested_fields() public void schema_should_have_nested_fields()
{ {

View File

@ -7,7 +7,6 @@ namespace NzbDrone.Automation.Test
public AutomationTestAttribute() public AutomationTestAttribute()
: base("AutomationTest") : base("AutomationTest")
{ {
} }
} }
} }

View File

@ -1,4 +1,5 @@
using FluentAssertions; using System.Reflection;
using FluentAssertions;
using NUnit.Framework; using NUnit.Framework;
using NzbDrone.Automation.Test.PageModel; using NzbDrone.Automation.Test.PageModel;
using OpenQA.Selenium; using OpenQA.Selenium;
@ -8,73 +9,86 @@ namespace NzbDrone.Automation.Test
[TestFixture] [TestFixture]
public class MainPagesTest : AutomationTest public class MainPagesTest : AutomationTest
{ {
private PageBase page; private PageBase _page;
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
page = new PageBase(driver); _page = new PageBase(driver);
} }
[Test] [Test]
public void series_page() public void series_page()
{ {
page.SeriesNavIcon.Click(); _page.SeriesNavIcon.Click();
page.WaitForNoSpinner(); _page.WaitForNoSpinner();
page.Find(By.CssSelector("div[class*='SeriesIndex']")).Should().NotBeNull(); var imageName = MethodBase.GetCurrentMethod().Name;
TakeScreenshot(imageName);
_page.Find(By.CssSelector("div[class*='SeriesIndex']")).Should().NotBeNull();
} }
[Test] [Test]
public void calendar_page() public void calendar_page()
{ {
page.CalendarNavIcon.Click(); _page.CalendarNavIcon.Click();
page.WaitForNoSpinner(); _page.WaitForNoSpinner();
page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull(); var imageName = MethodBase.GetCurrentMethod().Name;
TakeScreenshot(imageName);
_page.Find(By.CssSelector("div[class*='CalendarPage']")).Should().NotBeNull();
} }
[Test] [Test]
public void activity_page() public void activity_page()
{ {
page.ActivityNavIcon.Click(); _page.ActivityNavIcon.Click();
page.WaitForNoSpinner(); _page.WaitForNoSpinner();
page.Find(By.LinkText("Queue")).Should().NotBeNull(); var imageName = MethodBase.GetCurrentMethod().Name;
page.Find(By.LinkText("History")).Should().NotBeNull(); TakeScreenshot(imageName);
page.Find(By.LinkText("Blocklist")).Should().NotBeNull();
_page.Find(By.LinkText("Queue")).Should().NotBeNull();
_page.Find(By.LinkText("History")).Should().NotBeNull();
_page.Find(By.LinkText("Blocklist")).Should().NotBeNull();
} }
[Test] [Test]
public void wanted_page() public void wanted_page()
{ {
page.WantedNavIcon.Click(); _page.WantedNavIcon.Click();
page.WaitForNoSpinner(); _page.WaitForNoSpinner();
page.Find(By.LinkText("Missing")).Should().NotBeNull(); _page.Find(By.LinkText("Missing")).Should().NotBeNull();
page.Find(By.LinkText("Cutoff Unmet")).Should().NotBeNull(); _page.Find(By.LinkText("Cutoff Unmet")).Should().NotBeNull();
} }
[Test] [Test]
public void system_page() public void system_page()
{ {
page.SystemNavIcon.Click(); _page.SystemNavIcon.Click();
page.WaitForNoSpinner(); _page.WaitForNoSpinner();
page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull(); var imageName = MethodBase.GetCurrentMethod().Name;
TakeScreenshot(imageName);
_page.Find(By.CssSelector("div[class*='Health']")).Should().NotBeNull();
} }
[Test] [Test]
public void add_series_page() public void add_series_page()
{ {
page.SeriesNavIcon.Click(); _page.SeriesNavIcon.Click();
page.WaitForNoSpinner(); _page.WaitForNoSpinner();
page.Find(By.LinkText("Add New")).Click(); _page.Find(By.LinkText("Add New")).Click();
page.WaitForNoSpinner(); var imageName = MethodBase.GetCurrentMethod().Name;
TakeScreenshot(imageName);
page.Find(By.CssSelector("input[class*='AddNewSeries/searchInput']")).Should().NotBeNull(); _page.Find(By.CssSelector("input[class*='AddNewSeries-searchInput']")).Should().NotBeNull();
} }
} }
} }

View File

@ -59,4 +59,4 @@ namespace NzbDrone.Automation.Test.PageModel
public IWebElement SystemNavIcon => Find(By.PartialLinkText("System")); public IWebElement SystemNavIcon => Find(By.PartialLinkText("System"));
} }
} }

View File

@ -4,7 +4,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Selenium.Support" Version="3.141.0" /> <PackageReference Include="Selenium.Support" Version="3.141.0" />
<PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="88.0.4324.9600" /> <PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="92.0.4515.10700" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\NzbDrone.Test.Common\Sonarr.Test.Common.csproj" /> <ProjectReference Include="..\NzbDrone.Test.Common\Sonarr.Test.Common.csproj" />

View File

@ -99,4 +99,4 @@ namespace NzbDrone.Common.Test.CacheTests
return result; return result;
} }
} }
} }

View File

@ -26,7 +26,6 @@ namespace NzbDrone.Common.Test.CacheTests
_cachedString.Get("Test", _worker.GetString); _cachedString.Get("Test", _worker.GetString);
_worker.HitCount.Should().Be(1); _worker.HitCount.Should().Be(1);
} }
[Test] [Test]
@ -38,7 +37,6 @@ namespace NzbDrone.Common.Test.CacheTests
first.Should().Be(second); first.Should().Be(second);
} }
[Test] [Test]
public void should_be_able_to_update_key() public void should_be_able_to_update_key()
{ {
@ -48,7 +46,6 @@ namespace NzbDrone.Common.Test.CacheTests
_cachedString.Find("Key").Should().Be("New"); _cachedString.Find("Key").Should().Be("New");
} }
[Test] [Test]
public void should_be_able_to_remove_key() public void should_be_able_to_remove_key()
{ {
@ -70,7 +67,6 @@ namespace NzbDrone.Common.Test.CacheTests
{ {
int hitCount = 0; int hitCount = 0;
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
_cachedString.Get("key", () => _cachedString.Get("key", () =>
@ -84,6 +80,7 @@ namespace NzbDrone.Common.Test.CacheTests
} }
[Test] [Test]
[Platform(Exclude = "MacOsX")]
public void should_honor_ttl() public void should_honor_ttl()
{ {
int hitCount = 0; int hitCount = 0;
@ -91,11 +88,13 @@ namespace NzbDrone.Common.Test.CacheTests
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
_cachedString.Get("key", () => _cachedString.Get("key",
() =>
{ {
hitCount++; hitCount++;
return null; return null;
}, TimeSpan.FromMilliseconds(300)); },
TimeSpan.FromMilliseconds(300));
Thread.Sleep(100); Thread.Sleep(100);
} }
@ -114,4 +113,4 @@ namespace NzbDrone.Common.Test.CacheTests
return "Hit count is " + HitCount; return "Hit count is " + HitCount;
} }
} }
} }

View File

@ -26,4 +26,4 @@ namespace NzbDrone.Common.Test.CacheTests
result1.Should().BeSameAs(result2); result1.Should().BeSameAs(result2);
} }
} }
} }

View File

@ -62,10 +62,8 @@ namespace NzbDrone.Common.Test
const string key = "Port"; const string key = "Port";
const int value = 8989; const int value = 8989;
var result = Subject.GetValueInt(key, value); var result = Subject.GetValueInt(key, value);
result.Should().Be(value); result.Should().Be(value);
} }
@ -75,20 +73,16 @@ namespace NzbDrone.Common.Test
const string key = "LaunchBrowser"; const string key = "LaunchBrowser";
const bool value = true; const bool value = true;
var result = Subject.GetValueBoolean(key, value); var result = Subject.GetValueBoolean(key, value);
result.Should().BeTrue(); result.Should().BeTrue();
} }
[Test] [Test]
public void GetLaunchBrowser_Success() public void GetLaunchBrowser_Success()
{ {
var result = Subject.LaunchBrowser; var result = Subject.LaunchBrowser;
result.Should().Be(true); result.Should().Be(true);
} }
@ -97,10 +91,8 @@ namespace NzbDrone.Common.Test
{ {
const int value = 8989; const int value = 8989;
var result = Subject.Port; var result = Subject.Port;
result.Should().Be(value); result.Should().Be(value);
} }
@ -110,10 +102,8 @@ namespace NzbDrone.Common.Test
const string key = "LaunchBrowser"; const string key = "LaunchBrowser";
const bool value = false; const bool value = false;
Subject.SetValue(key, value); Subject.SetValue(key, value);
var result = Subject.LaunchBrowser; var result = Subject.LaunchBrowser;
result.Should().Be(value); result.Should().Be(value);
} }
@ -124,10 +114,8 @@ namespace NzbDrone.Common.Test
const string key = "Port"; const string key = "Port";
const int value = 12345; const int value = 12345;
Subject.SetValue(key, value); Subject.SetValue(key, value);
var result = Subject.Port; var result = Subject.Port;
result.Should().Be(value); result.Should().Be(value);
} }
@ -138,10 +126,8 @@ namespace NzbDrone.Common.Test
const string key = "Hello"; const string key = "Hello";
const string value = "World"; const string value = "World";
var result = Subject.GetValue(key, value); var result = Subject.GetValue(key, value);
result.Should().Be(value); result.Should().Be(value);
} }
@ -178,7 +164,6 @@ namespace NzbDrone.Common.Test
dic["SslPort"] = origSslPort; dic["SslPort"] = origSslPort;
Subject.SaveConfigDictionary(dic); Subject.SaveConfigDictionary(dic);
dic = new Dictionary<string, object>(); dic = new Dictionary<string, object>();
dic["SslPort"] = sslPort; dic["SslPort"] = sslPort;
Subject.SaveConfigDictionary(dic); Subject.SaveConfigDictionary(dic);
@ -213,4 +198,4 @@ namespace NzbDrone.Common.Test
Assert.Throws<InvalidConfigFileException>(() => Subject.GetValue("key", "value")); Assert.Throws<InvalidConfigFileException>(() => Subject.GetValue("key", "value"));
} }
} }
} }

View File

@ -76,7 +76,7 @@ namespace NzbDrone.Common.Test.DiskTests
.Returns(_folders); .Returns(_folders);
var result = Subject.LookupContents(root, false, false); var result = Subject.LookupContents(root, false, false);
result.Directories.Should().HaveCount(_folders.Count - 3); result.Directories.Should().HaveCount(_folders.Count - 3);
result.Directories.Should().NotContain(f => f.Name == RECYCLING_BIN); result.Directories.Should().NotContain(f => f.Name == RECYCLING_BIN);

View File

@ -1,4 +1,4 @@
using System; using System;
using System.IO; using System.IO;
using FluentAssertions; using FluentAssertions;
using NUnit.Framework; using NUnit.Framework;
@ -7,7 +7,8 @@ using NzbDrone.Test.Common;
namespace NzbDrone.Common.Test.DiskTests namespace NzbDrone.Common.Test.DiskTests
{ {
public abstract class DiskProviderFixtureBase<TSubject> : TestBase<TSubject> where TSubject : class, IDiskProvider public abstract class DiskProviderFixtureBase<TSubject> : TestBase<TSubject>
where TSubject : class, IDiskProvider
{ {
[Test] [Test]
[Retry(5)] [Retry(5)]
@ -154,7 +155,7 @@ namespace NzbDrone.Common.Test.DiskTests
public void should_return_false_for_unlocked_file() public void should_return_false_for_unlocked_file()
{ {
var testFile = GetTempFilePath(); var testFile = GetTempFilePath();
Subject.WriteAllText(testFile, new Guid().ToString()); Subject.WriteAllText(testFile, default(Guid).ToString());
Subject.IsFileLocked(testFile).Should().BeFalse(); Subject.IsFileLocked(testFile).Should().BeFalse();
} }
@ -163,7 +164,7 @@ namespace NzbDrone.Common.Test.DiskTests
public void should_return_false_for_unlocked_and_readonly_file() public void should_return_false_for_unlocked_and_readonly_file()
{ {
var testFile = GetTempFilePath(); var testFile = GetTempFilePath();
Subject.WriteAllText(testFile, new Guid().ToString()); Subject.WriteAllText(testFile, default(Guid).ToString());
File.SetAttributes(testFile, FileAttributes.ReadOnly); File.SetAttributes(testFile, FileAttributes.ReadOnly);
@ -174,7 +175,7 @@ namespace NzbDrone.Common.Test.DiskTests
public void should_return_true_for_unlocked_file() public void should_return_true_for_unlocked_file()
{ {
var testFile = GetTempFilePath(); var testFile = GetTempFilePath();
Subject.WriteAllText(testFile, new Guid().ToString()); Subject.WriteAllText(testFile, default(Guid).ToString());
using (var file = File.OpenWrite(testFile)) using (var file = File.OpenWrite(testFile))
{ {
@ -186,7 +187,7 @@ namespace NzbDrone.Common.Test.DiskTests
public void should_be_able_to_set_permission_from_parrent() public void should_be_able_to_set_permission_from_parrent()
{ {
var testFile = GetTempFilePath(); var testFile = GetTempFilePath();
Subject.WriteAllText(testFile, new Guid().ToString()); Subject.WriteAllText(testFile, default(Guid).ToString());
Subject.InheritFolderPermissions(testFile); Subject.InheritFolderPermissions(testFile);
} }
@ -195,7 +196,7 @@ namespace NzbDrone.Common.Test.DiskTests
public void should_be_set_last_file_write() public void should_be_set_last_file_write()
{ {
var testFile = GetTempFilePath(); var testFile = GetTempFilePath();
Subject.WriteAllText(testFile, new Guid().ToString()); Subject.WriteAllText(testFile, default(Guid).ToString());
var lastWriteTime = DateTime.SpecifyKind(new DateTime(2012, 1, 2), DateTimeKind.Utc); var lastWriteTime = DateTime.SpecifyKind(new DateTime(2012, 1, 2), DateTimeKind.Utc);

View File

@ -751,7 +751,9 @@ namespace NzbDrone.Common.Test.DiskTests
{ {
var dir = Path.GetDirectoryName(path); var dir = Path.GetDirectoryName(path);
if (exists && dir.IsNotNullOrWhiteSpace()) if (exists && dir.IsNotNullOrWhiteSpace())
{
WithExistingFolder(dir); WithExistingFolder(dir);
}
Mocker.GetMock<IDiskProvider>() Mocker.GetMock<IDiskProvider>()
.Setup(v => v.FolderExists(path)) .Setup(v => v.FolderExists(path))
@ -762,7 +764,9 @@ namespace NzbDrone.Common.Test.DiskTests
{ {
var dir = Path.GetDirectoryName(path); var dir = Path.GetDirectoryName(path);
if (exists && dir.IsNotNullOrWhiteSpace()) if (exists && dir.IsNotNullOrWhiteSpace())
{
WithExistingFolder(dir); WithExistingFolder(dir);
}
Mocker.GetMock<IDiskProvider>() Mocker.GetMock<IDiskProvider>()
.Setup(v => v.FileExists(path)) .Setup(v => v.FileExists(path))
@ -816,7 +820,6 @@ namespace NzbDrone.Common.Test.DiskTests
WithExistingFile(v, false); WithExistingFile(v, false);
}); });
Mocker.GetMock<IDiskProvider>() Mocker.GetMock<IDiskProvider>()
.Setup(v => v.FolderExists(It.IsAny<string>())) .Setup(v => v.FolderExists(It.IsAny<string>()))
.Returns(false); .Returns(false);
@ -834,6 +837,7 @@ namespace NzbDrone.Common.Test.DiskTests
{ {
WithExistingFolder(s, false); WithExistingFolder(s, false);
WithExistingFolder(d); WithExistingFolder(d);
// Note: Should also deal with the files. // Note: Should also deal with the files.
}); });
@ -842,6 +846,7 @@ namespace NzbDrone.Common.Test.DiskTests
.Callback<string, bool>((f, r) => .Callback<string, bool>((f, r) =>
{ {
WithExistingFolder(f, false); WithExistingFolder(f, false);
// Note: Should also deal with the files. // Note: Should also deal with the files.
}); });
@ -907,8 +912,13 @@ namespace NzbDrone.Common.Test.DiskTests
Mocker.GetMock<IDiskProvider>() Mocker.GetMock<IDiskProvider>()
.Setup(v => v.MoveFile(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())) .Setup(v => v.MoveFile(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
.Callback<string, string, bool>((s,d,o) => { .Callback<string, string, bool>((s, d, o) =>
if (File.Exists(d) && o) File.Delete(d); {
if (File.Exists(d) && o)
{
File.Delete(d);
}
File.Move(s, d); File.Move(s, d);
}); });

View File

@ -7,7 +7,8 @@ using NzbDrone.Test.Common;
namespace NzbDrone.Common.Test.DiskTests namespace NzbDrone.Common.Test.DiskTests
{ {
public abstract class FreeSpaceFixtureBase<TSubject> : TestBase<TSubject> where TSubject : class, IDiskProvider public abstract class FreeSpaceFixtureBase<TSubject> : TestBase<TSubject>
where TSubject : class, IDiskProvider
{ {
[Test] [Test]
public void should_get_free_space_for_folder() public void should_get_free_space_for_folder()

View File

@ -15,7 +15,6 @@ namespace NzbDrone.Common.Test.EnsureTest
Ensure.That(path, () => path).IsValidPath(); Ensure.That(path, () => path).IsValidPath();
} }
[TestCase(@"/var/user/file with, comma.mkv")] [TestCase(@"/var/user/file with, comma.mkv")]
public void EnsureLinuxPath(string path) public void EnsureLinuxPath(string path)
{ {

View File

@ -10,13 +10,11 @@ namespace NzbDrone.Common.Test
[TestFixture] [TestFixture]
public class IAppDirectoryInfoTest : TestBase<AppFolderInfo> public class IAppDirectoryInfoTest : TestBase<AppFolderInfo>
{ {
[Test] [Test]
public void StartupPath_should_not_be_empty() public void StartupPath_should_not_be_empty()
{ {
Subject.StartUpFolder.Should().NotBeNullOrWhiteSpace(); Subject.StartUpFolder.Should().NotBeNullOrWhiteSpace();
Path.IsPathRooted(Subject.StartUpFolder).Should().BeTrue("Path is not rooted"); Path.IsPathRooted(Subject.StartUpFolder).Should().BeTrue("Path is not rooted");
} }
[Test] [Test]

View File

@ -9,13 +9,11 @@ namespace NzbDrone.Common.Test.EnvironmentTests
[TestFixture] [TestFixture]
public class BuildInfoTest : TestBase public class BuildInfoTest : TestBase
{ {
[TestCase("0.0.0.0")] [TestCase("0.0.0.0")]
[TestCase("1.0.0.0")] [TestCase("1.0.0.0")]
public void Application_version_should_not_be_default(string version) public void Application_version_should_not_be_default(string version)
{ {
BuildInfo.Version.Should().NotBe(new Version(version)); BuildInfo.Version.Should().NotBe(new Version(version));
} }
} }
} }

View File

@ -26,7 +26,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests
args.Flags.Contains("t").Should().BeTrue(); args.Flags.Contains("t").Should().BeTrue();
} }
[TestCase("/key=value")] [TestCase("/key=value")]
[TestCase("/KEY=value")] [TestCase("/KEY=value")]
[TestCase(" /key=\"value\"")] [TestCase(" /key=\"value\"")]
@ -37,7 +36,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests
args.Args["key"].Should().Be("value"); args.Args["key"].Should().Be("value");
} }
[TestCase("/data=test", "/data=test")] [TestCase("/data=test", "/data=test")]
[TestCase("/Data=/a/b/c", "/data=/a/b/c")] [TestCase("/Data=/a/b/c", "/data=/a/b/c")]
public void should_preserver_data(string arg, string preserved) public void should_preserver_data(string arg, string preserved)
@ -55,7 +53,6 @@ namespace NzbDrone.Common.Test.EnvironmentTests
args.PreservedArguments.Should().Be(preserved); args.PreservedArguments.Should().Be(preserved);
} }
[Test] [Test]
public void should_preserver_both() public void should_preserver_both()
{ {

View File

@ -56,7 +56,7 @@ namespace NzbDrone.Common.Test.ExtensionTests.IEnumerableExtensionTests
var result = first.ExceptBy(o => o.Prop1, second, o => o.Prop1, StringComparer.InvariantCultureIgnoreCase).ToList(); var result = first.ExceptBy(o => o.Prop1, second, o => o.Prop1, StringComparer.InvariantCultureIgnoreCase).ToList();
result.Should().HaveCount(1); result.Should().HaveCount(1);
result.First().GetType().Should().Be(typeof (Object1)); result.First().GetType().Should().Be(typeof(Object1));
result.First().Prop1.Should().Be("two"); result.First().Prop1.Should().Be("two");
} }
} }

View File

@ -24,7 +24,6 @@ namespace NzbDrone.Common.Test.ExtensionTests
public void should_return_false_for_public_ip_address(string ipAddress) public void should_return_false_for_public_ip_address(string ipAddress)
{ {
IPAddress.Parse(ipAddress).IsLocalAddress().Should().BeFalse(); IPAddress.Parse(ipAddress).IsLocalAddress().Should().BeFalse();
} }
} }
} }

View File

@ -18,4 +18,4 @@ namespace NzbDrone.Common.Test
HashUtil.AnonymousToken().Should().Be(HashUtil.AnonymousToken()); HashUtil.AnonymousToken().Should().Be(HashUtil.AnonymousToken());
} }
} }
} }

View File

@ -23,7 +23,8 @@ namespace NzbDrone.Common.Test.Http
[Ignore("httpbin is bugged")] [Ignore("httpbin is bugged")]
[IntegrationTest] [IntegrationTest]
[TestFixture(typeof(ManagedHttpDispatcher))] [TestFixture(typeof(ManagedHttpDispatcher))]
public class HttpClientFixture<TDispatcher> : TestBase<HttpClient> where TDispatcher : IHttpDispatcher public class HttpClientFixture<TDispatcher> : TestBase<HttpClient>
where TDispatcher : IHttpDispatcher
{ {
private string[] _httpBinHosts; private string[] _httpBinHosts;
private int _httpBinSleep; private int _httpBinSleep;
@ -35,6 +36,7 @@ namespace NzbDrone.Common.Test.Http
public void FixtureSetUp() public void FixtureSetUp()
{ {
var candidates = new[] { "eu.httpbin.org", /*"httpbin.org",*/ "www.httpbin.org" }; var candidates = new[] { "eu.httpbin.org", /*"httpbin.org",*/ "www.httpbin.org" };
// httpbin.org is broken right now, occassionally redirecting to https if it's unavailable. // httpbin.org is broken right now, occassionally redirecting to https if it's unavailable.
_httpBinHosts = candidates.Where(IsTestSiteAvailable).ToArray(); _httpBinHosts = candidates.Where(IsTestSiteAvailable).ToArray();
@ -49,7 +51,10 @@ namespace NzbDrone.Common.Test.Http
{ {
var req = WebRequest.Create($"http://{site}/get") as HttpWebRequest; var req = WebRequest.Create($"http://{site}/get") as HttpWebRequest;
var res = req.GetResponse() as HttpWebResponse; var res = req.GetResponse() as HttpWebResponse;
if (res.StatusCode != HttpStatusCode.OK) return false; if (res.StatusCode != HttpStatusCode.OK)
{
return false;
}
try try
{ {
@ -61,7 +66,10 @@ namespace NzbDrone.Common.Test.Http
res = ex.Response as HttpWebResponse; res = ex.Response as HttpWebResponse;
} }
if (res == null || res.StatusCode != (HttpStatusCode)429) return false; if (res == null || res.StatusCode != (HttpStatusCode)429)
{
return false;
}
return true; return true;
} }
@ -688,7 +696,7 @@ namespace NzbDrone.Common.Test.Http
[Test] [Test]
public void should_call_interceptor() public void should_call_interceptor()
{ {
Mocker.SetConstant<IEnumerable<IHttpRequestInterceptor>>(new [] { Mocker.GetMock<IHttpRequestInterceptor>().Object }); Mocker.SetConstant<IEnumerable<IHttpRequestInterceptor>>(new[] { Mocker.GetMock<IHttpRequestInterceptor>().Object });
Mocker.GetMock<IHttpRequestInterceptor>() Mocker.GetMock<IHttpRequestInterceptor>()
.Setup(v => v.PreRequest(It.IsAny<HttpRequest>())) .Setup(v => v.PreRequest(It.IsAny<HttpRequest>()))

View File

@ -1,11 +1,11 @@
using NUnit.Framework; using System;
using FluentAssertions;
using NzbDrone.Test.Common;
using System;
using System.Text;
using NzbDrone.Common.Http;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.Linq; using System.Linq;
using System.Text;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Http;
using NzbDrone.Test.Common;
namespace NzbDrone.Common.Test.Http namespace NzbDrone.Common.Test.Http
{ {

View File

@ -35,7 +35,6 @@ namespace NzbDrone.Common.Test.Http
var request = builder.Resource("/v1/").Build(); var request = builder.Resource("/v1/").Build();
request.Url.FullUri.Should().Be("http://domain/v1/"); request.Url.FullUri.Should().Be("http://domain/v1/");
} }
} }
} }

View File

@ -6,4 +6,4 @@ namespace NzbDrone.Common.Test.Http
public class HttpRequestFixture public class HttpRequestFixture
{ {
} }
} }

View File

@ -27,4 +27,4 @@ namespace NzbDrone.Common.Test.Http
Subject.GetUserAgent(false).Should().NotBeNullOrWhiteSpace(); Subject.GetUserAgent(false).Should().NotBeNullOrWhiteSpace();
} }
} }
} }

View File

@ -1,6 +1,6 @@
using NUnit.Framework;
using NzbDrone.Common.Instrumentation;
using FluentAssertions; using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Instrumentation;
namespace NzbDrone.Common.Test.InstrumentationTests namespace NzbDrone.Common.Test.InstrumentationTests
{ {
@ -16,9 +16,11 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[TestCase(@"https://baconbits.org/feeds.php?feed=torrents_tv&user=12345&auth=2b51db35e1910123321025a12b9933d2&passkey=mySecret&authkey=2b51db35e1910123321025a12b9933d2")] [TestCase(@"https://baconbits.org/feeds.php?feed=torrents_tv&user=12345&auth=2b51db35e1910123321025a12b9933d2&passkey=mySecret&authkey=2b51db35e1910123321025a12b9933d2")]
[TestCase(@"http://127.0.0.1:9117/dl/indexername?jackett_apikey=flwjiefewklfjacketmySecretsdfldskjfsdlk&path=we0re9f0sdfbase64sfdkfjsdlfjk&file=The+Torrent+File+Name.torrent")] [TestCase(@"http://127.0.0.1:9117/dl/indexername?jackett_apikey=flwjiefewklfjacketmySecretsdfldskjfsdlk&path=we0re9f0sdfbase64sfdkfjsdlfjk&file=The+Torrent+File+Name.torrent")]
[TestCase(@"http://nzb.su/getnzb/2b51db35e1912ffc138825a12b9933d2.nzb&i=37292&r=2b51db35e1910123321025a12b9933d2")] [TestCase(@"http://nzb.su/getnzb/2b51db35e1912ffc138825a12b9933d2.nzb&i=37292&r=2b51db35e1910123321025a12b9933d2")]
// NzbGet // NzbGet
[TestCase(@"{ ""Name"" : ""ControlUsername"", ""Value"" : ""mySecret"" }, { ""Name"" : ""ControlPassword"", ""Value"" : ""mySecret"" }, ")] [TestCase(@"{ ""Name"" : ""ControlUsername"", ""Value"" : ""mySecret"" }, { ""Name"" : ""ControlPassword"", ""Value"" : ""mySecret"" }, ")]
[TestCase(@"{ ""Name"" : ""Server1.Username"", ""Value"" : ""mySecret"" }, { ""Name"" : ""Server1.Password"", ""Value"" : ""mySecret"" }, ")] [TestCase(@"{ ""Name"" : ""Server1.Username"", ""Value"" : ""mySecret"" }, { ""Name"" : ""Server1.Password"", ""Value"" : ""mySecret"" }, ")]
// Sabnzbd // Sabnzbd
[TestCase(@"http://127.0.0.1:1234/api/call?vv=1&apikey=mySecret")] [TestCase(@"http://127.0.0.1:1234/api/call?vv=1&apikey=mySecret")]
[TestCase(@"http://127.0.0.1:1234/api/call?vv=1&ma_username=mySecret&ma_password=mySecret")] [TestCase(@"http://127.0.0.1:1234/api/call?vv=1&ma_username=mySecret&ma_password=mySecret")]
@ -29,6 +31,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[TestCase(@"""misc"":{""username"":""mySecret"",""api_key"":""mySecret"",""password"":""mySecret"",""nzb_key"":""mySecret""}")] [TestCase(@"""misc"":{""username"":""mySecret"",""api_key"":""mySecret"",""password"":""mySecret"",""nzb_key"":""mySecret""}")]
[TestCase(@"""servers"":[{""username"":""mySecret"",""password"":""mySecret""}]")] [TestCase(@"""servers"":[{""username"":""mySecret"",""password"":""mySecret""}]")]
[TestCase(@"""misc"":{""email_account"":""mySecret"",""email_to"":[],""email_from"":"""",""email_pwd"":""mySecret""}")] [TestCase(@"""misc"":{""email_account"":""mySecret"",""email_to"":[],""email_from"":"""",""email_pwd"":""mySecret""}")]
// uTorrent // uTorrent
[TestCase(@"http://localhost:9091/gui/?token=wThmph5l0ZXfH-a6WOA4lqiLvyjCP0FpMrMeXmySecret_VXBO11HoKL751MAAAAA&list=1")] [TestCase(@"http://localhost:9091/gui/?token=wThmph5l0ZXfH-a6WOA4lqiLvyjCP0FpMrMeXmySecret_VXBO11HoKL751MAAAAA&list=1")]
[TestCase(@",[""boss_key"",0,""mySecret"",{""access"":""Y""}],[""boss_key_salt"",0,""mySecret"",{""access"":""W""}]")] [TestCase(@",[""boss_key"",0,""mySecret"",{""access"":""Y""}],[""boss_key_salt"",0,""mySecret"",{""access"":""W""}]")]
@ -36,22 +39,28 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[TestCase(@",[""webui.uconnect_username"",2,""mySecret"",{""access"":""Y""}],[""webui.uconnect_password"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""webui.uconnect_username"",2,""mySecret"",{""access"":""Y""}],[""webui.uconnect_password"",2,""mySecret"",{""access"":""Y""}]")]
[TestCase(@",[""proxy.proxy"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""proxy.proxy"",2,""mySecret"",{""access"":""Y""}]")]
[TestCase(@",[""proxy.username"",2,""mySecret"",{""access"":""Y""}],[""proxy.password"",2,""mySecret"",{""access"":""Y""}]")] [TestCase(@",[""proxy.username"",2,""mySecret"",{""access"":""Y""}],[""proxy.password"",2,""mySecret"",{""access"":""Y""}]")]
// Deluge // Deluge
[TestCase(@",{""download_location"": ""C:\Users\\mySecret mySecret\\Downloads""}")] [TestCase(@",{""download_location"": ""C:\Users\\mySecret mySecret\\Downloads""}")]
[TestCase(@",{""download_location"": ""/home/mySecret/Downloads""}")] [TestCase(@",{""download_location"": ""/home/mySecret/Downloads""}")]
[TestCase(@"auth.login(""mySecret"")")] [TestCase(@"auth.login(""mySecret"")")]
// Download Station // Download Station
[TestCase(@"webapi/entry.cgi?api=(removed)&version=2&method=login&account=01233210&passwd=mySecret&format=sid&session=DownloadStation")] [TestCase(@"webapi/entry.cgi?api=(removed)&version=2&method=login&account=01233210&passwd=mySecret&format=sid&session=DownloadStation")]
// BroadcastheNet // BroadcastheNet
[TestCase(@"method: ""getTorrents"", ""params"": [ ""mySecret"",")] [TestCase(@"method: ""getTorrents"", ""params"": [ ""mySecret"",")]
[TestCase(@"getTorrents(""mySecret"", [asdfasdf], 100, 0)")] [TestCase(@"getTorrents(""mySecret"", [asdfasdf], 100, 0)")]
[TestCase(@"""DownloadURL"":""https:\/\/broadcasthe.net\/torrents.php?action=download&id=123&authkey=mySecret&torrent_pass=mySecret""")] [TestCase(@"""DownloadURL"":""https:\/\/broadcasthe.net\/torrents.php?action=download&id=123&authkey=mySecret&torrent_pass=mySecret""")]
// Plex // Plex
[TestCase(@" http://localhost:32400/library/metadata/12345/refresh?X-Plex-Client-Identifier=1234530f-422f-4aac-b6b3-01233210aaaa&X-Plex-Product=Sonarr&X-Plex-Platform=Windows&X-Plex-Platform-Version=7&X-Plex-Device-Name=Sonarr&X-Plex-Version=3.0.3.833&X-Plex-Token=mySecret")] [TestCase(@" http://localhost:32400/library/metadata/12345/refresh?X-Plex-Client-Identifier=1234530f-422f-4aac-b6b3-01233210aaaa&X-Plex-Product=Sonarr&X-Plex-Platform=Windows&X-Plex-Platform-Version=7&X-Plex-Device-Name=Sonarr&X-Plex-Version=3.0.3.833&X-Plex-Token=mySecret")]
// Internal // Internal
[TestCase(@"OutputPath=/home/mySecret/Downloads")] [TestCase(@"OutputPath=/home/mySecret/Downloads")]
[TestCase("Hardlinking episode file: /home/mySecret/Downloads to /media/abc.mkv")] [TestCase("Hardlinking episode file: /home/mySecret/Downloads to /media/abc.mkv")]
[TestCase("Hardlink '/home/mySecret/Downloads/abs.mkv' to '/media/abc.mkv' failed.")] [TestCase("Hardlink '/home/mySecret/Downloads/abs.mkv' to '/media/abc.mkv' failed.")]
// Announce URLs (passkeys) Magnet & Tracker // Announce URLs (passkeys) Magnet & Tracker
[TestCase(@"magnet_uri"":""magnet:?xt=urn:btih:9pr04sgkillroyimaveql2tyu8xyui&dn=&tr=https%3a%2f%2fxxx.yyy%2f9pr04sg601233210imaveql2tyu8xyui%2fannounce""}")] [TestCase(@"magnet_uri"":""magnet:?xt=urn:btih:9pr04sgkillroyimaveql2tyu8xyui&dn=&tr=https%3a%2f%2fxxx.yyy%2f9pr04sg601233210imaveql2tyu8xyui%2fannounce""}")]
[TestCase(@"magnet_uri"":""magnet:?xt=urn:btih:9pr04sgkillroyimaveql2tyu8xyui&dn=&tr=https%3a%2f%2fxxx.yyy%2ftracker.php%2f9pr04sg601233210imaveql2tyu8xyui%2fannounce""}")] [TestCase(@"magnet_uri"":""magnet:?xt=urn:btih:9pr04sgkillroyimaveql2tyu8xyui&dn=&tr=https%3a%2f%2fxxx.yyy%2ftracker.php%2f9pr04sg601233210imaveql2tyu8xyui%2fannounce""}")]
@ -62,6 +71,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[TestCase(@"tracker"":""https://xxx.yyy/announce/9pr04sg601233210imaveql2tyu8xyui""}")] [TestCase(@"tracker"":""https://xxx.yyy/announce/9pr04sg601233210imaveql2tyu8xyui""}")]
[TestCase(@"tracker"":""https://xxx.yyy/announce.php?passkey=9pr04sg601233210imaveql2tyu8xyui""}")] [TestCase(@"tracker"":""https://xxx.yyy/announce.php?passkey=9pr04sg601233210imaveql2tyu8xyui""}")]
[TestCase(@"tracker"":""http://xxx.yyy/announce.php?passkey=9pr04sg601233210imaveql2tyu8xyui"",""info"":""http://xxx.yyy/info?a=b""")] [TestCase(@"tracker"":""http://xxx.yyy/announce.php?passkey=9pr04sg601233210imaveql2tyu8xyui"",""info"":""http://xxx.yyy/info?a=b""")]
// Webhooks - Notifiarr // Webhooks - Notifiarr
[TestCase(@"https://xxx.yyy/api/v1/notification/sonarr/9pr04sg6-0123-3210-imav-eql2tyu8xyui")] [TestCase(@"https://xxx.yyy/api/v1/notification/sonarr/9pr04sg6-0123-3210-imav-eql2tyu8xyui")]

View File

@ -1,24 +1,25 @@
using NUnit.Framework;
using FluentAssertions;
using NzbDrone.Common.Instrumentation.Sentry;
using System; using System;
using NLog;
using NzbDrone.Test.Common;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using FluentAssertions;
using NLog;
using NUnit.Framework;
using NzbDrone.Common.Instrumentation.Sentry;
using NzbDrone.Test.Common;
namespace NzbDrone.Common.Test.InstrumentationTests namespace NzbDrone.Common.Test.InstrumentationTests
{ {
[TestFixture] [TestFixture]
public class SentryTargetFixture : TestBase public class SentryTargetFixture : TestBase
{ {
private SentryTarget Subject; private SentryTarget _subject;
private static LogLevel[] AllLevels = LogLevel.AllLevels.ToArray(); private static LogLevel[] AllLevels = LogLevel.AllLevels.ToArray();
private static LogLevel[] SentryLevels = LogLevel.AllLevels.Where(x => x >= LogLevel.Error).ToArray(); private static LogLevel[] SentryLevels = LogLevel.AllLevels.Where(x => x >= LogLevel.Error).ToArray();
private static LogLevel[] OtherLevels = AllLevels.Except(SentryLevels).ToArray(); private static LogLevel[] OtherLevels = AllLevels.Except(SentryLevels).ToArray();
private static Exception[] FilteredExceptions = new Exception[] { private static Exception[] FilteredExceptions = new Exception[]
{
new UnauthorizedAccessException(), new UnauthorizedAccessException(),
new TinyIoC.TinyIoCResolutionException(typeof(string)) new TinyIoC.TinyIoCResolutionException(typeof(string))
}; };
@ -26,7 +27,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
Subject = new SentryTarget("https://aaaaaaaaaaaaaaaaaaaaaaaaaa@sentry.io/111111"); _subject = new SentryTarget("https://aaaaaaaaaaaaaaaaaaaaaaaaaa@sentry.io/111111");
} }
private LogEventInfo GivenLogEvent(LogLevel level, Exception ex, string message) private LogEventInfo GivenLogEvent(LogLevel level, Exception ex, string message)
@ -34,44 +35,50 @@ namespace NzbDrone.Common.Test.InstrumentationTests
return LogEventInfo.Create(level, "SentryTest", ex, CultureInfo.InvariantCulture, message); return LogEventInfo.Create(level, "SentryTest", ex, CultureInfo.InvariantCulture, message);
} }
[Test, TestCaseSource("AllLevels")] [Test]
[TestCaseSource("AllLevels")]
public void log_without_error_is_not_sentry_event(LogLevel level) public void log_without_error_is_not_sentry_event(LogLevel level)
{ {
Subject.IsSentryMessage(GivenLogEvent(level, null, "test")).Should().BeFalse(); _subject.IsSentryMessage(GivenLogEvent(level, null, "test")).Should().BeFalse();
} }
[Test, TestCaseSource("SentryLevels")] [Test]
[TestCaseSource("SentryLevels")]
public void error_or_worse_with_exception_is_sentry_event(LogLevel level) public void error_or_worse_with_exception_is_sentry_event(LogLevel level)
{ {
Subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeTrue(); _subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeTrue();
} }
[Test, TestCaseSource("OtherLevels")] [Test]
[TestCaseSource("OtherLevels")]
public void less_than_error_with_exception_is_not_sentry_event(LogLevel level) public void less_than_error_with_exception_is_not_sentry_event(LogLevel level)
{ {
Subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeFalse(); _subject.IsSentryMessage(GivenLogEvent(level, new Exception(), "test")).Should().BeFalse();
} }
[Test, TestCaseSource("FilteredExceptions")] [Test]
[TestCaseSource("FilteredExceptions")]
public void should_filter_event_for_filtered_exception_types(Exception ex) public void should_filter_event_for_filtered_exception_types(Exception ex)
{ {
var log = GivenLogEvent(LogLevel.Error, ex, "test"); var log = GivenLogEvent(LogLevel.Error, ex, "test");
Subject.IsSentryMessage(log).Should().BeFalse(); _subject.IsSentryMessage(log).Should().BeFalse();
} }
[Test, TestCaseSource("FilteredExceptions")] [Test]
[TestCaseSource("FilteredExceptions")]
public void should_not_filter_event_for_filtered_exception_types_if_filtering_disabled(Exception ex) public void should_not_filter_event_for_filtered_exception_types_if_filtering_disabled(Exception ex)
{ {
Subject.FilterEvents = false; _subject.FilterEvents = false;
var log = GivenLogEvent(LogLevel.Error, ex, "test"); var log = GivenLogEvent(LogLevel.Error, ex, "test");
Subject.IsSentryMessage(log).Should().BeTrue(); _subject.IsSentryMessage(log).Should().BeTrue();
} }
[Test, TestCaseSource(typeof(SentryTarget), "FilteredExceptionMessages")] [Test]
[TestCaseSource(typeof(SentryTarget), "FilteredExceptionMessages")]
public void should_filter_event_for_filtered_exception_messages(string message) public void should_filter_event_for_filtered_exception_messages(string message)
{ {
var log = GivenLogEvent(LogLevel.Error, new Exception("aaaaaaa" + message + "bbbbbbb"), "test"); var log = GivenLogEvent(LogLevel.Error, new Exception("aaaaaaa" + message + "bbbbbbb"), "test");
Subject.IsSentryMessage(log).Should().BeFalse(); _subject.IsSentryMessage(log).Should().BeFalse();
} }
[TestCase("A message that isn't filtered")] [TestCase("A message that isn't filtered")]
@ -79,7 +86,7 @@ namespace NzbDrone.Common.Test.InstrumentationTests
public void should_not_filter_event_for_exception_messages_that_are_not_filtered(string message) public void should_not_filter_event_for_exception_messages_that_are_not_filtered(string message)
{ {
var log = GivenLogEvent(LogLevel.Error, new Exception(message), "test"); var log = GivenLogEvent(LogLevel.Error, new Exception(message), "test");
Subject.IsSentryMessage(log).Should().BeTrue(); _subject.IsSentryMessage(log).Should().BeTrue();
} }
} }
} }

View File

@ -1,7 +1,7 @@
using NUnit.Framework; using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common.Disk; using NzbDrone.Common.Disk;
using NzbDrone.Test.Common; using NzbDrone.Test.Common;
using FluentAssertions;
namespace NzbDrone.Common.Test namespace NzbDrone.Common.Test
{ {

View File

@ -110,6 +110,7 @@ namespace NzbDrone.Common.Test
_parent.IsParentPath(path).Should().BeTrue(); _parent.IsParentPath(path).Should().BeTrue();
} }
[TestCase(@"C:\Test\", @"C:\Test\mydir")] [TestCase(@"C:\Test\", @"C:\Test\mydir")]
[TestCase(@"C:\Test\", @"C:\Test\mydir\")] [TestCase(@"C:\Test\", @"C:\Test\mydir\")]
[TestCase(@"C:\Test", @"C:\Test\30.Rock.S01E01.Pilot.avi")] [TestCase(@"C:\Test", @"C:\Test\30.Rock.S01E01.Pilot.avi")]
@ -198,10 +199,9 @@ namespace NzbDrone.Common.Test
public void get_actual_casing_for_none_existing_file_return_partially_fixed_result() public void get_actual_casing_for_none_existing_file_return_partially_fixed_result()
{ {
WindowsOnly(); WindowsOnly();
"C:\\WINDOWS\\invalidfile.exe".GetActualCasing().Should().Be("C:\\Windows\\invalidfile.exe"); "C:\\WINDOWS\\invalidfile.exe".GetActualCasing().Should().Be("C:\\Windows\\invalidfile.exe");
} }
[Test] [Test]
public void get_actual_casing_for_none_existing_folder_return_partially_fixed_result() public void get_actual_casing_for_none_existing_folder_return_partially_fixed_result()
{ {
@ -218,7 +218,6 @@ namespace NzbDrone.Common.Test
path.ToLower().GetActualCasing().Should().Be(path); path.ToLower().GetActualCasing().Should().Be(path);
} }
[Test] [Test]
public void get_actual_casing_should_return_actual_casing_for_local_dir_in_windows() public void get_actual_casing_should_return_actual_casing_for_local_dir_in_windows()
{ {

View File

@ -18,7 +18,6 @@ namespace NzbDrone.Common.Test
[TestFixture] [TestFixture]
public class ProcessProviderFixture : TestBase<ProcessProvider> public class ProcessProviderFixture : TestBase<ProcessProvider>
{ {
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
@ -44,7 +43,6 @@ namespace NzbDrone.Common.Test
{ {
TestLogger.Warn(ex, "{0} when killing process", ex.Message); TestLogger.Warn(ex, "{0} when killing process", ex.Message);
} }
}); });
} }
@ -134,7 +132,6 @@ namespace NzbDrone.Common.Test
} }
} }
[Test] [Test]
[Platform(Exclude = "MacOsX")] [Platform(Exclude = "MacOsX")]
[Retry(3)] [Retry(3)]

View File

@ -29,4 +29,4 @@ namespace NzbDrone.Common.Test
handlers.Should().OnlyHaveUniqueItems(); handlers.Should().OnlyHaveUniqueItems();
} }
} }
} }

View File

@ -36,7 +36,6 @@ namespace NzbDrone.Common.Test
} }
} }
private void CleanupService() private void CleanupService()
{ {
if (Subject.ServiceExist(TEMP_SERVICE_NAME)) if (Subject.ServiceExist(TEMP_SERVICE_NAME))
@ -62,7 +61,6 @@ namespace NzbDrone.Common.Test
Subject.ServiceExist("random_service_name").Should().BeFalse(); Subject.ServiceExist("random_service_name").Should().BeFalse();
} }
[Test] [Test]
public void Service_should_be_installed_and_then_uninstalled() public void Service_should_be_installed_and_then_uninstalled()
{ {
@ -123,7 +121,6 @@ namespace NzbDrone.Common.Test
Subject.Start(ALWAYS_INSTALLED_SERVICE); Subject.Start(ALWAYS_INSTALLED_SERVICE);
Assert.Throws<InvalidOperationException>(() => Subject.Start(ALWAYS_INSTALLED_SERVICE)); Assert.Throws<InvalidOperationException>(() => Subject.Start(ALWAYS_INSTALLED_SERVICE));
ExceptionVerification.ExpectedWarns(1); ExceptionVerification.ExpectedWarns(1);
} }
@ -133,15 +130,14 @@ namespace NzbDrone.Common.Test
Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status
.Should().NotBe(ServiceControllerStatus.Running); .Should().NotBe(ServiceControllerStatus.Running);
Subject.Stop(ALWAYS_INSTALLED_SERVICE); Subject.Stop(ALWAYS_INSTALLED_SERVICE);
Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status Subject.GetService(ALWAYS_INSTALLED_SERVICE).Status
.Should().Be(ServiceControllerStatus.Stopped); .Should().Be(ServiceControllerStatus.Stopped);
ExceptionVerification.ExpectedWarns(1); ExceptionVerification.ExpectedWarns(1);
} }
private static bool IsAnAdministrator() private static bool IsAnAdministrator()
{ {
var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

View File

@ -19,7 +19,6 @@ namespace NzbDrone.Common.Test.TPLTests
} }
} }
[Test] [Test]
[Retry(3)] [Retry(3)]
public void should_hold_the_call_for_debounce_duration() public void should_hold_the_call_for_debounce_duration()
@ -33,11 +32,9 @@ namespace NzbDrone.Common.Test.TPLTests
counter.Count.Should().Be(0); counter.Count.Should().Be(0);
Thread.Sleep(100); Thread.Sleep(100);
counter.Count.Should().Be(1); counter.Count.Should().Be(1);
} }
[Test] [Test]
@ -53,7 +50,6 @@ namespace NzbDrone.Common.Test.TPLTests
counter.Count.Should().Be(0); counter.Count.Should().Be(0);
Thread.Sleep(200); Thread.Sleep(200);
debounceFunction.Execute(); debounceFunction.Execute();
@ -63,7 +59,6 @@ namespace NzbDrone.Common.Test.TPLTests
Thread.Sleep(200); Thread.Sleep(200);
counter.Count.Should().Be(2); counter.Count.Should().Be(2);
} }
[Test] [Test]
@ -126,4 +121,4 @@ namespace NzbDrone.Common.Test.TPLTests
counter.Count.Should().Be(1); counter.Count.Should().Be(1);
} }
} }
} }

View File

@ -1,11 +1,11 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics; using System.Diagnostics;
using FluentAssertions;
using NUnit.Framework; using NUnit.Framework;
using NzbDrone.Common.Cache; using NzbDrone.Common.Cache;
using NzbDrone.Common.TPL; using NzbDrone.Common.TPL;
using NzbDrone.Test.Common; using NzbDrone.Test.Common;
using FluentAssertions;
namespace NzbDrone.Common.Test.TPLTests namespace NzbDrone.Common.Test.TPLTests
{ {

View File

@ -73,7 +73,9 @@ namespace NzbDrone.Common
{ {
continue; // Ignore directories continue; // Ignore directories
} }
string entryFileName = zipEntry.Name; string entryFileName = zipEntry.Name;
// to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
// Optionally match entrynames against a selection list here to skip as desired. // Optionally match entrynames against a selection list here to skip as desired.
// The unpacked length is available in the zipEntry.Size property. // The unpacked length is available in the zipEntry.Size property.

View File

@ -21,7 +21,6 @@ namespace NzbDrone.Common.Cache
public CacheManager() public CacheManager()
{ {
_cache = new Cached<ICached>(); _cache = new Cached<ICached>();
} }
public void Clear() public void Clear()
@ -61,4 +60,4 @@ namespace NzbDrone.Common.Cache
return (ICachedDictionary<T>)_cache.Get("dict_" + host.FullName + "_" + name, () => new CachedDictionary<T>(fetchFunc, lifeTime)); return (ICachedDictionary<T>)_cache.Get("dict_" + host.FullName + "_" + name, () => new CachedDictionary<T>(fetchFunc, lifeTime));
} }
} }
} }

View File

@ -7,7 +7,6 @@ using NzbDrone.Common.Extensions;
namespace NzbDrone.Common.Cache namespace NzbDrone.Common.Cache
{ {
public class Cached<T> : ICached<T> public class Cached<T> : ICached<T>
{ {
private class CacheItem private class CacheItem
@ -144,6 +143,5 @@ namespace NzbDrone.Common.Cache
return collection.Remove(new KeyValuePair<string, CacheItem>(key, value)); return collection.Remove(new KeyValuePair<string, CacheItem>(key, value));
} }
} }
} }

View File

@ -5,7 +5,6 @@ using System.Diagnostics;
namespace NzbDrone.Common.Cache namespace NzbDrone.Common.Cache
{ {
public class CachedDictionary<TValue> : ICachedDictionary<TValue> public class CachedDictionary<TValue> : ICachedDictionary<TValue>
{ {
private readonly Func<IDictionary<string, TValue>> _fetchFunc; private readonly Func<IDictionary<string, TValue>> _fetchFunc;

View File

@ -19,4 +19,4 @@ namespace NzbDrone.Common.Cache
ICollection<T> Values { get; } ICollection<T> Values { get; }
} }
} }

View File

@ -24,12 +24,14 @@ namespace NzbDrone.Common.Composition
_container.Register<TService, TImplementation>(); _container.Register<TService, TImplementation>();
} }
public void Register<T>(T instance) where T : class public void Register<T>(T instance)
where T : class
{ {
_container.Register<T>(instance); _container.Register<T>(instance);
} }
public T Resolve<T>() where T : class public T Resolve<T>()
where T : class
{ {
return _container.Resolve<T>(); return _container.Resolve<T>();
} }
@ -44,7 +46,8 @@ namespace NzbDrone.Common.Composition
_container.Register(serviceType, implementationType); _container.Register(serviceType, implementationType);
} }
public void Register<TService>(Func<IContainer, TService> factory) where TService : class public void Register<TService>(Func<IContainer, TService> factory)
where TService : class
{ {
_container.Register((c, n) => factory(this)); _container.Register((c, n) => factory(this));
} }
@ -67,7 +70,8 @@ namespace NzbDrone.Common.Composition
}); });
} }
public IEnumerable<T> ResolveAll<T>() where T : class public IEnumerable<T> ResolveAll<T>()
where T : class
{ {
return _container.ResolveAll<T>(); return _container.ResolveAll<T>();
} }
@ -103,8 +107,7 @@ namespace NzbDrone.Common.Composition
.Where(implementation => .Where(implementation =>
contractType.IsAssignableFrom(implementation) && contractType.IsAssignableFrom(implementation) &&
!implementation.IsInterface && !implementation.IsInterface &&
!implementation.IsAbstract !implementation.IsAbstract);
);
} }
} }
} }

View File

@ -121,6 +121,7 @@ namespace NzbDrone.Common.Composition
{ {
return; return;
} }
if (implementations.Count == 1) if (implementations.Count == 1)
{ {
var impl = implementations.Single(); var impl = implementations.Single();

View File

@ -5,20 +5,24 @@ namespace NzbDrone.Common.Composition
{ {
public interface IContainer public interface IContainer
{ {
void Register<T>(T instance) where T : class; void Register<T>(T instance)
where T : class;
void Register<TService, TImplementation>() void Register<TService, TImplementation>()
where TImplementation : class, TService where TImplementation : class, TService
where TService : class; where TService : class;
T Resolve<T>() where T : class; T Resolve<T>()
where T : class;
object Resolve(Type type); object Resolve(Type type);
void Register(Type serviceType, Type implementationType); void Register(Type serviceType, Type implementationType);
void Register<TService>(Func<IContainer, TService> factory) where TService : class; void Register<TService>(Func<IContainer, TService> factory)
where TService : class;
void RegisterSingleton(Type service, Type implementation); void RegisterSingleton(Type service, Type implementation);
IEnumerable<T> ResolveAll<T>() where T : class; IEnumerable<T> ResolveAll<T>()
where T : class;
void RegisterAllAsSingleton(Type registrationType, IEnumerable<Type> implementationList); void RegisterAllAsSingleton(Type registrationType, IEnumerable<Type> implementationList);
bool IsTypeRegistered(Type type); bool IsTypeRegistered(Type type);
IEnumerable<Type> GetImplementations(Type contractType); IEnumerable<Type> GetImplementations(Type contractType);
} }
} }

View File

@ -28,4 +28,4 @@ namespace NzbDrone.Common.Crypto
} }
} }
} }
} }

View File

@ -10,19 +10,23 @@ namespace NzbDrone.Common.Disk
{ {
} }
public DestinationAlreadyExistsException(string message) : base(message) public DestinationAlreadyExistsException(string message)
: base(message)
{ {
} }
public DestinationAlreadyExistsException(string message, int hresult) : base(message, hresult) public DestinationAlreadyExistsException(string message, int hresult)
: base(message, hresult)
{ {
} }
public DestinationAlreadyExistsException(string message, Exception innerException) : base(message, innerException) public DestinationAlreadyExistsException(string message, Exception innerException)
: base(message, innerException)
{ {
} }
protected DestinationAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) protected DestinationAlreadyExistsException(SerializationInfo info, StreamingContext context)
: base(info, context)
{ {
} }
} }

View File

@ -117,6 +117,7 @@ namespace NzbDrone.Common.Disk
{ {
return File.Exists(path) && path == path.GetActualCasing(); return File.Exists(path) && path == path.GetActualCasing();
} }
default: default:
{ {
return File.Exists(path); return File.Exists(path);
@ -367,7 +368,7 @@ namespace NzbDrone.Common.Disk
if (attributes.HasFlag(FileAttributes.ReadOnly)) if (attributes.HasFlag(FileAttributes.ReadOnly))
{ {
var newAttributes = attributes & ~(FileAttributes.ReadOnly); var newAttributes = attributes & ~FileAttributes.ReadOnly;
File.SetAttributes(path, newAttributes); File.SetAttributes(path, newAttributes);
} }
} }

View File

@ -14,7 +14,7 @@ namespace NzbDrone.Common.Disk
TransferMode TransferFile(string sourcePath, string targetPath, TransferMode mode, bool overwrite = false); TransferMode TransferFile(string sourcePath, string targetPath, TransferMode mode, bool overwrite = false);
int MirrorFolder(string sourcePath, string targetPath); int MirrorFolder(string sourcePath, string targetPath);
} }
public class DiskTransferService : IDiskTransferService public class DiskTransferService : IDiskTransferService
{ {
private readonly IDiskProvider _diskProvider; private readonly IDiskProvider _diskProvider;
@ -40,7 +40,7 @@ namespace NzbDrone.Common.Disk
return realParentPath + partialChildPath; return realParentPath + partialChildPath;
} }
public TransferMode TransferFolder(string sourcePath, string targetPath, TransferMode mode) public TransferMode TransferFolder(string sourcePath, string targetPath, TransferMode mode)
{ {
Ensure.That(sourcePath, () => sourcePath).IsValidPath(); Ensure.That(sourcePath, () => sourcePath).IsValidPath();
@ -101,14 +101,20 @@ namespace NzbDrone.Common.Disk
foreach (var subDir in _diskProvider.GetDirectoryInfos(sourcePath)) foreach (var subDir in _diskProvider.GetDirectoryInfos(sourcePath))
{ {
if (ShouldIgnore(subDir)) continue; if (ShouldIgnore(subDir))
{
continue;
}
result &= TransferFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name), mode); result &= TransferFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name), mode);
} }
foreach (var sourceFile in _diskProvider.GetFileInfos(sourcePath)) foreach (var sourceFile in _diskProvider.GetFileInfos(sourcePath))
{ {
if (ShouldIgnore(sourceFile)) continue; if (ShouldIgnore(sourceFile))
{
continue;
}
var destFile = Path.Combine(targetPath, sourceFile.Name); var destFile = Path.Combine(targetPath, sourceFile.Name);
@ -152,14 +158,20 @@ namespace NzbDrone.Common.Disk
foreach (var subDir in targetFolders.Where(v => !sourceFolders.Any(d => d.Name == v.Name))) foreach (var subDir in targetFolders.Where(v => !sourceFolders.Any(d => d.Name == v.Name)))
{ {
if (ShouldIgnore(subDir)) continue; if (ShouldIgnore(subDir))
{
continue;
}
_diskProvider.DeleteFolder(subDir.FullName, true); _diskProvider.DeleteFolder(subDir.FullName, true);
} }
foreach (var subDir in sourceFolders) foreach (var subDir in sourceFolders)
{ {
if (ShouldIgnore(subDir)) continue; if (ShouldIgnore(subDir))
{
continue;
}
filesCopied += MirrorFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name)); filesCopied += MirrorFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name));
} }
@ -169,14 +181,20 @@ namespace NzbDrone.Common.Disk
foreach (var targetFile in targetFiles.Where(v => !sourceFiles.Any(d => d.Name == v.Name))) foreach (var targetFile in targetFiles.Where(v => !sourceFiles.Any(d => d.Name == v.Name)))
{ {
if (ShouldIgnore(targetFile)) continue; if (ShouldIgnore(targetFile))
{
continue;
}
_diskProvider.DeleteFile(targetFile.FullName); _diskProvider.DeleteFile(targetFile.FullName);
} }
foreach (var sourceFile in sourceFiles) foreach (var sourceFile in sourceFiles)
{ {
if (ShouldIgnore(sourceFile)) continue; if (ShouldIgnore(sourceFile))
{
continue;
}
var targetFile = Path.Combine(targetPath, sourceFile.Name); var targetFile = Path.Combine(targetPath, sourceFile.Name);
@ -305,6 +323,7 @@ namespace NzbDrone.Common.Disk
{ {
return TransferMode.HardLink; return TransferMode.HardLink;
} }
if (!mode.HasFlag(TransferMode.Copy)) if (!mode.HasFlag(TransferMode.Copy))
{ {
throw new IOException("Hardlinking from '" + sourcePath + "' to '" + targetPath + "' failed."); throw new IOException("Hardlinking from '" + sourcePath + "' to '" + targetPath + "' failed.");
@ -315,14 +334,14 @@ namespace NzbDrone.Common.Disk
var sourceMount = _diskProvider.GetMount(sourcePath); var sourceMount = _diskProvider.GetMount(sourcePath);
var targetMount = _diskProvider.GetMount(targetPath); var targetMount = _diskProvider.GetMount(targetPath);
var isSameMount = (sourceMount != null && targetMount != null && sourceMount.RootDirectory == targetMount.RootDirectory); var isSameMount = sourceMount != null && targetMount != null && sourceMount.RootDirectory == targetMount.RootDirectory;
var sourceDriveFormat = sourceMount?.DriveFormat ?? string.Empty; var sourceDriveFormat = sourceMount?.DriveFormat ?? string.Empty;
var targetDriveFormat = targetMount?.DriveFormat ?? string.Empty; var targetDriveFormat = targetMount?.DriveFormat ?? string.Empty;
var isCifs = targetDriveFormat == "cifs"; var isCifs = targetDriveFormat == "cifs";
var isBtrfs = sourceDriveFormat == "btrfs" && targetDriveFormat == "btrfs"; var isBtrfs = sourceDriveFormat == "btrfs" && targetDriveFormat == "btrfs";
if (mode.HasFlag(TransferMode.Copy)) if (mode.HasFlag(TransferMode.Copy))
{ {
if (isBtrfs) if (isBtrfs)
@ -363,7 +382,7 @@ namespace NzbDrone.Common.Disk
_diskProvider.DeleteFile(sourcePath); _diskProvider.DeleteFile(sourcePath);
return TransferMode.Move; return TransferMode.Move;
} }
TryMoveFileVerified(sourcePath, targetPath, originalSize); TryMoveFileVerified(sourcePath, targetPath, originalSize);
return TransferMode.Move; return TransferMode.Move;
} }

View File

@ -6,7 +6,8 @@ namespace NzbDrone.Common.Disk
{ {
public string Filename { get; set; } public string Filename { get; set; }
public FileAlreadyExistsException(string message, string filename) : base(message) public FileAlreadyExistsException(string message, string filename)
: base(message)
{ {
Filename = filename; Filename = filename;
} }

View File

@ -125,7 +125,6 @@ namespace NzbDrone.Common.Disk
result.Files = GetFiles(path); result.Files = GetFiles(path);
} }
} }
catch (DirectoryNotFoundException) catch (DirectoryNotFoundException)
{ {
return new FileSystemResult { Parent = GetParent(path) }; return new FileSystemResult { Parent = GetParent(path) };

View File

@ -54,7 +54,11 @@ namespace NzbDrone.Common.Disk
{ {
get get
{ {
if (MAX_PATH == 0) DetectLongPathLimits(); if (MAX_PATH == 0)
{
DetectLongPathLimits();
}
return MAX_PATH; return MAX_PATH;
} }
} }
@ -63,7 +67,11 @@ namespace NzbDrone.Common.Disk
{ {
get get
{ {
if (MAX_NAME == 0) DetectLongPathLimits(); if (MAX_NAME == 0)
{
DetectLongPathLimits();
}
return MAX_NAME; return MAX_NAME;
} }
} }

View File

@ -4,11 +4,13 @@ namespace NzbDrone.Common.Disk
{ {
public class NotParentException : NzbDroneException public class NotParentException : NzbDroneException
{ {
public NotParentException(string message, params object[] args) : base(message, args) public NotParentException(string message, params object[] args)
: base(message, args)
{ {
} }
public NotParentException(string message) : base(message) public NotParentException(string message)
: base(message)
{ {
} }
} }

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using NzbDrone.Common.Extensions; using NzbDrone.Common.Extensions;
@ -44,22 +44,36 @@ namespace NzbDrone.Common.Disk
{ {
return OsPathKind.Unix; return OsPathKind.Unix;
} }
if (HasWindowsDriveLetter(path) || path.Contains('\\')) if (HasWindowsDriveLetter(path) || path.Contains('\\'))
{ {
return OsPathKind.Windows; return OsPathKind.Windows;
} }
if (path.Contains('/')) if (path.Contains('/'))
{ {
return OsPathKind.Unix; return OsPathKind.Unix;
} }
return OsPathKind.Unknown; return OsPathKind.Unknown;
} }
private static bool HasWindowsDriveLetter(string path) private static bool HasWindowsDriveLetter(string path)
{ {
if (path.Length < 2) return false; if (path.Length < 2)
if (!char.IsLetter(path[0]) || path[1] != ':') return false; {
if (path.Length > 2 && path[2] != '\\' && path[2] != '/') return false; return false;
}
if (!char.IsLetter(path[0]) || path[1] != ':')
{
return false;
}
if (path.Length > 2 && path[2] != '\\' && path[2] != '/')
{
return false;
}
return true; return true;
} }
@ -76,6 +90,7 @@ namespace NzbDrone.Common.Disk
{ {
path = path.Replace("//", "/"); path = path.Replace("//", "/");
} }
return path; return path;
} }
@ -98,11 +113,12 @@ namespace NzbDrone.Common.Disk
{ {
return _path.StartsWith(@"\\") || HasWindowsDriveLetter(_path); return _path.StartsWith(@"\\") || HasWindowsDriveLetter(_path);
} }
if (IsUnixPath) if (IsUnixPath)
{ {
return _path.StartsWith("/"); return _path.StartsWith("/");
} }
return false; return false;
} }
} }
@ -117,7 +133,7 @@ namespace NzbDrone.Common.Disk
{ {
return new OsPath(null); return new OsPath(null);
} }
return new OsPath(_path.Substring(0, index), _kind).AsDirectory(); return new OsPath(_path.Substring(0, index), _kind).AsDirectory();
} }
} }
@ -141,7 +157,7 @@ namespace NzbDrone.Common.Disk
return path; return path;
} }
return _path.Substring(index).Trim('\\', '/'); return _path.Substring(index).Trim('\\', '/');
} }
} }
@ -196,10 +212,12 @@ namespace NzbDrone.Common.Disk
{ {
return Equals((OsPath)obj); return Equals((OsPath)obj);
} }
if (obj is string) if (obj is string)
{ {
return Equals(new OsPath(obj as string)); return Equals(new OsPath(obj as string));
} }
return false; return false;
} }
@ -217,6 +235,7 @@ namespace NzbDrone.Common.Disk
case OsPathKind.Unix: case OsPathKind.Unix:
return new OsPath(_path.TrimEnd('/') + "/", _kind); return new OsPath(_path.TrimEnd('/') + "/", _kind);
} }
return this; return this;
} }
@ -250,7 +269,10 @@ namespace NzbDrone.Common.Disk
public bool Equals(OsPath other) public bool Equals(OsPath other)
{ {
if (ReferenceEquals(other, null)) return false; if (ReferenceEquals(other, null))
{
return false;
}
if (_path == other._path) if (_path == other._path)
{ {
@ -264,19 +286,26 @@ namespace NzbDrone.Common.Disk
{ {
return string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase); return string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase);
} }
return string.Equals(left, right, StringComparison.InvariantCulture); return string.Equals(left, right, StringComparison.InvariantCulture);
} }
public static bool operator ==(OsPath left, OsPath right) public static bool operator ==(OsPath left, OsPath right)
{ {
if (ReferenceEquals(left, null)) return ReferenceEquals(right, null); if (ReferenceEquals(left, null))
{
return ReferenceEquals(right, null);
}
return left.Equals(right); return left.Equals(right);
} }
public static bool operator !=(OsPath left, OsPath right) public static bool operator !=(OsPath left, OsPath right)
{ {
if (ReferenceEquals(left, null)) return !ReferenceEquals(right, null); if (ReferenceEquals(left, null))
{
return !ReferenceEquals(right, null);
}
return !left.Equals(right); return !left.Equals(right);
} }
@ -302,10 +331,12 @@ namespace NzbDrone.Common.Disk
{ {
return new OsPath(string.Join("\\", left._path.TrimEnd('\\'), right._path.TrimStart('\\')), OsPathKind.Windows); return new OsPath(string.Join("\\", left._path.TrimEnd('\\'), right._path.TrimStart('\\')), OsPathKind.Windows);
} }
if (left.Kind == OsPathKind.Unix || right.Kind == OsPathKind.Unix) if (left.Kind == OsPathKind.Unix || right.Kind == OsPathKind.Unix)
{ {
return new OsPath(string.Join("/", left._path.TrimEnd('/'), right._path), OsPathKind.Unix); return new OsPath(string.Join("/", left._path.TrimEnd('/'), right._path), OsPathKind.Unix);
} }
return new OsPath(string.Join("/", left._path, right._path), OsPathKind.Unknown); return new OsPath(string.Join("/", left._path, right._path), OsPathKind.Unknown);
} }
@ -361,6 +392,7 @@ namespace NzbDrone.Common.Disk
{ {
return new OsPath(string.Join("\\", newFragments), OsPathKind.Unknown); return new OsPath(string.Join("\\", newFragments), OsPathKind.Unknown);
} }
return new OsPath(string.Join("/", newFragments), OsPathKind.Unknown); return new OsPath(string.Join("/", newFragments), OsPathKind.Unknown);
} }
} }

View File

@ -20,4 +20,4 @@ namespace NzbDrone.Common.EnsureThat
return new TypeParam(name, value.GetType()); return new TypeParam(name, value.GetType());
} }
} }
} }

View File

@ -9,7 +9,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<bool> IsTrue(this Param<bool> param) public static Param<bool> IsTrue(this Param<bool> param)
{ {
if (!param.Value) if (!param.Value)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotTrue); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotTrue);
}
return param; return param;
} }
@ -18,9 +20,11 @@ namespace NzbDrone.Common.EnsureThat
public static Param<bool> IsFalse(this Param<bool> param) public static Param<bool> IsFalse(this Param<bool> param)
{ {
if (param.Value) if (param.Value)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotFalse); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotFalse);
}
return param; return param;
} }
} }
} }

View File

@ -10,10 +10,13 @@ namespace NzbDrone.Common.EnsureThat
public static class EnsureCollectionExtensions public static class EnsureCollectionExtensions
{ {
[DebuggerStepThrough] [DebuggerStepThrough]
public static Param<T> HasItems<T>(this Param<T> param) where T : class, ICollection public static Param<T> HasItems<T>(this Param<T> param)
where T : class, ICollection
{ {
if (param.Value == null || param.Value.Count < 1) if (param.Value == null || param.Value.Count < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param; return param;
} }
@ -22,7 +25,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<Collection<T>> HasItems<T>(this Param<Collection<T>> param) public static Param<Collection<T>> HasItems<T>(this Param<Collection<T>> param)
{ {
if (param.Value == null || param.Value.Count < 1) if (param.Value == null || param.Value.Count < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param; return param;
} }
@ -31,7 +36,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<IEnumerable<T>> HasItems<T>(this Param<IEnumerable<T>> param) public static Param<IEnumerable<T>> HasItems<T>(this Param<IEnumerable<T>> param)
{ {
if (param.Value == null || !param.Value.Any()) if (param.Value == null || !param.Value.Any())
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param; return param;
} }
@ -40,7 +47,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<T[]> HasItems<T>(this Param<T[]> param) public static Param<T[]> HasItems<T>(this Param<T[]> param)
{ {
if (param.Value == null || param.Value.Length < 1) if (param.Value == null || param.Value.Length < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param; return param;
} }
@ -49,19 +58,22 @@ namespace NzbDrone.Common.EnsureThat
public static Param<List<T>> HasItems<T>(this Param<List<T>> param) public static Param<List<T>> HasItems<T>(this Param<List<T>> param)
{ {
if (param.Value == null || param.Value.Count < 1) if (param.Value == null || param.Value.Count < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param; return param;
} }
[DebuggerStepThrough] [DebuggerStepThrough]
public static Param<IDictionary<TKey, TValue>> HasItems<TKey, TValue>(this Param<IDictionary<TKey, TValue>> param) public static Param<IDictionary<TKey, TValue>> HasItems<TKey, TValue>(this Param<IDictionary<TKey, TValue>> param)
{ {
if (param.Value == null || param.Value.Count < 1) if (param.Value == null || param.Value.Count < 1)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyCollection);
}
return param; return param;
} }
} }
} }

View File

@ -7,14 +7,15 @@ namespace NzbDrone.Common.EnsureThat
{ {
public static class EnsureDateTimeExtensions public static class EnsureDateTimeExtensions
{ {
private static readonly DateTime _minTime = new DateTime(1960, 1, 1); private static readonly DateTime _minTime = new DateTime(1960, 1, 1);
[DebuggerStepThrough] [DebuggerStepThrough]
public static Param<DateTime> IsLt(this Param<DateTime> param, DateTime limit) public static Param<DateTime> IsLt(this Param<DateTime> param, DateTime limit)
{ {
if (param.Value >= limit) if (param.Value >= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -23,7 +24,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsLte(this Param<DateTime> param, DateTime limit) public static Param<DateTime> IsLte(this Param<DateTime> param, DateTime limit)
{ {
if (!(param.Value <= limit)) if (!(param.Value <= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -32,7 +35,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsGt(this Param<DateTime> param, DateTime limit) public static Param<DateTime> IsGt(this Param<DateTime> param, DateTime limit)
{ {
if (param.Value <= limit) if (param.Value <= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -41,7 +46,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsGte(this Param<DateTime> param, DateTime limit) public static Param<DateTime> IsGte(this Param<DateTime> param, DateTime limit)
{ {
if (!(param.Value >= limit)) if (!(param.Value >= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -50,10 +57,14 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsInRange(this Param<DateTime> param, DateTime min, DateTime max) public static Param<DateTime> IsInRange(this Param<DateTime> param, DateTime min, DateTime max)
{ {
if (param.Value < min) if (param.Value < min)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min));
}
if (param.Value > max) if (param.Value > max)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max));
}
return param; return param;
} }
@ -62,15 +73,17 @@ namespace NzbDrone.Common.EnsureThat
public static Param<DateTime> IsUtc(this Param<DateTime> param) public static Param<DateTime> IsUtc(this Param<DateTime> param)
{ {
if (param.Value.Kind != DateTimeKind.Utc) if (param.Value.Kind != DateTimeKind.Utc)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, "Excepted time to be in UTC but was [{0}]".Inject(param.Value.Kind)); throw ExceptionFactory.CreateForParamValidation(param.Name, "Excepted time to be in UTC but was [{0}]".Inject(param.Value.Kind));
}
return param; return param;
} }
[DebuggerStepThrough] [DebuggerStepThrough]
public static Param<DateTime> IsValid(this Param<DateTime> param) public static Param<DateTime> IsValid(this Param<DateTime> param)
{ {
return IsGt(param, _minTime); return IsGt(param, _minTime);
} }
} }
} }

View File

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsLt(this Param<decimal> param, decimal limit) public static Param<decimal> IsLt(this Param<decimal> param, decimal limit)
{ {
if (param.Value >= limit) if (param.Value >= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsLte(this Param<decimal> param, decimal limit) public static Param<decimal> IsLte(this Param<decimal> param, decimal limit)
{ {
if (!(param.Value <= limit)) if (!(param.Value <= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsGt(this Param<decimal> param, decimal limit) public static Param<decimal> IsGt(this Param<decimal> param, decimal limit)
{ {
if (param.Value <= limit) if (param.Value <= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsGte(this Param<decimal> param, decimal limit) public static Param<decimal> IsGte(this Param<decimal> param, decimal limit)
{ {
if (!(param.Value >= limit)) if (!(param.Value >= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -46,12 +54,16 @@ namespace NzbDrone.Common.EnsureThat
public static Param<decimal> IsInRange(this Param<decimal> param, decimal min, decimal max) public static Param<decimal> IsInRange(this Param<decimal> param, decimal min, decimal max)
{ {
if (param.Value < min) if (param.Value < min)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min));
}
if (param.Value > max) if (param.Value > max)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max));
}
return param; return param;
} }
} }
} }

View File

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsLt(this Param<double> param, double limit) public static Param<double> IsLt(this Param<double> param, double limit)
{ {
if (param.Value >= limit) if (param.Value >= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsLte(this Param<double> param, double limit) public static Param<double> IsLte(this Param<double> param, double limit)
{ {
if (!(param.Value <= limit)) if (!(param.Value <= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsGt(this Param<double> param, double limit) public static Param<double> IsGt(this Param<double> param, double limit)
{ {
if (param.Value <= limit) if (param.Value <= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsGte(this Param<double> param, double limit) public static Param<double> IsGte(this Param<double> param, double limit)
{ {
if (!(param.Value >= limit)) if (!(param.Value >= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -46,12 +54,16 @@ namespace NzbDrone.Common.EnsureThat
public static Param<double> IsInRange(this Param<double> param, double min, double max) public static Param<double> IsInRange(this Param<double> param, double min, double max)
{ {
if (param.Value < min) if (param.Value < min)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min));
}
if (param.Value > max) if (param.Value > max)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max));
}
return param; return param;
} }
} }
} }

View File

@ -10,9 +10,11 @@ namespace NzbDrone.Common.EnsureThat
public static Param<Guid> IsNotEmpty(this Param<Guid> param) public static Param<Guid> IsNotEmpty(this Param<Guid> param)
{ {
if (Guid.Empty.Equals(param.Value)) if (Guid.Empty.Equals(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyGuid); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsEmptyGuid);
}
return param; return param;
} }
} }
} }

View File

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsLessThan(this Param<int> param, int limit) public static Param<int> IsLessThan(this Param<int> param, int limit)
{ {
if (param.Value >= limit) if (param.Value >= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsLessThanOrEqualTo(this Param<int> param, int limit) public static Param<int> IsLessThanOrEqualTo(this Param<int> param, int limit)
{ {
if (!(param.Value <= limit)) if (!(param.Value <= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsGreaterThan(this Param<int> param, int limit) public static Param<int> IsGreaterThan(this Param<int> param, int limit)
{ {
if (param.Value <= limit) if (param.Value <= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsGreaterThanZero(this Param<int> param) public static Param<int> IsGreaterThanZero(this Param<int> param)
{ {
if (param.Value <= 0) if (param.Value <= 0)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, 0)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, 0));
}
return param; return param;
} }
@ -46,7 +54,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsGreaterOrEqualTo(this Param<int> param, int limit) public static Param<int> IsGreaterOrEqualTo(this Param<int> param, int limit)
{ {
if (!(param.Value >= limit)) if (!(param.Value >= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -55,12 +65,16 @@ namespace NzbDrone.Common.EnsureThat
public static Param<int> IsInRange(this Param<int> param, int min, int max) public static Param<int> IsInRange(this Param<int> param, int min, int max)
{ {
if (param.Value < min) if (param.Value < min)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min));
}
if (param.Value > max) if (param.Value > max)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max));
}
return param; return param;
} }
} }
} }

View File

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsLt(this Param<long> param, long limit) public static Param<long> IsLt(this Param<long> param, long limit)
{ {
if (param.Value >= limit) if (param.Value >= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsLte(this Param<long> param, long limit) public static Param<long> IsLte(this Param<long> param, long limit)
{ {
if (!(param.Value <= limit)) if (!(param.Value <= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsGt(this Param<long> param, long limit) public static Param<long> IsGt(this Param<long> param, long limit)
{ {
if (param.Value <= limit) if (param.Value <= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsGte(this Param<long> param, long limit) public static Param<long> IsGte(this Param<long> param, long limit)
{ {
if (!(param.Value >= limit)) if (!(param.Value >= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -46,12 +54,16 @@ namespace NzbDrone.Common.EnsureThat
public static Param<long> IsInRange(this Param<long> param, long min, long max) public static Param<long> IsInRange(this Param<long> param, long min, long max)
{ {
if (param.Value < min) if (param.Value < min)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min));
}
if (param.Value > max) if (param.Value > max)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max));
}
return param; return param;
} }
} }
} }

View File

@ -6,12 +6,15 @@ namespace NzbDrone.Common.EnsureThat
public static class EnsureNullableValueTypeExtensions public static class EnsureNullableValueTypeExtensions
{ {
[DebuggerStepThrough] [DebuggerStepThrough]
public static Param<T?> IsNotNull<T>(this Param<T?> param) where T : struct public static Param<T?> IsNotNull<T>(this Param<T?> param)
where T : struct
{ {
if (param.Value == null || !param.Value.HasValue) if (param.Value == null || !param.Value.HasValue)
{
throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull); throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull);
}
return param; return param;
} }
} }
} }

View File

@ -6,12 +6,15 @@ namespace NzbDrone.Common.EnsureThat
public static class EnsureObjectExtensions public static class EnsureObjectExtensions
{ {
[DebuggerStepThrough] [DebuggerStepThrough]
public static Param<T> IsNotNull<T>(this Param<T> param) where T : class public static Param<T> IsNotNull<T>(this Param<T> param)
where T : class
{ {
if (param.Value == null) if (param.Value == null)
{
throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull); throw ExceptionFactory.CreateForParamNullValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNull);
}
return param; return param;
} }
} }
} }

View File

@ -10,7 +10,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsLt(this Param<short> param, short limit) public static Param<short> IsLt(this Param<short> param, short limit)
{ {
if (param.Value >= limit) if (param.Value >= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -19,7 +21,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsLte(this Param<short> param, short limit) public static Param<short> IsLte(this Param<short> param, short limit)
{ {
if (!(param.Value <= limit)) if (!(param.Value <= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -28,7 +32,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsGt(this Param<short> param, short limit) public static Param<short> IsGt(this Param<short> param, short limit)
{ {
if (param.Value <= limit) if (param.Value <= limit)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param.Value, limit));
}
return param; return param;
} }
@ -37,7 +43,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsGte(this Param<short> param, short limit) public static Param<short> IsGte(this Param<short> param, short limit)
{ {
if (!(param.Value >= limit)) if (!(param.Value >= limit))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param.Value, limit));
}
return param; return param;
} }
@ -46,12 +54,16 @@ namespace NzbDrone.Common.EnsureThat
public static Param<short> IsInRange(this Param<short> param, short min, short max) public static Param<short> IsInRange(this Param<short> param, short min, short max)
{ {
if (param.Value < min) if (param.Value < min)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param.Value, min));
}
if (param.Value > max) if (param.Value > max)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param.Value, max));
}
return param; return param;
} }
} }
} }

View File

@ -13,7 +13,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsNotNullOrWhiteSpace(this Param<string> param) public static Param<string> IsNotNullOrWhiteSpace(this Param<string> param)
{ {
if (string.IsNullOrWhiteSpace(param.Value)) if (string.IsNullOrWhiteSpace(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace);
}
return param; return param;
} }
@ -22,7 +24,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsNotNullOrEmpty(this Param<string> param) public static Param<string> IsNotNullOrEmpty(this Param<string> param)
{ {
if (string.IsNullOrEmpty(param.Value)) if (string.IsNullOrEmpty(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty);
}
return param; return param;
} }
@ -31,15 +35,21 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> HasLengthBetween(this Param<string> param, int minLength, int maxLength) public static Param<string> HasLengthBetween(this Param<string> param, int minLength, int maxLength)
{ {
if (string.IsNullOrEmpty(param.Value)) if (string.IsNullOrEmpty(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty);
}
var length = param.Value.Length; var length = param.Value.Length;
if (length < minLength) if (length < minLength)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToShort.Inject(minLength, maxLength, length)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToShort.Inject(minLength, maxLength, length));
}
if (length > maxLength) if (length > maxLength)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLong.Inject(minLength, maxLength, length)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotInRange_ToLong.Inject(minLength, maxLength, length));
}
return param; return param;
} }
@ -48,12 +58,16 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsLongerThan(this Param<string> param, int minLength) public static Param<string> IsLongerThan(this Param<string> param, int minLength)
{ {
if (string.IsNullOrEmpty(param.Value)) if (string.IsNullOrEmpty(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrEmpty);
}
var length = param.Value.Length; var length = param.Value.Length;
if (length < minLength) if (length < minLength)
{
throw ExceptionFactory.CreateForParamValidation(param.Name, "The string is not long enough. Must be at least '{0}' but was '{1}' characters long.".Inject(minLength, length)); throw ExceptionFactory.CreateForParamValidation(param.Name, "The string is not long enough. Must be at least '{0}' but was '{1}' characters long.".Inject(minLength, length));
}
return param; return param;
} }
@ -71,6 +85,7 @@ namespace NzbDrone.Common.EnsureThat
{ {
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_NoMatch.Inject(param.Value, match)); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_NoMatch.Inject(param.Value, match));
} }
return param; return param;
} }
@ -78,7 +93,9 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsRelativePath(this Param<string> param) public static Param<string> IsRelativePath(this Param<string> param)
{ {
if (string.IsNullOrWhiteSpace(param.Value)) if (string.IsNullOrWhiteSpace(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace);
}
if (!param.Value.EndsWith("\\")) if (!param.Value.EndsWith("\\"))
{ {
@ -97,9 +114,14 @@ namespace NzbDrone.Common.EnsureThat
public static Param<string> IsValidPath(this Param<string> param) public static Param<string> IsValidPath(this Param<string> param)
{ {
if (string.IsNullOrWhiteSpace(param.Value)) if (string.IsNullOrWhiteSpace(param.Value))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace); throw ExceptionFactory.CreateForParamValidation(param.Name, ExceptionMessages.EnsureExtensions_IsNotNullOrWhiteSpace);
}
if (param.Value.IsPathValid()) return param; if (param.Value.IsPathValid())
{
return param;
}
if (OsInfo.IsWindows) if (OsInfo.IsWindows)
{ {

View File

@ -9,7 +9,7 @@ namespace NzbDrone.Common.EnsureThat
{ {
private static class Types private static class Types
{ {
internal static readonly Type IntType = typeof (int); internal static readonly Type IntType = typeof(int);
internal static readonly Type ShortType = typeof(short); internal static readonly Type ShortType = typeof(short);
@ -78,10 +78,12 @@ namespace NzbDrone.Common.EnsureThat
public static TypeParam IsOfType(this TypeParam param, Type type) public static TypeParam IsOfType(this TypeParam param, Type type)
{ {
if (!param.Type.Equals(type)) if (!param.Type.Equals(type))
{
throw ExceptionFactory.CreateForParamValidation(param.Name, throw ExceptionFactory.CreateForParamValidation(param.Name,
ExceptionMessages.EnsureExtensions_IsNotOfType.Inject(param.Type.FullName)); ExceptionMessages.EnsureExtensions_IsNotOfType.Inject(param.Type.FullName));
}
return param; return param;
} }
} }
} }

View File

@ -19,4 +19,4 @@ namespace NzbDrone.Common.EnsureThat
return new ArgumentNullException(paramName, message); return new ArgumentNullException(paramName, message);
} }
} }
} }

View File

@ -9,7 +9,9 @@ namespace NzbDrone.Common.EnsureThat
var path = ""; var path = "";
if (e.Expression is MemberExpression parent) if (e.Expression is MemberExpression parent)
{
path = parent.ToPath() + "."; path = parent.ToPath() + ".";
}
return path + e.Member.Name; return path + e.Member.Name;
} }
@ -22,17 +24,23 @@ namespace NzbDrone.Common.EnsureThat
private static MemberExpression GetRightMostMember(Expression e) private static MemberExpression GetRightMostMember(Expression e)
{ {
if (e is LambdaExpression) if (e is LambdaExpression)
{
return GetRightMostMember(((LambdaExpression)e).Body); return GetRightMostMember(((LambdaExpression)e).Body);
}
if (e is MemberExpression) if (e is MemberExpression)
{
return (MemberExpression)e; return (MemberExpression)e;
}
if (e is MethodCallExpression) if (e is MethodCallExpression)
{ {
var callExpression = (MethodCallExpression)e; var callExpression = (MethodCallExpression)e;
if (callExpression.Object is MethodCallExpression || callExpression.Object is MemberExpression) if (callExpression.Object is MethodCallExpression || callExpression.Object is MemberExpression)
{
return GetRightMostMember(callExpression.Object); return GetRightMostMember(callExpression.Object);
}
var member = callExpression.Arguments.Count > 0 ? callExpression.Arguments[0] : callExpression.Object; var member = callExpression.Arguments.Count > 0 ? callExpression.Arguments[0] : callExpression.Object;
return GetRightMostMember(member); return GetRightMostMember(member);
@ -47,4 +55,4 @@ namespace NzbDrone.Common.EnsureThat
return null; return null;
} }
} }
} }

View File

@ -16,9 +16,10 @@ namespace NzbDrone.Common.EnsureThat
{ {
public readonly T Value; public readonly T Value;
internal Param(string name, T value) : base(name) internal Param(string name, T value)
: base(name)
{ {
Value = value; Value = value;
} }
} }
} }

View File

@ -12,4 +12,4 @@ namespace NzbDrone.Common.EnsureThat
Type = type; Type = type;
} }
} }
} }

View File

@ -95,9 +95,20 @@ namespace NzbDrone.Common.EnvironmentInfo
RemovePidFile(); RemovePidFile();
} }
if (_appFolderInfo.LegacyAppDataFolder.IsNullOrWhiteSpace()) return; if (_appFolderInfo.LegacyAppDataFolder.IsNullOrWhiteSpace())
if (_diskProvider.FileExists(_appFolderInfo.GetDatabase()) || _diskProvider.FileExists(_appFolderInfo.GetConfigPath())) return; {
if (!_diskProvider.FolderExists(_appFolderInfo.LegacyAppDataFolder)) return; return;
}
if (_diskProvider.FileExists(_appFolderInfo.GetDatabase()) || _diskProvider.FileExists(_appFolderInfo.GetConfigPath()))
{
return;
}
if (!_diskProvider.FolderExists(_appFolderInfo.LegacyAppDataFolder))
{
return;
}
// Delete the bin folder on Windows // Delete the bin folder on Windows
var binFolder = Path.Combine(_appFolderInfo.LegacyAppDataFolder, "bin"); var binFolder = Path.Combine(_appFolderInfo.LegacyAppDataFolder, "bin");

View File

@ -1,6 +1,5 @@
namespace NzbDrone.Common.EnvironmentInfo namespace NzbDrone.Common.EnvironmentInfo
{ {
public interface IOsVersionAdapter public interface IOsVersionAdapter
{ {
bool Enabled { get; } bool Enabled { get; }

View File

@ -34,6 +34,7 @@ namespace NzbDrone.Common.EnvironmentInfo
Os = Os.Windows; Os = Os.Windows;
break; break;
} }
case PlatformID.MacOSX: case PlatformID.MacOSX:
case PlatformID.Unix: case PlatformID.Unix:
{ {

View File

@ -2,8 +2,6 @@ namespace NzbDrone.Common.EnvironmentInfo
{ {
public class OsVersionModel public class OsVersionModel
{ {
public OsVersionModel(string name, string version, string fullName = null) public OsVersionModel(string name, string version, string fullName = null)
{ {
Name = Trim(name); Name = Trim(name);

View File

@ -2,7 +2,6 @@ using System;
namespace NzbDrone.Common.EnvironmentInfo namespace NzbDrone.Common.EnvironmentInfo
{ {
public enum PlatformType public enum PlatformType
{ {
DotNet = 0, DotNet = 0,

View File

@ -124,7 +124,6 @@ namespace NzbDrone.Common.EnvironmentInfo
public static bool IsProduction { get; } public static bool IsProduction { get; }
public static bool IsDevelopment { get; } public static bool IsDevelopment { get; }
private static bool InternalIsTesting() private static bool InternalIsTesting()
{ {
try try
@ -153,7 +152,6 @@ namespace NzbDrone.Common.EnvironmentInfo
} }
catch catch
{ {
} }
try try

View File

@ -7,19 +7,16 @@ namespace NzbDrone.Common.Exceptions
protected NzbDroneException(string message, params object[] args) protected NzbDroneException(string message, params object[] args)
: base(string.Format(message, args)) : base(string.Format(message, args))
{ {
} }
protected NzbDroneException(string message) protected NzbDroneException(string message)
: base(message) : base(message)
{ {
} }
protected NzbDroneException(string message, Exception innerException, params object[] args) protected NzbDroneException(string message, Exception innerException, params object[] args)
: base(string.Format(message, args), innerException) : base(string.Format(message, args), innerException)
{ {
} }
protected NzbDroneException(string message, Exception innerException) protected NzbDroneException(string message, Exception innerException)

View File

@ -7,19 +7,16 @@ namespace NzbDrone.Common.Exceptions
public SonarrStartupException(string message, params object[] args) public SonarrStartupException(string message, params object[] args)
: base("Sonarr failed to start: " + string.Format(message, args)) : base("Sonarr failed to start: " + string.Format(message, args))
{ {
} }
public SonarrStartupException(string message) public SonarrStartupException(string message)
: base("Sonarr failed to start: " + message) : base("Sonarr failed to start: " + message)
{ {
} }
public SonarrStartupException() public SonarrStartupException()
: base("Sonarr failed to start") : base("Sonarr failed to start")
{ {
} }
public SonarrStartupException(Exception innerException, string message, params object[] args) public SonarrStartupException(Exception innerException, string message, params object[] args)
@ -35,7 +32,6 @@ namespace NzbDrone.Common.Exceptions
public SonarrStartupException(Exception innerException) public SonarrStartupException(Exception innerException)
: base("Sonarr failed to start: " + innerException.Message) : base("Sonarr failed to start: " + innerException.Message)
{ {
} }
} }
} }

View File

@ -9,4 +9,4 @@ namespace NzbDrone.Common.Expansive
{ {
} }
} }
} }

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Specialized; using System.Collections.Specialized;
using System.Dynamic; using System.Dynamic;
@ -11,7 +11,6 @@ namespace NzbDrone.Common.Expansive
{ {
private static PatternStyle _patternStyle; private static PatternStyle _patternStyle;
public static bool RequireAllExpansions { get; set; } public static bool RequireAllExpansions { get; set; }
public static Func<string, string> DefaultExpansionFactory { get; set; } public static Func<string, string> DefaultExpansionFactory { get; set; }
@ -26,7 +25,6 @@ namespace NzbDrone.Common.Expansive
return source.Expand(DefaultExpansionFactory); return source.Expand(DefaultExpansionFactory);
} }
public static string Expand(this string source, params string[] args) public static string Expand(this string source, params string[] args)
{ {
var output = source; var output = source;
@ -50,9 +48,11 @@ namespace NzbDrone.Common.Expansive
{ {
tokenIndex = tokens.IndexOf(token); tokenIndex = tokens.IndexOf(token);
} }
output = Regex.Replace(output, _patternStyle.OutputFilter(match.Value), "{" + tokenIndex + "}"); output = Regex.Replace(output, _patternStyle.OutputFilter(match.Value), "{" + tokenIndex + "}");
} }
} }
var newArgs = new List<string>(); var newArgs = new List<string>();
foreach (var arg in args) foreach (var arg in args)
{ {
@ -63,15 +63,20 @@ namespace NzbDrone.Common.Expansive
foreach (Match match in tokenPattern.Matches(newArg)) foreach (Match match in tokenPattern.Matches(newArg))
{ {
var token = _patternStyle.TokenReplaceFilter(match.Value); var token = _patternStyle.TokenReplaceFilter(match.Value);
if (calls.Contains(string.Format("{0}:{1}", callingToken, token))) throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken)); if (calls.Contains(string.Format("{0}:{1}", callingToken, token)))
{
throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'.", callingToken));
}
calls.Push(string.Format("{0}:{1}", callingToken, token)); calls.Push(string.Format("{0}:{1}", callingToken, token));
callingToken = token; callingToken = token;
newArg = Regex.Replace(newArg, _patternStyle.OutputFilter(match.Value), args[tokens.IndexOf(token)]); newArg = Regex.Replace(newArg, _patternStyle.OutputFilter(match.Value), args[tokens.IndexOf(token)]);
} }
} }
newArgs.Add(newArg); newArgs.Add(newArg);
} }
return string.Format(output, newArgs.ToArray()); return string.Format(output, newArgs.ToArray());
} }
@ -80,9 +85,6 @@ namespace NzbDrone.Common.Expansive
return source.ExpandInternal(expansionFactory); return source.ExpandInternal(expansionFactory);
} }
public static string Expand(this string source, object model) public static string Expand(this string source, object model)
{ {
return source.ExpandInternal( return source.ExpandInternal(
@ -116,7 +118,10 @@ namespace NzbDrone.Common.Expansive
private static string ExpandInternal(this string source, Func<string, string> expansionFactory) private static string ExpandInternal(this string source, Func<string, string> expansionFactory)
{ {
if (expansionFactory == null) throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func<string, string> expansionFactory))"); if (expansionFactory == null)
{
throw new ApplicationException("ExpansionFactory not defined.\nDefine a DefaultExpansionFactory or call Expand(source, Func<string, string> expansionFactory))");
}
var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase); var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase);
@ -139,9 +144,12 @@ namespace NzbDrone.Common.Expansive
// if we have already encountered this token in this call tree, we have a circular reference // if we have already encountered this token in this call tree, we have a circular reference
if (thisNode.CallTree.Contains(token)) if (thisNode.CallTree.Contains(token))
{
throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'. Call Tree: {1}->{2}", throw new CircularReferenceException(string.Format("Circular Reference Detected for token '{0}'. Call Tree: {1}->{2}",
token, token,
string.Join("->", thisNode.CallTree.ToArray().Reverse()), token)); string.Join("->", thisNode.CallTree.ToArray().Reverse()),
token));
}
// expand this match // expand this match
var expandedValue = expansionFactory(token); var expandedValue = expansionFactory(token);
@ -156,6 +164,7 @@ namespace NzbDrone.Common.Expansive
output = Regex.Replace(output, patternStyle.OutputFilter(match.Value), child); output = Regex.Replace(output, patternStyle.OutputFilter(match.Value), child);
} }
} }
return output; return output;
} }
@ -171,7 +180,11 @@ namespace NzbDrone.Common.Expansive
{ {
var result = new ExpandoObject(); var result = new ExpandoObject();
var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary
if (o is ExpandoObject) return o; //shouldn't have to... but just in case if (o is ExpandoObject)
{
return o; //shouldn't have to... but just in case
}
if (o is NameValueCollection || o.GetType().IsSubclassOf(typeof(NameValueCollection))) if (o is NameValueCollection || o.GetType().IsSubclassOf(typeof(NameValueCollection)))
{ {
var nv = (NameValueCollection)o; var nv = (NameValueCollection)o;
@ -185,8 +198,10 @@ namespace NzbDrone.Common.Expansive
d.Add(item.Name, item.GetValue(o, null)); d.Add(item.Name, item.GetValue(o, null));
} }
} }
return result; return result;
} }
/// <summary> /// <summary>
/// Turns the object into a Dictionary /// Turns the object into a Dictionary
/// </summary> /// </summary>
@ -195,4 +210,4 @@ namespace NzbDrone.Common.Expansive
return (IDictionary<string, object>)thingy.ToExpando(); return (IDictionary<string, object>)thingy.ToExpando();
} }
} }
} }

View File

@ -9,4 +9,4 @@ namespace NzbDrone.Common.Expansive
public Func<string, string> TokenReplaceFilter { get; set; } public Func<string, string> TokenReplaceFilter { get; set; }
public Func<string, string> OutputFilter { get; set; } public Func<string, string> OutputFilter { get; set; }
} }
} }

View File

@ -8,4 +8,4 @@
Value = rootValue; Value = rootValue;
} }
} }
} }

View File

@ -1,4 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace NzbDrone.Common.Expansive namespace NzbDrone.Common.Expansive
{ {
@ -7,25 +7,29 @@ namespace NzbDrone.Common.Expansive
private List<T> _CallTree; private List<T> _CallTree;
private TreeNode<T> _Parent; private TreeNode<T> _Parent;
public TreeNode(T Value) public TreeNode(T value)
{ {
this.Value = Value; Value = value;
Parent = null; Parent = null;
Children = new TreeNodeList<T>(this); Children = new TreeNodeList<T>(this);
_CallTree = new List<T>(); _CallTree = new List<T>();
} }
public TreeNode(T Value, TreeNode<T> Parent) public TreeNode(T value, TreeNode<T> parent)
{ {
this.Value = Value; Value = value;
this.Parent = Parent; Parent = parent;
Children = new TreeNodeList<T>(this); Children = new TreeNodeList<T>(this);
_CallTree = new List<T>(); _CallTree = new List<T>();
} }
public TreeNode<T> Parent public TreeNode<T> Parent
{ {
get { return _Parent; } get
{
return _Parent;
}
set set
{ {
if (value == _Parent) if (value == _Parent)
@ -58,6 +62,7 @@ namespace NzbDrone.Common.Expansive
{ {
node = node.Parent; node = node.Parent;
} }
return node; return node;
} }
} }
@ -75,11 +80,16 @@ namespace NzbDrone.Common.Expansive
node = node.Parent; node = node.Parent;
_CallTree.Add(node.Value); _CallTree.Add(node.Value);
} }
return _CallTree; return _CallTree;
} }
private set { _CallTree = value; }
private set
{
_CallTree = value;
}
} }
public T Value { get; set; } public T Value { get; set; }
} }
} }

View File

@ -6,27 +6,26 @@ namespace NzbDrone.Common.Expansive
{ {
public TreeNode<T> Parent; public TreeNode<T> Parent;
public TreeNodeList(TreeNode<T> Parent) public TreeNodeList(TreeNode<T> parent)
{ {
this.Parent = Parent; this.Parent = parent;
} }
public new TreeNode<T> Add(TreeNode<T> Node) public new TreeNode<T> Add(TreeNode<T> node)
{ {
base.Add(Node); base.Add(node);
Node.Parent = Parent; node.Parent = Parent;
return Node; return node;
} }
public TreeNode<T> Add(T Value) public TreeNode<T> Add(T value)
{ {
return Add(new TreeNode<T>(Value)); return Add(new TreeNode<T>(value));
} }
public override string ToString() public override string ToString()
{ {
return "Count=" + Count.ToString(); return "Count=" + Count.ToString();
} }
} }
} }

View File

@ -7,30 +7,37 @@ namespace NzbDrone.Common.Extensions
{ {
public static class ExceptionExtensions public static class ExceptionExtensions
{ {
public static T WithData<T>(this T ex, string key, string value) where T : Exception public static T WithData<T>(this T ex, string key, string value)
where T : Exception
{ {
ex.AddData(key, value); ex.AddData(key, value);
return ex; return ex;
} }
public static T WithData<T>(this T ex, string key, int value) where T : Exception
public static T WithData<T>(this T ex, string key, int value)
where T : Exception
{ {
ex.AddData(key, value.ToString()); ex.AddData(key, value.ToString());
return ex; return ex;
} }
public static T WithData<T>(this T ex, string key, Http.HttpUri value) where T : Exception public static T WithData<T>(this T ex, string key, Http.HttpUri value)
where T : Exception
{ {
ex.AddData(key, value.ToString()); ex.AddData(key, value.ToString());
return ex; return ex;
} }
public static T WithData<T>(this T ex, Http.HttpResponse response, int maxSampleLength = 512)
public static T WithData<T>(this T ex, Http.HttpResponse response, int maxSampleLength = 512) where T : Exception where T : Exception
{ {
if (response == null || response.Content == null) return ex; if (response == null || response.Content == null)
{
return ex;
}
var contentSample = response.Content.Substring(0, Math.Min(response.Content.Length, maxSampleLength)); var contentSample = response.Content.Substring(0, Math.Min(response.Content.Length, maxSampleLength));
@ -50,16 +57,19 @@ namespace NzbDrone.Common.Extensions
{ {
ex.AddData("ContentType", response.Headers.ContentType ?? string.Empty); ex.AddData("ContentType", response.Headers.ContentType ?? string.Empty);
} }
ex.AddData("ContentLength", response.Content.Length.ToString()); ex.AddData("ContentLength", response.Content.Length.ToString());
ex.AddData("ContentSample", contentSample); ex.AddData("ContentSample", contentSample);
return ex; return ex;
} }
private static void AddData(this Exception ex, string key, string value) private static void AddData(this Exception ex, string key, string value)
{ {
if (value.IsNullOrWhiteSpace()) return; if (value.IsNullOrWhiteSpace())
{
return;
}
ex.Data[key] = value; ex.Data[key] = value;
} }

View File

@ -7,9 +7,11 @@ namespace NzbDrone.Common.Extensions
{ {
public static class EnumerableExtensions public static class EnumerableExtensions
{ {
public static IEnumerable<TFirst> IntersectBy<TFirst, TSecond, TKey>(this IEnumerable<TFirst> first, Func<TFirst, TKey> firstKeySelector, public static IEnumerable<TFirst> IntersectBy<TFirst, TSecond, TKey>(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second, Func<TSecond, TKey> secondKeySelector, Func<TFirst, TKey> firstKeySelector,
IEqualityComparer<TKey> keyComparer) IEnumerable<TSecond> second,
Func<TSecond, TKey> secondKeySelector,
IEqualityComparer<TKey> keyComparer)
{ {
var keys = new HashSet<TKey>(second.Select(secondKeySelector), keyComparer); var keys = new HashSet<TKey>(second.Select(secondKeySelector), keyComparer);
@ -25,9 +27,11 @@ namespace NzbDrone.Common.Extensions
} }
} }
public static IEnumerable<TFirst> ExceptBy<TFirst, TSecond, TKey>(this IEnumerable<TFirst> first, Func<TFirst, TKey> firstKeySelector, public static IEnumerable<TFirst> ExceptBy<TFirst, TSecond, TKey>(this IEnumerable<TFirst> first,
IEnumerable<TSecond> second, Func<TSecond, TKey> secondKeySelector, Func<TFirst, TKey> firstKeySelector,
IEqualityComparer<TKey> keyComparer) IEnumerable<TSecond> second,
Func<TSecond, TKey> secondKeySelector,
IEqualityComparer<TKey> keyComparer)
{ {
var keys = new HashSet<TKey>(second.Select(secondKeySelector), keyComparer); var keys = new HashSet<TKey>(second.Select(secondKeySelector), keyComparer);
var matchedKeys = new HashSet<TKey>(); var matchedKeys = new HashSet<TKey>();
@ -56,6 +60,7 @@ namespace NzbDrone.Common.Extensions
result[key] = item; result[key] = item;
} }
} }
return result; return result;
} }
@ -70,6 +75,7 @@ namespace NzbDrone.Common.Extensions
result[key] = valueSelector(item); result[key] = valueSelector(item);
} }
} }
return result; return result;
} }

View File

@ -11,8 +11,15 @@ namespace NzbDrone.Common.Extensions
{ {
const int bytesInKb = 1024; const int bytesInKb = 1024;
if (bytes < 0) return "-" + SizeSuffix(-bytes); if (bytes < 0)
if (bytes == 0) return "0 B"; {
return "-" + SizeSuffix(-bytes);
}
if (bytes == 0)
{
return "0 B";
}
var mag = (int)Math.Log(bytes, bytesInKb); var mag = (int)Math.Log(bytes, bytesInKb);
var adjustedSize = bytes / (decimal)Math.Pow(bytesInKb, mag); var adjustedSize = bytes / (decimal)Math.Pow(bytesInKb, mag);

View File

@ -6,9 +6,20 @@ namespace NzbDrone.Common.Extensions
{ {
public static int LevenshteinDistance(this string text, string other, int costInsert = 1, int costDelete = 1, int costSubstitute = 1) public static int LevenshteinDistance(this string text, string other, int costInsert = 1, int costDelete = 1, int costSubstitute = 1)
{ {
if (text == other) return 0; if (text == other)
if (text.Length == 0) return other.Length * costInsert; {
if (other.Length == 0) return text.Length * costDelete; return 0;
}
if (text.Length == 0)
{
return other.Length * costInsert;
}
if (other.Length == 0)
{
return text.Length * costDelete;
}
int[] matrix = new int[other.Length + 1]; int[] matrix = new int[other.Length + 1];
@ -47,4 +58,4 @@ namespace NzbDrone.Common.Extensions
return expected.LevenshteinDistance(other, 1, 3, 3); return expected.LevenshteinDistance(other, 1, 3, 3);
} }
} }
} }

View File

@ -4,10 +4,11 @@ namespace NzbDrone.Common.Extensions
{ {
public static class ObjectExtensions public static class ObjectExtensions
{ {
public static T JsonClone<T>(this T source) where T : new() public static T JsonClone<T>(this T source)
where T : new()
{ {
var json = source.ToJson(); var json = source.ToJson();
return Json.Deserialize<T>(json); return Json.Deserialize<T>(json);
} }
} }
} }

View File

@ -113,6 +113,7 @@ namespace NzbDrone.Common.Extensions
{ {
parentPath = parentPath.TrimEnd(Path.DirectorySeparatorChar); parentPath = parentPath.TrimEnd(Path.DirectorySeparatorChar);
} }
if (childPath != "/" && !parentPath.EndsWith(":\\")) if (childPath != "/" && !parentPath.EndsWith(":\\"))
{ {
childPath = childPath.TrimEnd(Path.DirectorySeparatorChar); childPath = childPath.TrimEnd(Path.DirectorySeparatorChar);

View File

@ -14,6 +14,7 @@ namespace NzbDrone.Common.Extensions
{ {
ms.Write(buffer, 0, read); ms.Write(buffer, 0, read);
} }
return ms.ToArray(); return ms.ToArray();
} }
} }

View File

@ -18,7 +18,11 @@ namespace NzbDrone.Common.Extensions
public static object NullSafe(this object target) public static object NullSafe(this object target)
{ {
if (target != null) return target; if (target != null)
{
return target;
}
return "[NULL]"; return "[NULL]";
} }
@ -76,7 +80,9 @@ namespace NzbDrone.Common.Extensions
public static string TrimEnd(this string text, string postfix) public static string TrimEnd(this string text, string postfix)
{ {
if (text.EndsWith(postfix)) if (text.EndsWith(postfix))
{
text = text.Substring(0, text.Length - postfix.Length); text = text.Substring(0, text.Length - postfix.Length);
}
return text; return text;
} }
@ -134,7 +140,7 @@ namespace NzbDrone.Common.Extensions
public static byte[] HexToByteArray(this string input) public static byte[] HexToByteArray(this string input)
{ {
return Enumerable.Range(0, input.Length) return Enumerable.Range(0, input.Length)
.Where(x => x%2 == 0) .Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(input.Substring(x, 2), 16)) .Select(x => Convert.ToByte(input.Substring(x, 2), 16))
.ToArray(); .ToArray();
} }
@ -151,9 +157,9 @@ namespace NzbDrone.Common.Extensions
var first = int.Parse(octalValue.Substring(0, 1)); var first = int.Parse(octalValue.Substring(0, 1));
var second = int.Parse(octalValue.Substring(1, 1)); var second = int.Parse(octalValue.Substring(1, 1));
var third = int.Parse(octalValue.Substring(2, 1)); var third = int.Parse(octalValue.Substring(2, 1));
var byteResult = (byte)((first << 6) | (second << 3) | (third)); var byteResult = (byte)((first << 6) | (second << 3) | third);
return Encoding.ASCII.GetString(new [] { byteResult }); return Encoding.ASCII.GetString(new[] { byteResult });
} }
public static string SplitCamelCase(this string input) public static string SplitCamelCase(this string input)
@ -165,7 +171,7 @@ namespace NzbDrone.Common.Extensions
{ {
return source.Contains(value, StringComparer.InvariantCultureIgnoreCase); return source.Contains(value, StringComparer.InvariantCultureIgnoreCase);
} }
public static string ToUrlSlug(this string value) public static string ToUrlSlug(this string value)
{ {
//First to lower case //First to lower case

View File

@ -28,7 +28,6 @@ namespace NzbDrone.Common.Extensions
} }
return true; return true;
} }
} }
} }

View File

@ -24,6 +24,7 @@ namespace NzbDrone.Common
} }
} }
} }
return $"{mCrc:x8}"; return $"{mCrc:x8}";
} }

View File

@ -197,6 +197,7 @@ namespace NzbDrone.Common.Http.Dispatchers
{ {
var responseStreamInfo = currentOperation.GetType().GetField("responseStream", BindingFlags.NonPublic | BindingFlags.Instance); var responseStreamInfo = currentOperation.GetType().GetField("responseStream", BindingFlags.NonPublic | BindingFlags.Instance);
var responseStream = responseStreamInfo.GetValue(currentOperation) as Stream; var responseStream = responseStreamInfo.GetValue(currentOperation) as Stream;
// Note that responseStream will likely be null once mono fixes it. // Note that responseStream will likely be null once mono fixes it.
responseStream?.Dispose(); responseStream?.Dispose();
} }

View File

@ -12,4 +12,4 @@ namespace NzbDrone.Common.Http
return request; return request;
} }
} }
} }

View File

@ -6,7 +6,7 @@
public static readonly HttpAccept Json = new HttpAccept("application/json"); public static readonly HttpAccept Json = new HttpAccept("application/json");
public static readonly HttpAccept JsonCharset = new HttpAccept("application/json; charset=utf-8"); public static readonly HttpAccept JsonCharset = new HttpAccept("application/json; charset=utf-8");
public static readonly HttpAccept Html = new HttpAccept("text/html"); public static readonly HttpAccept Html = new HttpAccept("text/html");
public string Value { get; private set; } public string Value { get; private set; }
public HttpAccept(string accept) public HttpAccept(string accept)

View File

@ -18,10 +18,12 @@ namespace NzbDrone.Common.Http
HttpResponse Execute(HttpRequest request); HttpResponse Execute(HttpRequest request);
void DownloadFile(string url, string fileName); void DownloadFile(string url, string fileName);
HttpResponse Get(HttpRequest request); HttpResponse Get(HttpRequest request);
HttpResponse<T> Get<T>(HttpRequest request) where T : new(); HttpResponse<T> Get<T>(HttpRequest request)
where T : new();
HttpResponse Head(HttpRequest request); HttpResponse Head(HttpRequest request);
HttpResponse Post(HttpRequest request); HttpResponse Post(HttpRequest request);
HttpResponse<T> Post<T>(HttpRequest request) where T : new(); HttpResponse<T> Post<T>(HttpRequest request)
where T : new();
} }
public class HttpClient : IHttpClient public class HttpClient : IHttpClient
@ -258,11 +260,13 @@ namespace NzbDrone.Common.Http
throw new HttpException(request, response, "Site responded with html content."); throw new HttpException(request, response, "Site responded with html content.");
} }
} }
stopWatch.Stop(); stopWatch.Stop();
if (File.Exists(fileName)) if (File.Exists(fileName))
{ {
File.Delete(fileName); File.Delete(fileName);
} }
File.Move(fileNamePart, fileName); File.Move(fileNamePart, fileName);
_logger.Debug("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds); _logger.Debug("Downloading Completed. took {0:0}s", stopWatch.Elapsed.Seconds);
} }
@ -271,7 +275,7 @@ namespace NzbDrone.Common.Http
if (File.Exists(fileNamePart)) if (File.Exists(fileNamePart))
{ {
File.Delete(fileNamePart); File.Delete(fileNamePart);
} }
} }
} }
@ -281,7 +285,8 @@ namespace NzbDrone.Common.Http
return Execute(request); return Execute(request);
} }
public HttpResponse<T> Get<T>(HttpRequest request) where T : new() public HttpResponse<T> Get<T>(HttpRequest request)
where T : new()
{ {
var response = Get(request); var response = Get(request);
CheckResponseContentType(response); CheckResponseContentType(response);
@ -300,7 +305,8 @@ namespace NzbDrone.Common.Http
return Execute(request); return Execute(request);
} }
public HttpResponse<T> Post<T>(HttpRequest request) where T : new() public HttpResponse<T> Post<T>(HttpRequest request)
where T : new()
{ {
var response = Post(request); var response = Post(request);
CheckResponseContentType(response); CheckResponseContentType(response);

Some files were not shown because too many files have changed in this diff Show More