1
0
Fork 0
mirror of https://github.com/Sonarr/Sonarr synced 2024-12-24 08:44:46 +00:00

fixed more tests.

This commit is contained in:
Keivan Beigi 2013-04-15 17:08:06 -07:00
parent 6a5c10a456
commit 9fdfd13dbf
23 changed files with 261 additions and 490 deletions

View file

@ -2,8 +2,6 @@
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using NLog;
using NzbDrone.Common.Model;
namespace NzbDrone.Common
@ -11,10 +9,9 @@ namespace NzbDrone.Common
public class ConfigFileProvider
{
private readonly EnvironmentProvider _environmentProvider;
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
private readonly string _configFile;
public ConfigFileProvider(EnvironmentProvider environmentProvider)
{
_environmentProvider = environmentProvider;
@ -25,7 +22,7 @@ namespace NzbDrone.Common
public ConfigFileProvider()
{
}
public virtual Guid Guid
@ -60,11 +57,6 @@ namespace NzbDrone.Common
set { SetValue("AuthenticationType", (int)value); }
}
public virtual bool EnableProfiler
{
get { return GetValueBoolean("EnableProfiler", false); }
set { SetValue("EnableProfiler", value); }
}
public virtual int GetValueInt(string key, int defaultValue)
{
@ -126,50 +118,5 @@ namespace NzbDrone.Common
xDoc.Save(_configFile);
}
}
public virtual void UpdateIISConfig(string configPath)
{
logger.Info(@"Server configuration file: {0}", configPath);
logger.Info(@"Configuring server to: [http://localhost:{0}]", Port);
var configXml = XDocument.Load(configPath);
var bindings =
configXml.XPathSelectElement("configuration/system.applicationHost/sites").Elements("site").Where(
d => d.Attribute("name").Value.ToLowerInvariant() == "nzbdrone").First().Element("bindings");
bindings.Descendants().Remove();
bindings.Add(
new XElement("binding",
new XAttribute("protocol", "http"),
new XAttribute("bindingInformation", String.Format("*:{0}:localhost", Port))
));
bindings.Add(
new XElement("binding",
new XAttribute("protocol", "http"),
new XAttribute("bindingInformation", String.Format("*:{0}:", Port))
));
//Update the authenticationTypes
var location = configXml.XPathSelectElement("configuration").Elements("location").Where(
d => d.Attribute("path").Value.ToLowerInvariant() == "nzbdrone").First();
var authenticationTypes = location.XPathSelectElements("system.webServer/security/authentication").First().Descendants();
//Set all authentication types enabled to false
foreach (var child in authenticationTypes)
{
child.Attribute("enabled").Value = "false";
}
var configuredAuthType = String.Format("{0}Authentication", AuthenticationType.ToString()).ToLowerInvariant();
//Set the users authenticationType to true
authenticationTypes.Where(t => t.Name.ToString().ToLowerInvariant() == configuredAuthType).Single().Attribute("enabled").Value = "true";
configXml.Save(configPath);
}
}
}

View file

@ -11,8 +11,6 @@ namespace NzbDrone.Common
private static readonly EnvironmentProvider Instance = new EnvironmentProvider();
private const string NZBDRONE_PID = "NZBDRONE_PID";
public static bool IsProduction
{
get
@ -104,19 +102,6 @@ namespace NzbDrone.Common
}
}
public virtual int NzbDroneProcessIdFromEnvironment
{
get
{
var id = Convert.ToInt32(Environment.GetEnvironmentVariable(NZBDRONE_PID));
if (id == 0)
throw new InvalidOperationException("NZBDRONE_PID isn't a valid environment variable.");
return id;
}
}
public virtual Version GetOsVersion()
{
OperatingSystem os = Environment.OSVersion;

View file

@ -9,15 +9,13 @@ namespace NzbDrone.Common.Expansive
{
public static class Expansive
{
private static Dictionary<TokenStyle, PatternStyle> _patternStyles;
private static PatternStyle _patternStyle;
public static bool RequireAllExpansions { get; set; }
public static Func<string, string> DefaultExpansionFactory { get; set; }
public static TokenStyle DefaultTokenStyle { get; set; }
static Expansive()
{
Initialize();
@ -28,17 +26,12 @@ namespace NzbDrone.Common.Expansive
return source.Expand(DefaultExpansionFactory);
}
public static string Expand(this string source, TokenStyle tokenStyle)
{
return source.ExpandInternal(DefaultExpansionFactory, tokenStyle);
}
public static string Expand(this string source, params string[] args)
{
var output = source;
var tokens = new List<string>();
var patternStyle = _patternStyles[DefaultTokenStyle];
var pattern = new Regex(patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase);
var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase);
var calls = new Stack<string>();
string callingToken = null;
@ -46,7 +39,7 @@ namespace NzbDrone.Common.Expansive
{
foreach (Match match in pattern.Matches(output))
{
var token = patternStyle.TokenReplaceFilter(match.Value);
var token = _patternStyle.TokenReplaceFilter(match.Value);
var tokenIndex = 0;
if (!tokens.Contains(token))
{
@ -57,23 +50,23 @@ namespace NzbDrone.Common.Expansive
{
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>();
foreach (var arg in args)
{
var newArg = arg;
var tokenPattern = new Regex(patternStyle.TokenFilter(String.Join("|", tokens)));
var tokenPattern = new Regex(_patternStyle.TokenFilter(String.Join("|", tokens)));
while (tokenPattern.IsMatch(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));
calls.Push(string.Format("{0}:{1}", 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)]);
}
}
@ -84,38 +77,13 @@ namespace NzbDrone.Common.Expansive
public static string Expand(this string source, Func<string, string> expansionFactory)
{
return source.ExpandInternal(expansionFactory, DefaultTokenStyle);
return source.ExpandInternal(expansionFactory);
}
public static string Expand(this string source, Func<string, string> expansionFactory, TokenStyle tokenStyle)
{
return source.ExpandInternal(expansionFactory, tokenStyle);
}
public static string Expand(this string source, object model)
{
return source.Expand(model, DefaultTokenStyle);
}
public static string Expand(this string source, params object[] models)
{
var mergedModel = new ExpandoObject().ToDictionary();
models.ToList().ForEach(m =>
{
var md = m.ToDictionary();
var keys = md.Keys;
keys.ToList().ForEach(k =>
{
if (!mergedModel.ContainsKey(k))
{
mergedModel.Add(k, md[k]);
}
});
});
return source.Expand(mergedModel as ExpandoObject);
}
public static string Expand(this string source, object model, TokenStyle tokenStyle)
{
return source.ExpandInternal(
name =>
@ -132,69 +100,29 @@ namespace NzbDrone.Common.Expansive
}
return modelDict[name].ToString();
}
, tokenStyle);
});
}
#region : Private Helper Methods :
private static void Initialize()
{
DefaultTokenStyle = TokenStyle.MvcRoute;
_patternStyles = new Dictionary<TokenStyle, PatternStyle>
_patternStyle = new PatternStyle
{
{
TokenStyle.MvcRoute, new PatternStyle
{
TokenMatchPattern = @"\{[a-zA-Z]\w*\}",
TokenReplaceFilter = token => token.Replace("{", "").Replace("}", ""),
OutputFilter = output => (output.StartsWith("{") && output.EndsWith("}") ? output : @"\{" + output + @"\}"),
TokenFilter = tokens => "{(" + tokens + ")}"
}
}
,
{
TokenStyle.Razor, new PatternStyle
{
TokenMatchPattern = @"@([a-zA-Z]\w*|\([a-zA-Z]\w*\))",
TokenReplaceFilter = token => token.Replace("@", "").Replace("(", "").Replace(")", ""),
OutputFilter = output => (output.StartsWith("@") ? output.Replace("(", @"\(").Replace(")",@"\)") : "@" + output.Replace("(", @"\(").Replace(")",@"\)")),
TokenFilter = tokens => @"@(" + tokens + @"|\(" + tokens + @"\))"
}
}
,
{
TokenStyle.NAnt, new PatternStyle
{
TokenMatchPattern = @"\$\{[a-zA-Z]\w*\}",
TokenReplaceFilter = token => token.Replace("${", "").Replace("}", ""),
OutputFilter = output => (output.StartsWith("${") && output.EndsWith("}") ? output.Replace("$",@"\$").Replace("{",@"\{").Replace("}",@"\}") : @"\$\{" + output + @"\}"),
TokenFilter = tokens => @"\$\{(" + tokens + @")\}"
}
}
,
{
TokenStyle.MSBuild, new PatternStyle
{
TokenMatchPattern = @"\$\([a-zA-Z]\w*\)",
TokenReplaceFilter = token => token.Replace("$(", "").Replace(")", ""),
OutputFilter = output => (output.StartsWith("$(") && output.EndsWith(")") ? output.Replace("$",@"\$").Replace("(",@"\(").Replace(")",@"\)") : @"\$\(" + output + @"\)"),
TokenFilter = tokens => @"\$\((" + tokens + @")\)"
}
}
TokenMatchPattern = @"\{[a-zA-Z]\w*\}",
TokenReplaceFilter = token => token.Replace("{", "").Replace("}", ""),
OutputFilter = output => (output.StartsWith("{") && output.EndsWith("}") ? output : @"\{" + output + @"\}"),
TokenFilter = tokens => "{(" + tokens + ")}"
};
}
private static string ExpandInternal(this string source, Func<string, string> expansionFactory, TokenStyle tokenStyle)
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))");
var patternStyle = _patternStyles[tokenStyle];
var pattern = new Regex(patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase);
var pattern = new Regex(_patternStyle.TokenMatchPattern, RegexOptions.IgnoreCase);
var callTreeParent = new Tree<string>("root").Root;
return source.Explode(pattern, patternStyle, expansionFactory, callTreeParent);
return source.Explode(pattern, _patternStyle, expansionFactory, callTreeParent);
}
private static string Explode(this string source, Regex pattern, PatternStyle patternStyle, Func<string, string> expansionFactory, TreeNode<string> parent)
@ -266,7 +194,5 @@ namespace NzbDrone.Common.Expansive
{
return (IDictionary<string, object>)thingy.ToExpando();
}
#endregion
}
}

View file

@ -58,6 +58,7 @@
<Reference Include="Ionic.Zip">
<HintPath>..\packages\DotNetZip.1.9.1.8\lib\net20\Ionic.Zip.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Nancy">
<HintPath>..\packages\Nancy.0.16.1\lib\net40\Nancy.dll</HintPath>
</Reference>

View file

@ -31,8 +31,9 @@ namespace NzbDrone.Core.Test.Download
.Build().ToList();
_parseResult = Builder<RemoteEpisode>.CreateNew()
.With(c => c.Quality = new QualityModel(Quality.DVD, false))
.With(c => c.Quality = new QualityModel(Quality.DVD))
.With(c => c.Series = Builder<Series>.CreateNew().Build())
.With(c=>c.Report = Builder<ReportInfo>.CreateNew().Build())
.With(c => c.Episodes = episodes)
.Build();
}

View file

@ -1,6 +1,7 @@
using System;
using System.IO;
using NUnit.Framework;
using NzbDrone.Common;
using NzbDrone.Core.Model.Notification;
using NzbDrone.Test.Common;
@ -25,6 +26,11 @@ namespace NzbDrone.Core.Test.Framework
{
return File.ReadAllText(Path.Combine(path));
}
protected void UseRealHttp()
{
Mocker.SetConstant<IHttpProvider>(new HttpProvider(new EnvironmentProvider()));
}
}
public abstract class CoreTest<TSubject> : CoreTest where TSubject : class

View file

@ -1,24 +1,15 @@
using System.Linq;
using System;
using System.Diagnostics;
using System.IO;
using FizzWare.NBuilder;
using FluentAssertions;
using Moq;
using Moq;
using NUnit.Framework;
using NzbDrone.Common;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Jobs;
using NzbDrone.Core.Jobs.Implementations;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Test.Common;
namespace NzbDrone.Core.Test.JobTests
{
[TestFixture]
internal class PostDownloadScanJobFixture : CoreTest
internal class PostDownloadScanJobFixture : CoreTest<PostDownloadScanJob>
{
[SetUp]
public void Setup()
@ -31,10 +22,10 @@ namespace NzbDrone.Core.Test.JobTests
{
var path = @"C:\Test\Unsorted TV";
Mocker.GetMock<DropFolderImportService>().Setup(s => s.ProcessDropFolder(path));
Mocker.Resolve<PostDownloadScanJob>().Start(MockNotification, new { Path = path });
Mocker.GetMock<IDropFolderImportService>().Setup(s => s.ProcessDropFolder(path));
Subject.Start(MockNotification, new { Path = path });
Mocker.GetMock<DropFolderImportService>().Verify(s => s.ProcessDropFolder(path), Times.Once());
Mocker.GetMock<IDropFolderImportService>().Verify(s => s.ProcessDropFolder(path), Times.Once());
}
[Test]
@ -42,8 +33,8 @@ namespace NzbDrone.Core.Test.JobTests
{
var path = @"C:\Test\Unsorted TV";
Mocker.GetMock<DropFolderImportService>().Setup(s => s.ProcessDropFolder(path));
Mocker.Resolve<PostDownloadScanJob>().Start(MockNotification, new { Path = path });
Mocker.GetMock<IDropFolderImportService>().Setup(s => s.ProcessDropFolder(path));
Subject.Start(MockNotification, new { Path = path });
Mocker.GetMock<IConfigService>().Verify(s => s.DownloadClientTvDirectory, Times.Never());
}
@ -54,7 +45,7 @@ namespace NzbDrone.Core.Test.JobTests
var path = @"C:\Test\Unsorted TV";
Mocker.GetMock<IConfigService>().SetupGet(s => s.DownloadClientTvDirectory).Returns(path);
Mocker.Resolve<PostDownloadScanJob>().Start(MockNotification, null);
Subject.Start(MockNotification, null);
Mocker.GetMock<IConfigService>().Verify(s => s.DownloadClientTvDirectory, Times.Once());
}
@ -65,9 +56,10 @@ namespace NzbDrone.Core.Test.JobTests
var path = @"C:\Test\Unsorted TV";
Mocker.GetMock<IConfigService>().SetupGet(s => s.DownloadClientTvDirectory).Returns(path);
Mocker.Resolve<PostDownloadScanJob>().Start(MockNotification, null);
Subject.Start(MockNotification, null);
Mocker.GetMock<DropFolderImportService>().Verify(s => s.ProcessDropFolder(path), Times.Once());
Mocker.GetMock<IDropFolderImportService>().Verify(s => s.ProcessDropFolder(path), Times.Once());
}
}
}

View file

@ -172,7 +172,7 @@
<Compile Include="ProviderTests\DiskProviderTests\ExtractArchiveFixture.cs" />
<Compile Include="ProviderTests\PostDownloadProviderTests\DropFolderImportServiceFixture.cs" />
<Compile Include="JobTests\TestJobs.cs" />
<Compile Include="JobTests\AppUpdateJobFixture.cs" />
<Compile Include="UpdateTests\UpdateServiceFixture.cs" />
<Compile Include="ProviderTests\XemCommunicationProviderTests\GetSceneTvdbMappingsFixture.cs" />
<Compile Include="ProviderTests\XemCommunicationProviderTests\GetXemSeriesIdsFixture.cs" />
<Compile Include="Services\ParseErrorServiceFixture.cs" />
@ -204,7 +204,6 @@
<Compile Include="Qualities\QualityProfileFixture.cs" />
<Compile Include="TvTests\SeriesProviderTest.cs" />
<Compile Include="UpdateTests\UpdatePackageProviderFixture.cs" />
<Compile Include="UpdateTests\GetAvailableUpdateFixture.cs" />
<Compile Include="UpdateTests\GetUpdateLogFixture.cs" />
<Compile Include="XbmcVersionTests.cs" />
</ItemGroup>

View file

@ -1,31 +1,24 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using FizzWare.NBuilder;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using NzbDrone.Common;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Test.Common;
using NzbDrone.Test.Common.AutoMoq;
namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests
{
public class GetVideoFilesFixture : CoreTest
public class GetVideoFilesFixture : CoreTest<DiskScanService>
{
private string[] _files;
[SetUp]
public void Setup()
{
_files = new string[]
_files = new[]
{
@"C:\Test\30 Rock1.mkv",
@"C:\Test\30 Rock2.avi",
@ -44,7 +37,7 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests
{
var path = @"C:\Test\";
Mocker.Resolve<IDiskScanService>().GetVideoFiles(path);
Subject.GetVideoFiles(path);
Mocker.GetMock<DiskProvider>().Verify(s => s.GetFiles(path, SearchOption.AllDirectories), Times.Once());
Mocker.GetMock<DiskProvider>().Verify(s => s.GetFiles(path, SearchOption.TopDirectoryOnly), Times.Never());
@ -55,7 +48,7 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests
{
var path = @"C:\Test\";
Mocker.Resolve<IDiskScanService>().GetVideoFiles(path, true);
Subject.GetVideoFiles(path, true);
Mocker.GetMock<DiskProvider>().Verify(s => s.GetFiles(path, SearchOption.AllDirectories), Times.Once());
Mocker.GetMock<DiskProvider>().Verify(s => s.GetFiles(path, SearchOption.TopDirectoryOnly), Times.Never());
@ -66,7 +59,7 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests
{
var path = @"C:\Test\";
Mocker.Resolve<IDiskScanService>().GetVideoFiles(path, false);
Subject.GetVideoFiles(path, false);
Mocker.GetMock<DiskProvider>().Verify(s => s.GetFiles(path, SearchOption.AllDirectories), Times.Never());
Mocker.GetMock<DiskProvider>().Verify(s => s.GetFiles(path, SearchOption.TopDirectoryOnly), Times.Once());
@ -77,7 +70,7 @@ namespace NzbDrone.Core.Test.ProviderTests.DiskScanProviderTests
{
var path = @"C:\Test\";
Mocker.Resolve<IDiskScanService>().GetVideoFiles(path).Should().HaveCount(4);
Subject.GetVideoFiles(path).Should().HaveCount(4);
}
}
}

View file

@ -1,61 +0,0 @@
using System;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Test.Framework;
namespace NzbDrone.Core.Test.UpdateTests
{
class GetAvailableUpdateFixture : CoreTest<UpdateService>
{
private static readonly Version LatestTestVersion = new Version("0.6.0.3");
private const string LATEST_TEST_URL = "http://update.nzbdrone.com/_test/NzbDrone.master.0.6.0.3.zip";
private const string LATEST_TEST_FILE_NAME = "NzbDrone.master.0.6.0.3.zip";
[SetUp]
public void Setup()
{
Mocker.GetMock<IConfigService>().SetupGet(c => c.UpdateUrl).Returns("http://update.nzbdrone.com/_test/");
Mocker.Resolve<HttpProvider>();
}
[TestCase("0.6.0.9")]
[TestCase("0.7.0.1")]
[TestCase("1.0.0.0")]
public void should_return_null_if_latest_is_lower_than_current_version(string currentVersion)
{
Mocker.GetMock<EnvironmentProvider>().SetupGet(c => c.Version).Returns(new Version(currentVersion));
var updatePackage = Subject.GetAvailableUpdate();
updatePackage.Should().BeNull();
}
[Test]
public void should_return_null_if_latest_is_equal_to_current_version()
{
Mocker.GetMock<EnvironmentProvider>().SetupGet(c => c.Version).Returns(LatestTestVersion);
var updatePackage = Subject.GetAvailableUpdate();
updatePackage.Should().BeNull();
}
[TestCase("0.0.0.0")]
[TestCase("0.0.0.1")]
[TestCase("0.0.10.10")]
public void should_return_update_if_latest_is_higher_than_current_version(string currentVersion)
{
Mocker.GetMock<EnvironmentProvider>().SetupGet(c => c.Version).Returns(new Version(currentVersion));
var updatePackage = Subject.GetAvailableUpdate();
updatePackage.Should().NotBeNull();
updatePackage.Version.Should().Be(LatestTestVersion);
updatePackage.FileName.Should().BeEquivalentTo(LATEST_TEST_FILE_NAME);
updatePackage.Url.Should().BeEquivalentTo(LATEST_TEST_URL);
}
}
}

View file

@ -1,15 +1,28 @@
using System;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Common;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Core.Update;
using System.Linq;
namespace NzbDrone.Core.Test.UpdateTests
{
public class UpdatePackageProviderFixture : CoreTest<UpdatePackageProvider>
{
[Test]
public void should_get_list_of_avilable_updates()
{
UseRealHttp();
Mocker.GetMock<IConfigService>().SetupGet(c => c.UpdateUrl).Returns("http://update.nzbdrone.com/_release/");
var updates = Subject.GetAvailablePackages().ToList();
updates.Should().NotBeEmpty();
updates.Should().OnlyContain(c => !string.IsNullOrWhiteSpace(c.FileName));
updates.Should().OnlyContain(c => !string.IsNullOrWhiteSpace(c.Url));
updates.Should().OnlyContain(c => c.Version != null);
updates.Should().OnlyContain(c => c.Version.Minor != 0);
}
}
}

View file

@ -1,30 +1,25 @@
using System.Linq;
using System;
using System;
using System.Diagnostics;
using System.IO;
using FizzWare.NBuilder;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using NzbDrone.Common;
using NzbDrone.Core.Jobs;
using NzbDrone.Core.Lifecycle;
using NzbDrone.Core.Model;
using NzbDrone.Core.Providers;
using NzbDrone.Common.Model;
using NzbDrone.Core.Test.Framework;
using NzbDrone.Core.Update;
using NzbDrone.Test.Common;
namespace NzbDrone.Core.Test.JobTests
namespace NzbDrone.Core.Test.UpdateTests
{
[TestFixture]
internal class AppUpdateJobFixture : CoreTest
internal class UpdateServiceFixture : CoreTest<UpdateService>
{
private const string SANDBOX_FOLDER = @"C:\Temp\nzbdrone_update\";
private string _sandboxFolder;
private readonly Guid _clientGuid = Guid.NewGuid();
private readonly UpdatePackage updatePackage = new UpdatePackage
private readonly UpdatePackage _updatePackage = new UpdatePackage
{
FileName = "NzbDrone.kay.one.0.6.0.2031.zip",
Url = "http://update.nzbdrone.com/_test/NzbDrone.zip",
@ -34,61 +29,56 @@ namespace NzbDrone.Core.Test.JobTests
[SetUp]
public void Setup()
{
Mocker.GetMock<EnvironmentProvider>().SetupGet(c => c.SystemTemp).Returns(@"C:\Temp\");
Mocker.GetMock<EnvironmentProvider>().SetupGet(c => c.SystemTemp).Returns(TempFolder);
Mocker.GetMock<ConfigFileProvider>().SetupGet(c => c.Guid).Returns(_clientGuid);
Mocker.GetMock<UpdateService>().Setup(c => c.GetAvailableUpdate()).Returns(updatePackage);
Mocker.GetMock<IUpdatePackageProvider>().Setup(c => c.GetLatestUpdate()).Returns(_updatePackage);
Mocker.GetMock<ProcessProvider>().Setup(c => c.GetCurrentProcess()).Returns(new ProcessInfo { Id = 12 });
_sandboxFolder = Mocker.GetMock<EnvironmentProvider>().Object.GetUpdateSandboxFolder();
}
[Test]
public void should_delete_sandbox_before_update_if_folder_exists()
{
Mocker.GetMock<DiskProvider>().Setup(c => c.FolderExists(SANDBOX_FOLDER)).Returns(true);
Mocker.GetMock<DiskProvider>().Setup(c => c.FolderExists(_sandboxFolder)).Returns(true);
Subject.InstallAvailableUpdate();
StartUpdate();
Mocker.GetMock<DiskProvider>().Verify(c => c.DeleteFolder(SANDBOX_FOLDER, true));
Mocker.GetMock<DiskProvider>().Verify(c => c.DeleteFolder(_sandboxFolder, true));
}
[Test]
public void should_not_delete_sandbox_before_update_if_folder_doesnt_exists()
{
Mocker.GetMock<DiskProvider>().Setup(c => c.FolderExists(SANDBOX_FOLDER)).Returns(false);
Mocker.GetMock<DiskProvider>().Setup(c => c.FolderExists(_sandboxFolder)).Returns(false);
Subject.InstallAvailableUpdate();
StartUpdate();
Mocker.GetMock<DiskProvider>().Verify(c => c.DeleteFolder(SANDBOX_FOLDER, true), Times.Never());
Mocker.GetMock<DiskProvider>().Verify(c => c.DeleteFolder(_sandboxFolder, true), Times.Never());
}
[Test]
public void Should_download_update_package()
{
var updateArchive = Path.Combine(SANDBOX_FOLDER, updatePackage.FileName);
var updateArchive = Path.Combine(_sandboxFolder, _updatePackage.FileName);
Subject.InstallAvailableUpdate();
StartUpdate();
Mocker.GetMock<IHttpProvider>().Verify(
c => c.DownloadFile(updatePackage.Url, updateArchive));
Mocker.GetMock<IHttpProvider>().Verify(c => c.DownloadFile(_updatePackage.Url, updateArchive));
}
[Test]
public void Should_extract_update_package()
{
var updateArchive = Path.Combine(SANDBOX_FOLDER, updatePackage.FileName);
var updateArchive = Path.Combine(_sandboxFolder, _updatePackage.FileName);
Subject.InstallAvailableUpdate();
StartUpdate();
Mocker.GetMock<ArchiveProvider>().Verify(
c => c.ExtractArchive(updateArchive, SANDBOX_FOLDER));
Mocker.GetMock<ArchiveProvider>().Verify(c => c.ExtractArchive(updateArchive, _sandboxFolder));
}
[Test]
@ -96,25 +86,20 @@ namespace NzbDrone.Core.Test.JobTests
{
var updateClientFolder = Mocker.GetMock<EnvironmentProvider>().Object.GetUpdateClientFolder();
StartUpdate();
Subject.InstallAvailableUpdate();
Mocker.GetMock<DiskProvider>().Verify(
c => c.MoveDirectory(updateClientFolder, SANDBOX_FOLDER));
Mocker.GetMock<DiskProvider>().Verify(c => c.MoveDirectory(updateClientFolder, _sandboxFolder));
}
[Test]
public void should_start_update_client()
{
var updateClientPath = Mocker.GetMock<EnvironmentProvider>().Object.GetUpdateClientExePath();
Mocker.GetMock<EnvironmentProvider>()
.SetupGet(c => c.NzbDroneProcessIdFromEnvironment).Returns(12);
StartUpdate();
Subject.InstallAvailableUpdate();
Mocker.GetMock<ProcessProvider>().Verify(
@ -127,42 +112,34 @@ namespace NzbDrone.Core.Test.JobTests
[Test]
public void when_no_updates_are_available_should_return_without_error_or_warnings()
{
Mocker.GetMock<UpdateService>().Setup(c => c.GetAvailableUpdate()).Returns((UpdatePackage)null);
Mocker.GetMock<IUpdatePackageProvider>().Setup(c => c.GetLatestUpdate()).Returns<UpdatePackage>(null);
StartUpdate();
Subject.InstallAvailableUpdate();
ExceptionVerification.AssertNoUnexcpectedLogs();
}
[Test]
[Category(INTEGRATION_TEST)]
[IntegrationTest]
public void Should_download_and_extract_to_temp_folder()
{
Mocker.GetMock<EnvironmentProvider>().SetupGet(c => c.SystemTemp).Returns(TempFolder);
UseRealHttp();
var updateSubFolder = new DirectoryInfo(Mocker.GetMock<EnvironmentProvider>().Object.GetUpdateSandboxFolder());
updateSubFolder.Exists.Should().BeFalse();
Mocker.SetConstant<IHttpProvider>(new HttpProvider(new EnvironmentProvider()));
Mocker.Resolve<DiskProvider>();
Mocker.Resolve<ArchiveProvider>();
StartUpdate();
updateSubFolder.Refresh();
Subject.InstallAvailableUpdate();
updateSubFolder.Refresh();
updateSubFolder.Exists.Should().BeTrue();
updateSubFolder.GetDirectories("nzbdrone").Should().HaveCount(1);
updateSubFolder.GetDirectories().Should().HaveCount(1);
updateSubFolder.GetFiles().Should().HaveCount(1);
}
private void StartUpdate()
{
Mocker.Resolve<AppUpdateJob>().Start(MockNotification, null);
updateSubFolder.GetFiles().Should().NotBeEmpty();
}
}
}

View file

@ -12,11 +12,11 @@ namespace NzbDrone.Core.Jobs.Implementations
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly DropFolderImportService _dropFolderImportService;
private readonly IDropFolderImportService _dropFolderImportService;
private readonly IConfigService _configService;
private readonly DiskProvider _diskProvider;
public PostDownloadScanJob(DropFolderImportService dropFolderImportService,IConfigService configService, DiskProvider diskProvider)
public PostDownloadScanJob(IDropFolderImportService dropFolderImportService,IConfigService configService, DiskProvider diskProvider)
{
_dropFolderImportService = dropFolderImportService;
_configService = configService;

View file

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq;
using NLog;
using NzbDrone.Core.Configuration;
using NzbDrone.Core.DataAugmentation;
using NzbDrone.Core.DataAugmentation.DailySeries;
using NzbDrone.Core.Helpers;
using NzbDrone.Core.Model.Notification;

View file

@ -1,94 +0,0 @@
using System;
using System.Linq;
using System.Diagnostics;
using System.IO;
using NLog;
using NzbDrone.Common;
using NzbDrone.Core.Jobs;
using NzbDrone.Core.Model.Notification;
using NzbDrone.Core.Providers;
using NzbDrone.Core.Update;
namespace NzbDrone.Core.Lifecycle
{
public class AppUpdateJob : IJob
{
private readonly UpdateService _updateService;
private readonly EnvironmentProvider _environmentProvider;
private readonly DiskProvider _diskProvider;
private readonly IHttpProvider _httpProvider;
private readonly ProcessProvider _processProvider;
private readonly ArchiveProvider _archiveProvider;
private readonly ConfigFileProvider _configFileProvider;
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public AppUpdateJob(UpdateService updateService, EnvironmentProvider environmentProvider, DiskProvider diskProvider,
IHttpProvider httpProvider, ProcessProvider processProvider, ArchiveProvider archiveProvider, ConfigFileProvider configFileProvider)
{
_updateService = updateService;
_environmentProvider = environmentProvider;
_diskProvider = diskProvider;
_httpProvider = httpProvider;
_processProvider = processProvider;
_archiveProvider = archiveProvider;
_configFileProvider = configFileProvider;
}
public string Name
{
get { return "Update Application Job"; }
}
public TimeSpan DefaultInterval
{
get { return TimeSpan.FromDays(2); }
}
public virtual void Start(ProgressNotification notification, dynamic options)
{
notification.CurrentMessage = "Checking for updates";
var updatePackage = _updateService.GetAvailableUpdate();
//No updates available
if (updatePackage == null)
return;
var packageDestination = Path.Combine(_environmentProvider.GetUpdateSandboxFolder(), updatePackage.FileName);
if (_diskProvider.FolderExists(_environmentProvider.GetUpdateSandboxFolder()))
{
logger.Info("Deleting old update files");
_diskProvider.DeleteFolder(_environmentProvider.GetUpdateSandboxFolder(), true);
}
logger.Info("Downloading update package from [{0}] to [{1}]", updatePackage.Url, packageDestination);
notification.CurrentMessage = "Downloading Update " + updatePackage.Version;
_httpProvider.DownloadFile(updatePackage.Url, packageDestination);
logger.Info("Download completed for update package from [{0}]", updatePackage.FileName);
logger.Info("Extracting Update package");
notification.CurrentMessage = "Extracting Update";
_archiveProvider.ExtractArchive(packageDestination, _environmentProvider.GetUpdateSandboxFolder());
logger.Info("Update package extracted successfully");
logger.Info("Preparing client");
notification.CurrentMessage = "Preparing to start Update";
_diskProvider.MoveDirectory(_environmentProvider.GetUpdateClientFolder(), _environmentProvider.GetUpdateSandboxFolder());
logger.Info("Starting update client");
var startInfo = new ProcessStartInfo
{
FileName = _environmentProvider.GetUpdateClientExePath(),
Arguments = string.Format("{0} {1}", _environmentProvider.NzbDroneProcessIdFromEnvironment, _configFileProvider.Guid)
};
var process = _processProvider.Start(startInfo);
notification.CurrentMessage = "Update in progress. NzbDrone will restart shortly.";
_processProvider.WaitForExit(process);
}
}
}

View file

@ -41,7 +41,7 @@ namespace NzbDrone.Core.MetadataSource
private static IRestClient BuildClient(string resource, string method)
{
return new RestClient(string.Format("http://api.trakt.tv/{0}/{1}.json/6fc98f83c6a02decd17eb7e13d00e89c", resource, method));
return new RestClient(string.Format("http://api.trakt.tv/{0}/{1}.json/bc3c2c460f22cbb01c264022b540e191", resource, method));
}
private static Series MapSeries(Show show)

View file

@ -392,7 +392,7 @@
<Compile Include="Providers\RecycleBinProvider.cs" />
<Compile Include="Tv\SeasonService.cs" />
<Compile Include="Instrumentation\TrimLogsJob.cs" />
<Compile Include="Lifecycle\AppUpdateJob.cs" />
<Compile Include="Update\AppUpdateJob.cs" />
<Compile Include="Model\Xbmc\TvShowResponse.cs" />
<Compile Include="Model\Xbmc\TvShow.cs" />
<Compile Include="Model\Xbmc\VersionResult.cs" />
@ -529,7 +529,7 @@
<Compile Include="Tv\SeriesStatusType.cs" />
<Compile Include="Update\UpdatePackageProvider.cs" />
<Compile Include="Update\UpdatePackage.cs" />
<Compile Include="Update\UpdateProvider.cs" />
<Compile Include="Update\UpdateService.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0,Profile=Client">

View file

@ -0,0 +1,31 @@
using System;
using NzbDrone.Core.Jobs;
using NzbDrone.Core.Model.Notification;
namespace NzbDrone.Core.Update
{
public class AppUpdateJob : IJob
{
private readonly IUpdateService _updateService;
public AppUpdateJob(IUpdateService updateService)
{
_updateService = updateService;
}
public string Name
{
get { return "Update Application Job"; }
}
public TimeSpan DefaultInterval
{
get { return TimeSpan.FromDays(2); }
}
public virtual void Start(ProgressNotification notification, dynamic options)
{
_updateService.InstallAvailableUpdate();
}
}
}

View file

@ -1,68 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using NLog;
using NzbDrone.Common;
using NzbDrone.Core.Update;
namespace NzbDrone.Core.Update
{
public interface IUpdateService
{
UpdatePackage GetAvailableUpdate();
Dictionary<DateTime, string> GetUpdateLogFiles();
}
}
public class UpdateService : IUpdateService
{
private readonly IUpdatePackageProvider _updatePackageProvider;
private readonly EnvironmentProvider _environmentProvider;
private readonly DiskProvider _diskProvider;
private readonly Logger _logger;
public UpdateService(IUpdatePackageProvider updatePackageProvider, EnvironmentProvider environmentProvider, DiskProvider diskProvider, Logger logger)
{
_updatePackageProvider = updatePackageProvider;
_environmentProvider = environmentProvider;
_diskProvider = diskProvider;
_logger = logger;
}
public UpdatePackage GetAvailableUpdate()
{
var latestAvailable = _updatePackageProvider.GetLatestUpdate();
if (latestAvailable != null && latestAvailable.Version > _environmentProvider.Version)
{
_logger.Debug("An update is available ({0}) => ({1})", _environmentProvider.Version, latestAvailable.Version);
return latestAvailable;
}
_logger.Trace("No updates available");
return null;
}
public Dictionary<DateTime, string> GetUpdateLogFiles()
{
var list = new Dictionary<DateTime, string>();
if (_diskProvider.FolderExists(_environmentProvider.GetUpdateLogFolder()))
{
var provider = CultureInfo.InvariantCulture;
var files = _diskProvider.GetFiles(_environmentProvider.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly).ToList();
foreach (var file in files.Select(c => new FileInfo(c)).OrderByDescending(c => c.Name))
{
list.Add(DateTime.ParseExact(file.Name.Replace(file.Extension, string.Empty), "yyyy.MM.dd-H-mm", provider), file.FullName);
}
}
return list;
}
}

View file

@ -0,0 +1,112 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using NLog;
using NzbDrone.Common;
using NzbDrone.Core.Update;
namespace NzbDrone.Core.Update
{
public interface IUpdateService
{
void InstallAvailableUpdate();
Dictionary<DateTime, string> GetUpdateLogFiles();
}
}
public class UpdateService : IUpdateService
{
private readonly IUpdatePackageProvider _updatePackageProvider;
private readonly EnvironmentProvider _environmentProvider;
private readonly DiskProvider _diskProvider;
private readonly IHttpProvider _httpProvider;
private readonly ConfigFileProvider _configFileProvider;
private readonly ArchiveProvider _archiveProvider;
private readonly ProcessProvider _processProvider;
private readonly Logger _logger;
public UpdateService(IUpdatePackageProvider updatePackageProvider, EnvironmentProvider environmentProvider, DiskProvider diskProvider,
IHttpProvider httpProvider, ConfigFileProvider configFileProvider, ArchiveProvider archiveProvider, ProcessProvider processProvider, Logger logger)
{
_updatePackageProvider = updatePackageProvider;
_environmentProvider = environmentProvider;
_diskProvider = diskProvider;
_httpProvider = httpProvider;
_configFileProvider = configFileProvider;
_archiveProvider = archiveProvider;
_processProvider = processProvider;
_logger = logger;
}
public void InstallAvailableUpdate()
{
var latestAvailable = _updatePackageProvider.GetLatestUpdate();
if (latestAvailable == null || latestAvailable.Version <= _environmentProvider.Version)
{
_logger.Debug("No update available.");
return;
}
InstallUpdate(latestAvailable);
}
private void InstallUpdate(UpdatePackage updatePackage)
{
var packageDestination = Path.Combine(_environmentProvider.GetUpdateSandboxFolder(), updatePackage.FileName);
if (_diskProvider.FolderExists(_environmentProvider.GetUpdateSandboxFolder()))
{
_logger.Info("Deleting old update files");
_diskProvider.DeleteFolder(_environmentProvider.GetUpdateSandboxFolder(), true);
}
_logger.Info("Downloading update package from [{0}] to [{1}]", updatePackage.Url, packageDestination);
_httpProvider.DownloadFile(updatePackage.Url, packageDestination);
_logger.Info("Download completed for update package from [{0}]", updatePackage.FileName);
_logger.Info("Extracting Update package");
_archiveProvider.ExtractArchive(packageDestination, _environmentProvider.GetUpdateSandboxFolder());
_logger.Info("Update package extracted successfully");
_logger.Info("Preparing client");
_diskProvider.MoveDirectory(_environmentProvider.GetUpdateClientFolder(), _environmentProvider.GetUpdateSandboxFolder());
_logger.Info("Starting update client");
var startInfo = new ProcessStartInfo
{
FileName = _environmentProvider.GetUpdateClientExePath(),
Arguments = string.Format("{0} {1}", _processProvider.GetCurrentProcess().Id, _configFileProvider.Guid)
};
var process = _processProvider.Start(startInfo);
_processProvider.WaitForExit(process);
}
public Dictionary<DateTime, string> GetUpdateLogFiles()
{
var list = new Dictionary<DateTime, string>();
if (_diskProvider.FolderExists(_environmentProvider.GetUpdateLogFolder()))
{
var provider = CultureInfo.InvariantCulture;
var files = _diskProvider.GetFiles(_environmentProvider.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly).ToList();
foreach (var file in files.Select(c => new FileInfo(c)).OrderByDescending(c => c.Name))
{
list.Add(DateTime.ParseExact(file.Name.Replace(file.Extension, string.Empty), "yyyy.MM.dd-H-mm", provider), file.FullName);
}
}
return list;
}
}

View file

@ -0,0 +1,13 @@
using NUnit.Framework;
namespace NzbDrone.Test.Common
{
public class IntegrationTestAttribute : CategoryAttribute
{
public IntegrationTestAttribute()
: base("Integration Test")
{
}
}
}

View file

@ -88,6 +88,7 @@
<Compile Include="AutoMoq\Unity\AutoMockingBuilderStrategy.cs" />
<Compile Include="AutoMoq\Unity\AutoMockingContainerExtension.cs" />
<Compile Include="ExceptionVerification.cs" />
<Compile Include="IntegrationTest.cs" />
<Compile Include="LoggingTest.cs" />
<Compile Include="MockerExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />

View file

@ -37,8 +37,6 @@ namespace NzbDrone.Test.Common
public abstract class TestBase : LoggingTest
{
protected const string INTEGRATION_TEST = "Integration Test";
private AutoMoqer _mocker;
protected AutoMoqer Mocker
{