Skip to content

Instantly share code, notes, and snippets.

@dlidstrom
Last active August 29, 2015 13:56
Show Gist options
  • Save dlidstrom/9051827 to your computer and use it in GitHub Desktop.
Save dlidstrom/9051827 to your computer and use it in GitHub Desktop.
public static class ContextFactory
{
public static ICommandQueryContext CreateContext()
{
// this environment variable determines if we are running inside TeamCity
if (Environment.GetEnvironmentVariable("TEAMCITY_PROJECT_NAME") == null)
return new InMemoryContext();
// we are inside TeamCity, use a database with unique name
// that includes test method and test class
const string DataSource = @"Data Source=xxxxxxxx";
var now = DateTime.Now;
var databaseName = string.Format(
"SomeProjectName-{0}-{1}",
GuessTestName(),
now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
var initialCatalog = string.Format("Initial Catalog={0}", databaseName);
const string IntegratedSecurity = "Integrated Security=True";
var connectionString = string.Join(
";",
new[] { DataSource, initialCatalog, IntegratedSecurity });
return new MainDataContext(connectionString, true);
}
private static string GuessTestName()
{
var stackTrace = new StackTrace();
var stackFrames = stackTrace.GetFrames();
if (stackFrames == null) return string.Empty;
foreach (var stackFrame in stackFrames)
{
var method = stackFrame.GetMethod();
var attributes = method.GetCustomAttributes(false);
foreach (var attribute in attributes)
{
if (attribute is TestAttribute && method.ReflectedType != null)
{
var name = string.Format("{0}_{1}", method.ReflectedType.Name, method.Name);
return name;
}
}
}
return string.Empty;
}
}
public class IntegrationTestAttribute : CategoryAttribute
{
public IntegrationTestAttribute()
: base("IntegrationTest")
{
}
}
[IntegrationTest]
public abstract class IntegrationTest
{
private ICommandQueryContext Context { get; set; }
[SetUp]
public void SetUp()
{
OnSetUp();
}
[TearDown]
public void TearDown()
{
OnTearDown();
Context.Dispose();
Context = null;
}
protected void Transact(Action<ICommandQueryContext> action)
{
if (action == null) throw new ArgumentNullException("action");
Transact(context =>
{
action.Invoke(context);
return false;
});
}
protected TResult Transact<TResult>(Func<ICommandQueryContext, TResult> func)
{
if (func == null) throw new ArgumentNullException("func");
var context = GetContext();
var result = func.Invoke(context);
context.SaveChanges();
return result;
}
protected virtual void OnSetUp()
{
}
protected virtual void OnTearDown()
{
}
private ICommandQueryContext GetContext()
{
return Context ?? (Context = ContextFactory.CreateContext());
}
}
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server") "xxxxxxxx"
$today = Get-Date
$databasesToDrop = New-Object Collections.Generic.List["Microsoft.SqlServer.Management.Smo.Database"];
foreach ($database in $server.Databases)
{
$databaseName = $database.Name
# the following will match databases with names that look like: SomeProjectName-SampleDbTest_PersistsData-2014-02-10T14:03:22.123
if ($databaseName -match "SomeProjectName-(.*_.*)?-(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}).(?<millisecond>\d{3})")
{
$creationDate = Get-Date `
-Year $Matches["year"] `
-Month $Matches["month"] `
-Day $Matches["day"] `
-Hour $Matches["hour"] `
-Minute $Matches["minute"] `
-Second $Matches["second"] `
-Millisecond $Matches["millisecond"]
$age = $today - $creationDate;
Write-Host $age $today $creationDate.ToString("yyyy-MM-ddTHH:mm:ss.fff")
$totalDays = [System.Math]::Floor($age.TotalDays);
if ($totalDays -ge 7)
{
$databasesToDrop.Add($database);
}
else
{
Write-Host "${databaseName} age (${totalDays} days) is not yet 7 days, keeping it"
}
}
else
{
Write-Host "${databaseName} is not an integration test database"
}
}
foreach ($databaseToDrop in $databasesToDrop)
{
$databaseName = $databaseToDrop.Name
Write-Host "Dropping ${databaseName}"
$databaseToDrop.Drop()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment