Skip to content

Commit

Permalink
Merge pull request #40 from absynce/console-logging
Browse files Browse the repository at this point in the history
Console logging
  • Loading branch information
absynce authored Jun 20, 2016
2 parents ce1fbbb + 779d599 commit a442754
Show file tree
Hide file tree
Showing 14 changed files with 363 additions and 117 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ All notable changes will be documented in this file, particularly any breaking
changes. This project adheres to [Semantic Versioning](http://semver.org).

## [x.x.x]
- Added - Option to configure a `RavenMigration.ILogger` or use the `ConsoleLogger`.

## [2.0.0]
- Changed (breaking) - The way the MigrationDocument's Id is determined. Multiple underscores
Expand Down
134 changes: 94 additions & 40 deletions RavenMigrations.Tests/AlterTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using System.Collections.Generic;
using FluentAssertions;
using Raven.Abstractions.Commands;
using System.Collections.Generic;
using FluentAssertions;
using Raven.Abstractions.Commands;
using Raven.Abstractions.Data;
using Raven.Client;
using Raven.Client.Indexes;
using Raven.Json.Linq;
using Raven.Tests.Helpers;
using Moq;
using Xunit;

namespace RavenMigrations.Tests
Expand All @@ -20,7 +21,7 @@ public void Can_migrate_down_from_new_clr_type()
InitialiseWithPerson(store, "Sean Kearon");

var migration = new AlterCollectionMigration();
migration.Setup(store);
migration.Setup(store, new NullLogger());

migration.Up();
WaitForIndexing(store);
Expand All @@ -44,7 +45,7 @@ public void Can_migrate_up_to_new_clr_type()
InitialiseWithPerson(store, "Sean Kearon");

var migration = new AlterCollectionMigration();
migration.Setup(store);
migration.Setup(store, new NullLogger());

migration.Up();
using (var session = store.OpenSession())
Expand All @@ -54,28 +55,70 @@ public void Can_migrate_up_to_new_clr_type()
customer.LastName.Should().Be("Kearon");
}
}
}

[Fact]
public void Can_add_additional_commands_as_part_of_migration()
{
}

[Fact]
public void Can_add_additional_commands_as_part_of_migration()
{
using (var store = NewDocumentStore())
{
InitialiseWithPerson(store, "Sean Kearon");

var migration = new AlterCollectionMigration();
migration.Setup(store);
migration.Setup(store, new NullLogger());

migration.Up();

using (var session = store.OpenSession())
{
var foobaz = session.Load<FooBaz>(1);
foobaz.Bar.Should().BeEquivalentTo("loaded");
var foobaz = session.Load<FooBaz>(1);
foobaz.Bar.Should().BeEquivalentTo("loaded");
}
}
}

[Fact]
public void Logger_WriteInformation_is_called_when_altering_collection()
{
var loggerMock = new Mock<ILogger>();

using (var store = NewDocumentStore())
{
InitialiseWithPerson(store, "Sean Kearon");

var migration = new AlterCollectionMigration();
migration.Setup(store, loggerMock.Object);

migration.Up();
}

loggerMock.Verify(logger => logger.WriteInformation("Updated {0} documents", 1), "Informational message should indicate how many documents were updated.");
}

[Fact]
public void Logger_WriteInformation_is_called_per_batch_when_altering_collection()
{
var loggerMock = new Mock<ILogger>();

using (var store = NewDocumentStore())
{
InitialiseWithPeople(store, new List<Person1>() {
new Person1 {Name = "Sean Kearon"},
new Person1 {Name = "Jared M. Smith"},
new Person1 {Name = "Michael Owen"},
new Person1 {Name = "Jonathan Skelton"},
new Person1 {Name = "Matt King"}
});
var migration = new AlterCollectionMigration();
migration.Setup(store, loggerMock.Object);

migration.Up();
}

loggerMock.Verify(logger => logger.WriteInformation("Updated {0} documents", 2), Times.Exactly(2), "Informational message should indicate how many documents were updated.");
loggerMock.Verify(logger => logger.WriteInformation("Updated {0} documents", 1), Times.Once, "Informational message should indicate how many documents were updated.");
}

private void InitialiseWithPerson(IDocumentStore store, string name)
{
new RavenDocumentsByEntityName().Execute(store); //https://groups.google.com/forum/#!topic/ravendb/QqZPrRUwEkE
Expand All @@ -86,6 +129,17 @@ private void InitialiseWithPerson(IDocumentStore store, string name)
}
WaitForIndexing(store);
}

private void InitialiseWithPeople(IDocumentStore store, List<Person1> people)
{
new RavenDocumentsByEntityName().Execute(store); //https://groups.google.com/forum/#!topic/ravendb/QqZPrRUwEkE
using (var session = store.OpenSession())
{
people.ForEach(session.Store);
session.SaveChanges();
}
WaitForIndexing(store);
}
}

[Migration(1, "alter")]
Expand All @@ -98,7 +152,7 @@ public override void Down()

public override void Up()
{
Alter.CollectionWithAdditionalCommands("Person1s", MigratePerson1ToPerson2);
Alter.CollectionWithAdditionalCommands("Person1s", MigratePerson1ToPerson2, 2);
}

private void MigratePerson2ToPerson1(RavenJObject doc, RavenJObject metadata)
Expand All @@ -110,7 +164,7 @@ private void MigratePerson2ToPerson1(RavenJObject doc, RavenJObject metadata)
doc.Remove("FirstName");
doc.Remove("LastName");

metadata[Constants.RavenClrType] = "RavenMigrations.Tests.Person1, RavenMigrations.Tests";
metadata[Constants.RavenClrType] = "RavenMigrations.Tests.Person1, RavenMigrations.Tests";
}

private IEnumerable<ICommandData> MigratePerson1ToPerson2(RavenJObject doc, RavenJObject metadata)
Expand All @@ -123,32 +177,32 @@ private IEnumerable<ICommandData> MigratePerson1ToPerson2(RavenJObject doc, Rave
}
doc.Remove("Name");

metadata[Constants.RavenClrType] = "RavenMigrations.Tests.Person2, RavenMigrations.Tests";

var foobaz = new FooBaz
{
Id = 1,
Bar = "loaded"
};

var foobazDoc = RavenJObject.FromObject(foobaz);
var meta = new RavenJObject();
meta[Constants.RavenEntityName] = "FooBazs";
var cmd = new PutCommandData
{
Document = foobazDoc,
Key = "foobazs/" + foobaz.Id,
Metadata = meta
};

return new[] {cmd};
metadata[Constants.RavenClrType] = "RavenMigrations.Tests.Person2, RavenMigrations.Tests";

var foobaz = new FooBaz
{
Id = 1,
Bar = "loaded"
};

var foobazDoc = RavenJObject.FromObject(foobaz);
var meta = new RavenJObject();
meta[Constants.RavenEntityName] = "FooBazs";
var cmd = new PutCommandData
{
Document = foobazDoc,
Key = "foobazs/" + foobaz.Id,
Metadata = meta
};

return new[] {cmd};
}
}

public class FooBaz
{
public int Id { get; set; }
public string Bar { get; set; }
}

public class FooBaz
{
public int Id { get; set; }
public string Bar { get; set; }
}

public class Person1
Expand Down
15 changes: 15 additions & 0 deletions RavenMigrations.Tests/RavenMigrations.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\xunit.runner.visualstudio.2.1.0\build\net20\xunit.runner.visualstudio.props" Condition="Exists('..\packages\xunit.runner.visualstudio.2.1.0\build\net20\xunit.runner.visualstudio.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
Expand Down Expand Up @@ -32,6 +33,10 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Castle.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\packages\Castle.Core.3.3.3\lib\net45\Castle.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="FluentAssertions">
<HintPath>..\packages\FluentAssertions.2.1.0.0\lib\net45\FluentAssertions.dll</HintPath>
</Reference>
Expand All @@ -49,6 +54,10 @@
<Reference Include="Microsoft.WindowsAzure.Storage, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\WindowsAzure.Storage.2.0.6.1\lib\net40\Microsoft.WindowsAzure.Storage.dll</HintPath>
</Reference>
<Reference Include="Moq, Version=4.5.9.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\packages\Moq.4.5.9\lib\net45\Moq.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Raven.Abstractions">
<HintPath>..\packages\RavenDB.Client.2.5.2700\lib\net45\Raven.Abstractions.dll</HintPath>
</Reference>
Expand Down Expand Up @@ -101,6 +110,12 @@
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\xunit.runner.visualstudio.2.1.0\build\net20\xunit.runner.visualstudio.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\xunit.runner.visualstudio.2.1.0\build\net20\xunit.runner.visualstudio.props'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
Expand Down
52 changes: 51 additions & 1 deletion RavenMigrations.Tests/RunnerTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Linq;
using FluentAssertions;
using Moq;
using Raven.Abstractions.Data;
using Raven.Client;
using Raven.Client.Indexes;
using Raven.Tests.Helpers;
using Xunit;
Expand Down Expand Up @@ -284,6 +286,52 @@ public void Can_call_migrations_with_custom_attributes()
}
}
}

public class Logger
{
public class WhenMigrationRunUp : RavenTestBase
{
[Fact]
public void Logger_WriteInformation_should_be_called_before_and_after_migration()
{
var mockLogger = new Mock<ILogger>();

using (var store = NewDocumentStore())
{
Runner.Run(store, new MigrationOptions { Logger = mockLogger.Object });
}

mockLogger.Verify(logger => logger.WriteInformation("{0}: Up migration started", typeof(First_Migration).Name), Times.AtLeastOnce, "Informational message should indicate Up migration started.");
mockLogger.Verify(logger => logger.WriteInformation("{0}: Up migration completed", typeof(First_Migration).Name), Times.AtLeastOnce, "Informational message should indicate Up migration started.");
}
}

public class WhenMigrationRunDown : RavenTestBase
{
[Fact]
public void Logger_WriteInformation_should_be_called_before_and_after_migration()
{
var mockLogger = new Mock<ILogger>();

using (var store = NewDocumentStore())
{
new TestDocumentIndex().Execute(store);

Runner.Run(store);
WaitForIndexing(store);

Runner.Run(store, new MigrationOptions
{
Direction = Directions.Down,
Logger = mockLogger.Object
});
}

mockLogger.Verify(logger => logger.WriteInformation("{0}: Down migration started", typeof(First_Migration).Name), Times.AtLeastOnce, "Informational message should indicate Up migration started.");
mockLogger.Verify(logger => logger.WriteInformation("{0}: Down migration completed", typeof(First_Migration).Name), Times.AtLeastOnce, "Informational message should indicate Up migration started.");
}
}
}
}

public class TestDocument
Expand Down Expand Up @@ -388,7 +436,9 @@ public override void Up()
session.SaveChanges();
}
}
}
}



public abstract class BaseMigration : Migration
{
Expand Down
3 changes: 3 additions & 0 deletions RavenMigrations.Tests/packages.config
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="3.3.3" targetFramework="net45" />
<package id="FluentAssertions" version="2.1.0.0" targetFramework="net45" />
<package id="Microsoft.Data.Edm" version="5.2.0" targetFramework="net45" />
<package id="Microsoft.Data.OData" version="5.2.0" targetFramework="net45" />
<package id="Microsoft.WindowsAzure.ConfigurationManager" version="1.8.0.0" targetFramework="net45" />
<package id="Moq" version="4.5.9" targetFramework="net45" />
<package id="RavenDB.Client" version="2.5.2700" targetFramework="net45" />
<package id="RavenDB.Database" version="2.5.2700" targetFramework="net45" />
<package id="RavenDB.Embedded" version="2.5.2700" targetFramework="net45" />
<package id="RavenDB.Tests.Helpers" version="2.5.2700" targetFramework="net45" />
<package id="System.Spatial" version="5.2.0" targetFramework="net45" />
<package id="WindowsAzure.Storage" version="2.0.6.1" targetFramework="net45" />
<package id="xunit" version="1.9.2" targetFramework="net45" />
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" />
</packages>
44 changes: 44 additions & 0 deletions RavenMigrations/ConsoleLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;

namespace RavenMigrations
{
public class ConsoleLogger : ILogger
{
/// <summary>
/// Writes an informational message to the log.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public void WriteInformation(string format, params object[] args)
{
Write(ConsoleColor.White, format, args);
}

/// <summary>
/// Writes an error message to the log.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public void WriteError(string format, params object[] args)
{
Write(ConsoleColor.Red, format, args);
}

/// <summary>
/// Writes a warning message to the log.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
public void WriteWarning(string format, params object[] args)
{
Write(ConsoleColor.Yellow, format, args);
}

private static void Write(ConsoleColor color, string format, object[] args)
{
Console.ForegroundColor = color;
Console.WriteLine(format, args);
Console.ResetColor();
}
}
}
Loading

0 comments on commit a442754

Please sign in to comment.