Edit Data Service (#241)

This is a very large change. I'll try to outline what's going on.

1. This adds the **EditDataService** which manages editing **Sessions**.
    1. Each session has a **ResultSet** (from the QueryExecutionService) which has the rows of the table and basic metadata about the columns 
    2. Each session also has an **IEditTableMetadata** implementation which is derived from SMO metadata which provides more in-depth and trustworthy data about the table than SqlClient alone can.
    3. Each session holds a list of **RowEditBase** abstract class implementations
        1. **RowUpdate** - Update cells in a row (generates `UPDATE` statement)
        2. **RowDelete** - Delete an entire row (generates `DELETE` statement)
        3. **RowCreate** - Add a new row (generates `INSERT INTO` statement)
    4. Row edits have a collection of **CellUpdates** that hold updates for individual cells (except for RowDelete)
        1. Cell updates are generated from text
     5. RowEditBase offers some baseline functionality
        1. Generation of `WHERE` clauses (which can be parameterized)
        2. Validation of whether a column can be updated
2. New API Actions
    1. edit/initialize - Queries for the contents of a table/view, builds SMO metadata, sets up a session
    2. edit/createRow - Adds a new RowCreate to the Session
    3. edit/deleteRow - Adds a new RowDelete to the Session
    4. edit/updateCell - Adds a CellUpdate to a RowCreate or RowUpdate in the Session
    5. edit/revertRow - Removes a RowCreate, RowDelete, or RowUpdate from the Session
    6. edit/script - Generates a script for the changes in the Session and stores to disk
    7. edit/dispose - Removes a Session and releases the query
3. Smaller updates (unit test mock improvements, tweaks to query execution service)

**There are more updates planned -- this is just to get eyeballs on the main body of code**

* Initial stubs for edit data service

* Stubbing out update management code

* Adding rudimentary dispose request

* More stubbing out of update row code

* Adding complete edit command contracts, stubbing out request handlers

* Adding basic implementation of get script

* More in progress work to implement base of row edits

* More in progress work to implement base of row edits

* Adding string => object conversion logic and various cleanup

* Adding a formatter for using values in scripts

* Splitting IMessageSender into IEventSender and IRequestSender

* Adding inter-service method for executing queries

* Adding inter-service method for disposing of a query

* Changing edit contract to include the object to edit

* Fully fleshing out edit session initialization

* Generation of delete scripts is working

* Adding scripter for update statements

* Adding scripting functionality for INSERT statements

* Insert, Update, and Delete all working with SMO metadata

* Polishing for SqlScriptFormatter

* Unit tests and reworked byte[] conversion

* Replacing the awful and inflexible Dictionary<string, string>[][] with a much better test data set class

* Fixing syntax error in generated UPDATE statements

* Adding unit tests for RowCreate

* Adding tests for the row edit base class

* Adding row delete tests

* Adding RowUpdate tests, validation for number of key columns

* Adding tests for the unit class

* Adding get script tests for the session

* Service integration tests, except initialization tests

* Service integration tests, except initialization tests

* Adding messages to sr.strings

* Adding messages to sr.strings

* Fixing broken unit tests

* Adding factory pattern for SMO metadata provider

* Copyright and other comments

* Addressing first round of comments

* Refactoring EditDataService to have a single method for handling
session-dependent operations
* Refactoring Edit Data contracts to inherit from a Session and Row
operation params base class
* Copyright additions
* Small tweak to strings
* Updated unit tests to test the refactors

* More revisions as per pull request comments
This commit is contained in:
Benjamin Russell
2017-02-22 17:32:57 -08:00
committed by GitHub
parent 2b15890b00
commit 795eba3da6
49 changed files with 4370 additions and 137 deletions

View File

@@ -0,0 +1,208 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Data.Common;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
public class CellUpdateTests
{
[Fact]
public void NullColumnTest()
{
// If: I attempt to create a CellUpdate with a null column
// Then: I should get an exception thrown
Assert.Throws<ArgumentNullException>(() => new CellUpdate(null, string.Empty));
}
[Fact]
public void NullStringValueTest()
{
// If: I attempt to create a CellUpdate with a null string value
// Then: I should get an exception thrown
Assert.Throws<ArgumentNullException>(() => new CellUpdate(new CellUpdateTestDbColumn(null), null));
}
[Fact]
public void NullStringTest()
{
// If: I attempt to create a CellUpdate to set it to NULL (with mixed cases)
const string nullString = "NULL";
DbColumn col = new CellUpdateTestDbColumn(typeof(string));
CellUpdate cu = new CellUpdate(col, nullString);
// Then: The value should be a DBNull and the string value should be the same as what
// was given
Assert.IsType<DBNull>(cu.Value);
Assert.Equal(DBNull.Value, cu.Value);
Assert.Equal(nullString, cu.ValueAsString);
Assert.Equal(col, cu.Column);
}
[Fact]
public void NullTextStringTest()
{
// If: I attempt to create a CellUpdate with the text 'NULL' (with mixed case)
DbColumn col = new CellUpdateTestDbColumn(typeof(string));
CellUpdate cu = new CellUpdate(col, "'NULL'");
// Then: The value should be NULL
Assert.IsType<string>(cu.Value);
Assert.Equal("NULL", cu.Value);
Assert.Equal("'NULL'", cu.ValueAsString);
Assert.Equal(col, cu.Column);
}
[Theory]
[MemberData(nameof(ByteArrayTestParams))]
public void ByteArrayTest(string strValue, byte[] expectedValue, string expectedString)
{
// If: I attempt to create a CellUpdate for a binary column
DbColumn col = new CellUpdateTestDbColumn(typeof(byte[]));
CellUpdate cu = new CellUpdate(col, strValue);
// Then: The value should be a binary and should match the expected data
Assert.IsType<byte[]>(cu.Value);
Assert.Equal(expectedValue, cu.Value);
Assert.Equal(expectedString, cu.ValueAsString);
Assert.Equal(col, cu.Column);
}
public static IEnumerable<object> ByteArrayTestParams
{
get
{
// All zero tests
yield return new object[] {"00000000", new byte[] {0x00}, "0x00"}; // Base10
yield return new object[] {"0x000000", new byte[] {0x00, 0x00, 0x00}, "0x000000"}; // Base16
yield return new object[] {"0x000", new byte[] {0x00, 0x00}, "0x0000"}; // Base16, odd
// Single byte tests
yield return new object[] {"50", new byte[] {0x32}, "0x32"}; // Base10
yield return new object[] {"050", new byte[] {0x32}, "0x32"}; // Base10, leading zeros
yield return new object[] {"0xF0", new byte[] {0xF0}, "0xF0"}; // Base16
yield return new object[] {"0x0F", new byte[] {0x0F}, "0x0F"}; // Base16, leading zeros
yield return new object[] {"0xF", new byte[] {0x0F}, "0x0F"}; // Base16, odd
// Two byte tests
yield return new object[] {"1000", new byte[] {0x03, 0xE8}, "0x03E8"}; // Base10
yield return new object[] {"01000", new byte[] {0x03, 0xE8}, "0x03E8"}; // Base10, leading zeros
yield return new object[] {"0xF001", new byte[] {0xF0, 0x01}, "0xF001"}; // Base16
yield return new object[] {"0x0F10", new byte[] {0x0F, 0x10}, "0x0F10"}; // Base16, leading zeros
yield return new object[] {"0xF10", new byte[] {0x0F, 0x10}, "0x0F10"}; // Base16, odd
// Three byte tests
yield return new object[] {"100000", new byte[] {0x01, 0x86, 0xA0}, "0x0186A0"}; // Base10
yield return new object[] {"0100000", new byte[] {0x01, 0x86, 0xA0}, "0x0186A0"}; // Base10, leading zeros
yield return new object[] {"0x101010", new byte[] {0x10, 0x10, 0x10}, "0x101010"}; // Base16
yield return new object[] {"0x010101", new byte[] {0x01, 0x01, 0x01}, "0x010101"}; // Base16, leading zeros
yield return new object[] {"0x10101", new byte[] {0x01, 0x01, 0x01}, "0x010101"}; // Base16, odd
// Four byte tests
yield return new object[] {"20000000", new byte[] {0x01, 0x31, 0x2D, 0x00}, "0x01312D00"}; // Base10
yield return new object[] {"020000000", new byte[] {0x01, 0x31, 0x2D, 0x00}, "0x01312D00"}; // Base10, leading zeros
yield return new object[] {"0xF0F00101", new byte[] {0xF0, 0xF0, 0x01, 0x01}, "0xF0F00101"}; // Base16
yield return new object[] {"0x0F0F1010", new byte[] {0x0F, 0x0F, 0x10, 0x10}, "0x0F0F1010"}; // Base16, leading zeros
yield return new object[] {"0xF0F1010", new byte[] {0x0F, 0x0F, 0x10, 0x10}, "0x0F0F1010"}; // Base16, odd
}
}
[Fact]
public void ByteArrayInvalidFormatTest()
{
// If: I attempt to create a CellUpdate for a binary column
// Then: It should throw an exception
DbColumn col = new CellUpdateTestDbColumn(typeof(byte[]));
Assert.Throws<FormatException>(() => new CellUpdate(col, "this is totally invalid"));
}
[Theory]
[MemberData(nameof(BoolTestParams))]
public void BoolTest(string input, bool output, string outputString)
{
// If: I attempt to create a CellUpdate for a boolean column
DbColumn col = new CellUpdateTestDbColumn(typeof(bool));
CellUpdate cu = new CellUpdate(col, input);
// Then: The value should match what was expected
Assert.IsType<bool>(cu.Value);
Assert.Equal(output, cu.Value);
Assert.Equal(outputString, cu.ValueAsString);
Assert.Equal(col, cu.Column);
}
public static IEnumerable<object> BoolTestParams
{
get
{
yield return new object[] {"1", true, bool.TrueString};
yield return new object[] {"0", false, bool.FalseString};
yield return new object[] {bool.TrueString, true, bool.TrueString};
yield return new object[] {bool.FalseString, false, bool.FalseString};
}
}
[Fact]
public void BoolInvalidFormatTest()
{
// If: I create a CellUpdate for a bool column and provide an invalid numeric value
// Then: It should throw an exception
DbColumn col = new CellUpdateTestDbColumn(typeof(bool));
Assert.Throws<ArgumentOutOfRangeException>(() => new CellUpdate(col, "12345"));
}
[Theory]
[MemberData(nameof(RoundTripTestParams))]
public void RoundTripTest(Type dbColType, object obj)
{
// Setup: Figure out the test string
string testString = obj.ToString();
// If: I attempt to create a CellUpdate for a GUID column
DbColumn col = new CellUpdateTestDbColumn(dbColType);
CellUpdate cu = new CellUpdate(col, testString);
// Then: The value and type should match what we put in
Assert.IsType(dbColType, cu.Value);
Assert.Equal(obj, cu.Value);
Assert.Equal(testString, cu.ValueAsString);
Assert.Equal(col, cu.Column);
}
public static IEnumerable<object> RoundTripTestParams
{
get
{
yield return new object[] {typeof(Guid), Guid.NewGuid()};
yield return new object[] {typeof(TimeSpan), new TimeSpan(0, 1, 20, 0, 123)};
yield return new object[] {typeof(DateTime), new DateTime(2016, 04, 25, 9, 45, 0)};
yield return new object[]
{
typeof(DateTimeOffset),
new DateTimeOffset(2016, 04, 25, 9, 45, 0, TimeSpan.FromHours(8))
};
yield return new object[] {typeof(long), 1000L};
yield return new object[] {typeof(decimal), new decimal(3.14)};
yield return new object[] {typeof(int), 1000};
yield return new object[] {typeof(short), (short) 1000};
yield return new object[] {typeof(byte), (byte) 5};
yield return new object[] {typeof(double), 3.14d};
yield return new object[] {typeof(float), 3.14f};
}
}
private class CellUpdateTestDbColumn : DbColumn
{
public CellUpdateTestDbColumn(Type dataType)
{
DataType = dataType;
}
}
}
}

View File

@@ -0,0 +1,93 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading;
using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.QueryExecution.Contracts;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Microsoft.SqlTools.ServiceLayer.Utility;
using Moq;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
public class Common
{
public const string OwnerUri = "testFile";
public static IEditTableMetadata GetMetadata(DbColumn[] columns, bool allKeys = true, bool isMemoryOptimized = false)
{
// Create a Column Metadata Provider
var columnMetas = columns.Select((c, i) =>
new EditColumnWrapper
{
DbColumn = new DbColumnWrapper(c),
EscapedName = c.ColumnName,
Ordinal = i,
IsKey = c.IsIdentity.HasTrue()
}).ToArray();
// Create a table metadata provider
var tableMetaMock = new Mock<IEditTableMetadata>();
if (allKeys)
{
// All columns should be returned as "keys"
tableMetaMock.Setup(m => m.KeyColumns).Returns(columnMetas);
}
else
{
// All identity columns should be returned as keys
tableMetaMock.Setup(m => m.KeyColumns).Returns(columnMetas.Where(c => c.DbColumn.IsIdentity.HasTrue()));
}
tableMetaMock.Setup(m => m.Columns).Returns(columnMetas);
tableMetaMock.Setup(m => m.IsMemoryOptimized).Returns(isMemoryOptimized);
tableMetaMock.Setup(m => m.EscapedMultipartName).Returns("tbl");
return tableMetaMock.Object;
}
public static DbColumn[] GetColumns(bool includeIdentity)
{
List<DbColumn> columns = new List<DbColumn>();
if (includeIdentity)
{
columns.Add(new TestDbColumn("id", true));
}
for (int i = 0; i < 3; i++)
{
columns.Add(new TestDbColumn($"col{i}"));
}
return columns.ToArray();
}
public static ResultSet GetResultSet(DbColumn[] columns, bool includeIdentity)
{
object[][] rows = includeIdentity
? new[] { new object[] { "id", "1", "2", "3" } }
: new[] { new object[] { "1", "2", "3" } };
var testResultSet = new TestResultSet(columns, rows);
var reader = new TestDbDataReader(new[] { testResultSet });
var resultSet = new ResultSet(reader, 0, 0, QueryExecution.Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
resultSet.ReadResultToEnd(CancellationToken.None).Wait();
return resultSet;
}
public static void AddCells(RowEditBase rc, bool includeIdentity)
{
// Skip the first column since if identity, since identity columns can't be updated
int start = includeIdentity ? 1 : 0;
for (int i = start; i < rc.AssociatedResultSet.Columns.Length; i++)
{
rc.SetCell(i, "123");
}
}
}
}

View File

@@ -0,0 +1,84 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Data.Common;
using System.Text.RegularExpressions;
using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
public class RowCreateTests
{
[Fact]
public void RowCreateConstruction()
{
// Setup: Create the values to store
const long rowId = 100;
ResultSet rs = QueryExecution.Common.GetBasicExecutedBatch().ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
// If: I create a RowCreate instance
RowCreate rc = new RowCreate(rowId, rs, etm);
// Then: The values I provided should be available
Assert.Equal(rowId, rc.RowId);
Assert.Equal(rs, rc.AssociatedResultSet);
Assert.Equal(etm, rc.AssociatedObjectMetadata);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void GetScript(bool includeIdentity)
{
// Setup: Generate the parameters for the row create
const long rowId = 100;
DbColumn[] columns = Common.GetColumns(includeIdentity);
ResultSet rs = Common.GetResultSet(columns, includeIdentity);
IEditTableMetadata etm = Common.GetMetadata(columns);
// If: I ask for a script to be generated without an identity column
RowCreate rc = new RowCreate(rowId, rs, etm);
Common.AddCells(rc, includeIdentity);
string script = rc.GetScript();
// Then:
// ... The script should not be null,
Assert.NotNull(script);
// ... It should be formatted as an insert script
Regex r = new Regex(@"INSERT INTO (.+)\((.*)\) VALUES \((.*)\)");
var m = r.Match(script);
Assert.True(m.Success);
// ... It should have 3 columns and 3 values (regardless of the presence of an identity col)
string tbl = m.Groups[1].Value;
string cols = m.Groups[2].Value;
string vals = m.Groups[3].Value;
Assert.Equal(etm.EscapedMultipartName, tbl);
Assert.Equal(3, cols.Split(',').Length);
Assert.Equal(3, vals.Split(',').Length);
}
[Fact]
public void GetScriptMissingCell()
{
// Setup: Generate the parameters for the row create
const long rowId = 100;
DbColumn[] columns = Common.GetColumns(false);
ResultSet rs = Common.GetResultSet(columns, false);
IEditTableMetadata etm = Common.GetMetadata(columns);
// If: I ask for a script to be generated without setting any values
// Then: An exception should be thrown for missing cells
RowCreate rc = new RowCreate(rowId, rs, etm);
Assert.Throws<InvalidOperationException>(() => rc.GetScript());
}
}
}

View File

@@ -0,0 +1,73 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Data.Common;
using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
public class RowDeleteTests
{
[Fact]
public void RowDeleteConstruction()
{
// Setup: Create the values to store
const long rowId = 100;
ResultSet rs = QueryExecution.Common.GetBasicExecutedBatch().ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
// If: I create a RowCreate instance
RowCreate rc = new RowCreate(rowId, rs, etm);
// Then: The values I provided should be available
Assert.Equal(rowId, rc.RowId);
Assert.Equal(rs, rc.AssociatedResultSet);
Assert.Equal(etm, rc.AssociatedObjectMetadata);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void GetScriptTest(bool isHekaton)
{
DbColumn[] columns = Common.GetColumns(true);
ResultSet rs = Common.GetResultSet(columns, true);
IEditTableMetadata etm = Common.GetMetadata(columns, false, isHekaton);
// If: I ask for a script to be generated for delete
RowDelete rd = new RowDelete(0, rs, etm);
string script = rd.GetScript();
// Then:
// ... The script should not be null
Assert.NotNull(script);
// ... It should be formatted as a delete script
string scriptStart = $"DELETE FROM {etm.EscapedMultipartName}";
if (isHekaton)
{
scriptStart += " WITH(SNAPSHOT)";
}
Assert.StartsWith(scriptStart, script);
}
[Fact]
public void SetCell()
{
DbColumn[] columns = Common.GetColumns(true);
ResultSet rs = Common.GetResultSet(columns, true);
IEditTableMetadata etm = Common.GetMetadata(columns, false);
// If: I set a cell on a delete row edit
// Then: It should throw as invalid operation
RowDelete rd = new RowDelete(0, rs, etm);
Assert.Throws<InvalidOperationException>(() => rd.SetCell(0, null));
}
}
}

View File

@@ -0,0 +1,183 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.Contracts;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
public class RowEditBaseTests
{
[Theory]
[InlineData(-1)] // Negative index
[InlineData(100)] // Index larger than number of columns
public void ValidateUpdatableColumnOutOfRange(int columnId)
{
// Setup: Create a result set
ResultSet rs = GetResultSet(
new DbColumn[] { new TestDbColumn("id", true), new TestDbColumn("col1")},
new object[] { "id", "1" });
// If: I validate a column ID that is out of range
// Then: It should throw
RowEditTester tester = new RowEditTester(rs, null);
Assert.Throws<ArgumentOutOfRangeException>(() => tester.ValidateColumn(columnId));
}
[Fact]
public void ValidateUpdatableColumnNotUpdatable()
{
// Setup: Create a result set with an identity column
ResultSet rs = GetResultSet(
new DbColumn[] { new TestDbColumn("id", true), new TestDbColumn("col1") },
new object[] { "id", "1" });
// If: I validate a column ID that is not updatable
// Then: It should throw
RowEditTester tester = new RowEditTester(rs, null);
Assert.Throws<InvalidOperationException>(() => tester.ValidateColumn(0));
}
[Theory]
[MemberData(nameof(GetWhereClauseIsNotNullData))]
public void GetWhereClauseSimple(DbColumn col, object val, string nullClause)
{
// Setup: Create a result set and metadata provider with a single column
var cols = new[] {col};
ResultSet rs = GetResultSet(cols, new[] {val});
IEditTableMetadata etm = Common.GetMetadata(cols);
RowEditTester rt = new RowEditTester(rs, etm);
rt.ValidateWhereClauseSingleKey(nullClause);
}
public static IEnumerable<object> GetWhereClauseIsNotNullData
{
get
{
yield return new object[] {new TestDbColumn("col"), DBNull.Value, "IS NULL"};
yield return new object[] {new TestDbColumn("col", "VARBINARY", typeof(byte[])), new byte[5], "IS NOT NULL"};
yield return new object[] {new TestDbColumn("col", "TEXT", typeof(string)), "abc", "IS NOT NULL"};
yield return new object[] {new TestDbColumn("col", "NTEXT", typeof(string)), "abc", "IS NOT NULL"};
}
}
[Fact]
public void GetWhereClauseMultipleKeyColumns()
{
// Setup: Create a result set and metadata provider with multiple key columns
DbColumn[] cols = {new TestDbColumn("col1"), new TestDbColumn("col2")};
ResultSet rs = GetResultSet(cols, new object[] {"abc", "def"});
IEditTableMetadata etm = Common.GetMetadata(cols);
RowEditTester rt = new RowEditTester(rs, etm);
rt.ValidateWhereClauseMultipleKeys();
}
[Fact]
public void GetWhereClauseNoKeyColumns()
{
// Setup: Create a result set and metadata provider with no key columns
DbColumn[] cols = {new TestDbColumn("col1"), new TestDbColumn("col2")};
ResultSet rs = GetResultSet(cols, new object[] {"abc", "def"});
IEditTableMetadata etm = Common.GetMetadata(new DbColumn[] {});
RowEditTester rt = new RowEditTester(rs, etm);
rt.ValidateWhereClauseNoKeys();
}
private static ResultSet GetResultSet(DbColumn[] columns, object[] row)
{
object[][] rows = {row};
var testResultSet = new TestResultSet(columns, rows);
var testReader = new TestDbDataReader(new [] {testResultSet});
var resultSet = new ResultSet(testReader, 0,0, QueryExecution.Common.GetFileStreamFactory(new Dictionary<string, byte[]>()));
resultSet.ReadResultToEnd(CancellationToken.None).Wait();
return resultSet;
}
private class RowEditTester : RowEditBase
{
public RowEditTester(ResultSet rs, IEditTableMetadata meta) : base(0, rs, meta) { }
public void ValidateColumn(int columnId)
{
ValidateColumnIsUpdatable(columnId);
}
// ReSharper disable once UnusedParameter.Local
public void ValidateWhereClauseSingleKey(string nullValue)
{
// If: I generate a where clause with one is null column value
WhereClause wc = GetWhereClause(false);
// Then:
// ... There should only be one component
Assert.Equal(1, wc.ClauseComponents.Count);
// ... Parameterization should be empty
Assert.Empty(wc.Parameters);
// ... The component should contain the name of the column and be null
Assert.Equal(
$"({AssociatedObjectMetadata.Columns.First().EscapedName} {nullValue})",
wc.ClauseComponents[0]);
// ... The complete clause should contain a single WHERE
Assert.Equal($"WHERE {wc.ClauseComponents[0]}", wc.CommandText);
}
public void ValidateWhereClauseMultipleKeys()
{
// If: I generate a where clause with multiple key columns
WhereClause wc = GetWhereClause(false);
// Then:
// ... There should two components
var keys = AssociatedObjectMetadata.KeyColumns.ToArray();
Assert.Equal(keys.Length, wc.ClauseComponents.Count);
// ... Parameterization should be empty
Assert.Empty(wc.Parameters);
// ... The components should contain the name of the column and the value
Regex r = new Regex(@"\([0-9a-z]+ = .+\)");
Assert.All(wc.ClauseComponents, s => Assert.True(r.IsMatch(s)));
// ... The complete clause should contain multiple cause components joined
// with and
Assert.True(wc.CommandText.StartsWith("WHERE "));
Assert.True(wc.CommandText.EndsWith(string.Join(" AND ", wc.ClauseComponents)));
}
public void ValidateWhereClauseNoKeys()
{
// If: I generate a where clause from metadata that doesn't have keys
// Then: An exception should be thrown
Assert.Throws<InvalidOperationException>(() => GetWhereClause(false));
}
public override string GetScript()
{
throw new NotImplementedException();
}
public override EditUpdateCellResult SetCell(int columnId, string newValue)
{
throw new NotImplementedException();
}
}
}
}

View File

@@ -0,0 +1,105 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Data.Common;
using System.Text.RegularExpressions;
using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
public class RowUpdateTests
{
[Fact]
public void RowUpdateConstruction()
{
// Setup: Create the values to store
const long rowId = 0;
ResultSet rs = QueryExecution.Common.GetBasicExecutedBatch().ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
// If: I create a RowUpdate instance
RowUpdate rc = new RowUpdate(rowId, rs, etm);
// Then: The values I provided should be available
Assert.Equal(rowId, rc.RowId);
Assert.Equal(rs, rc.AssociatedResultSet);
Assert.Equal(etm, rc.AssociatedObjectMetadata);
}
[Fact]
public void ImplicitRevertTest()
{
// Setup: Create a fake table to update
DbColumn[] columns = Common.GetColumns(true);
ResultSet rs = Common.GetResultSet(columns, true);
IEditTableMetadata etm = Common.GetMetadata(columns);
// If:
// ... I add updates to all the cells in the row
RowUpdate ru = new RowUpdate(0, rs, etm);
Common.AddCells(ru, true);
// ... Then I update a cell back to it's old value
var output = ru.SetCell(1, (string) rs.GetRow(0)[1].RawObject);
// Then:
// ... The output should indicate a revert
Assert.NotNull(output);
Assert.True(output.IsRevert);
Assert.False(output.HasCorrections);
Assert.False(output.IsNull);
Assert.Equal(rs.GetRow(0)[1].DisplayValue, output.NewValue);
// ... It should be formatted as an update script
Regex r = new Regex(@"UPDATE .+ SET (.*) WHERE");
var m = r.Match(ru.GetScript());
// ... It should have 2 updates
string updates = m.Groups[1].Value;
string[] updateSplit = updates.Split(',');
Assert.Equal(2, updateSplit.Length);
Assert.All(updateSplit, s => Assert.Equal(2, s.Split('=').Length));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void GetScriptTest(bool isHekaton)
{
// Setup: Create a fake table to update
DbColumn[] columns = Common.GetColumns(true);
ResultSet rs = Common.GetResultSet(columns, true);
IEditTableMetadata etm = Common.GetMetadata(columns, false, isHekaton);
// If: I ask for a script to be generated for update
RowUpdate ru = new RowUpdate(0, rs, etm);
Common.AddCells(ru, true);
string script = ru.GetScript();
// Then:
// ... The script should not be null
Assert.NotNull(script);
// ... It should be formatted as an update script
string regexString = isHekaton
? @"UPDATE (.+) WITH \(SNAPSHOT\) SET (.*) WHERE .+"
: @"UPDATE (.+) SET (.*) WHERE .+";
Regex r = new Regex(regexString);
var m = r.Match(script);
Assert.True(m.Success);
// ... It should have 3 updates
string tbl = m.Groups[1].Value;
string updates = m.Groups[2].Value;
string[] updateSplit = updates.Split(',');
Assert.Equal(etm.EscapedMultipartName, tbl);
Assert.Equal(3, updateSplit.Length);
Assert.All(updateSplit, s => Assert.Equal(2, s.Split('=').Length));
}
}
}

View File

@@ -0,0 +1,239 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.Contracts;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
public class ServiceIntegrationTests
{
#region Session Operation Helper Tests
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" \t\n\r")]
[InlineData("Does not exist")]
public async Task NullOrMissingSessionId(string sessionId)
{
// Setup:
// ... Create a edit data service
var eds = new EditDataService(null, null, null);
// ... Create a session params that returns the provided session ID
var mockParams = new EditCreateRowParams {OwnerUri = sessionId};
// If: I ask to perform an action that requires a session
// Then: I should get an error from it
var efv = new EventFlowValidator<EditDisposeResult>()
.AddStandardErrorValidation()
.Complete();
await eds.HandleSessionRequest(mockParams, efv.Object, session => null);
efv.Validate();
}
[Fact]
public async Task OperationThrows()
{
// Setup:
// ... Create an edit data service with a session
var eds = new EditDataService(null, null, null);
eds.ActiveSessions[Common.OwnerUri] = GetDefaultSession();
// ... Create a session param that returns the common owner uri
var mockParams = new EditCreateRowParams { OwnerUri = Common.OwnerUri };
// If: I ask to perform an action that requires a session
// Then: I should get an error from it
var efv = new EventFlowValidator<EditDisposeResult>()
.AddStandardErrorValidation()
.Complete();
await eds.HandleSessionRequest(mockParams, efv.Object, s => { throw new Exception(); });
efv.Validate();
}
#endregion
#region Dispose Tests
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" \t\n\r")]
[InlineData("Does not exist")]
public async Task DisposeNullOrMissingSessionId(string sessionId)
{
// Setup: Create a edit data service
var eds = new EditDataService(null, null, null);
// If: I ask to perform an action that requires a session
// Then: I should get an error from it
var efv = new EventFlowValidator<EditDisposeResult>()
.AddStandardErrorValidation()
.Complete();
await eds.HandleDisposeRequest(new EditDisposeParams {OwnerUri = sessionId}, efv.Object);
efv.Validate();
}
[Fact]
public async Task DisposeSuccess()
{
// Setup: Create an edit data service with a session
var eds = new EditDataService(null, null, null);
eds.ActiveSessions[Common.OwnerUri] = GetDefaultSession();
// If: I ask to dispose of an existing session
var efv = new EventFlowValidator<EditDisposeResult>()
.AddResultValidation(Assert.NotNull)
.Complete();
await eds.HandleDisposeRequest(new EditDisposeParams {OwnerUri = Common.OwnerUri}, efv.Object);
// Then:
// ... It should have completed successfully
efv.Validate();
// ... And the session should have been removed from the active session list
Assert.Empty(eds.ActiveSessions);
}
#endregion
[Fact]
public async Task DeleteSuccess()
{
// Setup: Create an edit data service with a session
var eds = new EditDataService(null, null, null);
eds.ActiveSessions[Common.OwnerUri] = GetDefaultSession();
// If: I validly ask to delete a row
var efv = new EventFlowValidator<EditDeleteRowResult>()
.AddResultValidation(Assert.NotNull)
.Complete();
await eds.HandleDeleteRowRequest(new EditDeleteRowParams {OwnerUri = Common.OwnerUri, RowId = 0}, efv.Object);
// Then:
// ... It should be successful
efv.Validate();
// ... There should be a delete in the session
Session s = eds.ActiveSessions[Common.OwnerUri];
Assert.True(s.EditCache.Any(e => e.Value is RowDelete));
}
[Fact]
public async Task CreateSucceeds()
{
// Setup: Create an edit data service with a session
var eds = new EditDataService(null, null, null);
eds.ActiveSessions[Common.OwnerUri] = GetDefaultSession();
// If: I ask to create a row from a non existant session
var efv = new EventFlowValidator<EditCreateRowResult>()
.AddResultValidation(ecrr => { Assert.True(ecrr.NewRowId > 0); })
.Complete();
await eds.HandleCreateRowRequest(new EditCreateRowParams { OwnerUri = Common.OwnerUri }, efv.Object);
// Then:
// ... It should have been successful
efv.Validate();
// ... There should be a create in the session
Session s = eds.ActiveSessions[Common.OwnerUri];
Assert.True(s.EditCache.Any(e => e.Value is RowCreate));
}
[Fact]
public async Task RevertSucceeds()
{
// Setup: Create an edit data service with a session that has an pending edit
var eds = new EditDataService(null, null, null);
var session = GetDefaultSession();
session.EditCache[0] = new Mock<RowEditBase>().Object;
eds.ActiveSessions[Common.OwnerUri] = session;
// If: I ask to revert a row that has a pending edit
var efv = new EventFlowValidator<EditRevertRowResult>()
.AddResultValidation(Assert.NotNull)
.Complete();
await eds.HandleRevertRowRequest(new EditRevertRowParams { OwnerUri = Common.OwnerUri, RowId = 0}, efv.Object);
// Then:
// ... It should have succeeded
efv.Validate();
// ... The edit cache should be empty again
Session s = eds.ActiveSessions[Common.OwnerUri];
Assert.Empty(s.EditCache);
}
[Fact]
public async Task UpdateSuccess()
{
// Setup: Create an edit data service with a session
var eds = new EditDataService(null, null, null);
var session = GetDefaultSession();
eds.ActiveSessions[Common.OwnerUri] = session;
var edit = new Mock<RowEditBase>();
edit.Setup(e => e.SetCell(It.IsAny<int>(), It.IsAny<string>())).Returns(new EditUpdateCellResult
{
NewValue = string.Empty,
HasCorrections = true,
IsRevert = false,
IsNull = false
});
session.EditCache[0] = edit.Object;
// If: I validly ask to update a cell
var efv = new EventFlowValidator<EditUpdateCellResult>()
.AddResultValidation(eucr =>
{
Assert.NotNull(eucr);
Assert.NotNull(eucr.NewValue);
Assert.False(eucr.IsRevert);
Assert.False(eucr.IsNull);
})
.Complete();
await eds.HandleUpdateCellRequest(new EditUpdateCellParams { OwnerUri = Common.OwnerUri, RowId = 0}, efv.Object);
// Then:
// ... It should be successful
efv.Validate();
// ... Set cell should have been called once
edit.Verify(e => e.SetCell(It.IsAny<int>(), It.IsAny<string>()), Times.Once);
}
private static Session GetDefaultSession()
{
// ... Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
return s;
}
}
public static class EditServiceEventFlowValidatorExtensions
{
public static EventFlowValidator<T> AddStandardErrorValidation<T>(this EventFlowValidator<T> evf)
{
return evf.AddErrorValidation<string>(p =>
{
Assert.NotNull(p);
Assert.NotEmpty(p);
});
}
}
}

View File

@@ -0,0 +1,381 @@
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using Microsoft.SqlTools.ServiceLayer.Connection;
using Microsoft.SqlTools.ServiceLayer.EditData;
using Microsoft.SqlTools.ServiceLayer.EditData.UpdateManagement;
using Microsoft.SqlTools.ServiceLayer.QueryExecution;
using Microsoft.SqlTools.ServiceLayer.SqlContext;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.ServiceLayer.Test.Utility;
using Moq;
using Xunit;
namespace Microsoft.SqlTools.ServiceLayer.Test.EditData
{
public class SessionTests
{
#region Construction Tests
[Fact]
public void SessionConstructionNullQuery()
{
// If: I create a session object without a null query
// Then: It should throw an exception
Assert.Throws<ArgumentNullException>(() => new Session(null, Common.GetMetadata(new DbColumn[] {})));
}
[Fact]
public void SessionConstructionNullMetadataProvider()
{
// If: I create a session object without a null metadata provider
// Then: It should throw an exception
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
Assert.Throws<ArgumentNullException>(() => new Session(rs, null));
}
[Fact]
public void SessionConstructionValid()
{
// If: I create a session object with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// Then:
// ... The edit cache should exist and be empty
Assert.NotNull(s.EditCache);
Assert.Empty(s.EditCache);
// ... The next row ID should be equivalent to the number of rows in the result set
Assert.Equal(q.Batches[0].ResultSets[0].RowCount, s.NextRowId);
}
#endregion
#region Validate Tests
[Fact]
public void SessionValidateUnfinishedQuery()
{
// If: I create a session object with a query that hasn't finished execution
// Then: It should throw an exception
Query q = QueryExecution.Common.GetBasicExecutedQuery();
q.HasExecuted = false;
Assert.Throws<InvalidOperationException>(() => Session.ValidateQueryForSession(q));
}
[Fact]
public void SessionValidateIncorrectResultSet()
{
// Setup: Create a query that yields >1 result sets
TestResultSet[] results =
{
QueryExecution.Common.StandardTestResultSet,
QueryExecution.Common.StandardTestResultSet
};
// @TODO: Fix when the connection service is fixed
ConnectionInfo ci = QueryExecution.Common.CreateConnectedConnectionInfo(results, false);
ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
var fsf = QueryExecution.Common.GetFileStreamFactory(new Dictionary<string, byte[]>());
Query query = new Query(QueryExecution.Common.StandardQuery, ci, new QueryExecutionSettings(), fsf);
query.Execute();
query.ExecutionTask.Wait();
// If: I create a session object with a query that has !=1 result sets
// Then: It should throw an exception
Assert.Throws<InvalidOperationException>(() => Session.ValidateQueryForSession(query));
}
[Fact]
public void SessionValidateValidResultSet()
{
// If: I validate a query for a session with a valid query
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = Session.ValidateQueryForSession(q);
// Then: I should get the only result set back
Assert.NotNull(rs);
}
#endregion
#region Create Row Tests
[Fact]
public void CreateRowAddFailure()
{
// NOTE: This scenario should theoretically never occur, but is tested for completeness
// Setup:
// ... Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// ... Add a mock edit to the edit cache to cause the .TryAdd to fail
var mockEdit = new Mock<RowEditBase>().Object;
s.EditCache[rs.RowCount] = mockEdit;
// If: I create a row in the session
// Then:
// ... An exception should be thrown
Assert.Throws<InvalidOperationException>(() => s.CreateRow());
// ... The mock edit should still exist
Assert.Equal(mockEdit, s.EditCache[rs.RowCount]);
// ... The next row ID should not have changes
Assert.Equal(rs.RowCount, s.NextRowId);
}
[Fact]
public void CreateRowSuccess()
{
// Setup: Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// If: I add a row to the session
long newId = s.CreateRow();
// Then:
// ... The new ID should be equal to the row count
Assert.Equal(rs.RowCount, newId);
// ... The next row ID should have been incremented
Assert.Equal(rs.RowCount + 1, s.NextRowId);
// ... There should be a new row create object in the cache
Assert.Contains(newId, s.EditCache.Keys);
Assert.IsType<RowCreate>(s.EditCache[newId]);
}
#endregion
[Theory]
[MemberData(nameof(RowIdOutOfRangeData))]
public void RowIdOutOfRange(long rowId, Action<Session, long> testAction)
{
// Setup: Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// If: I delete a row that is out of range for the result set
// Then: I should get an exception
Assert.Throws<ArgumentOutOfRangeException>(() => testAction(s, rowId));
}
public static IEnumerable<object> RowIdOutOfRangeData
{
get
{
// Delete Row
Action<Session, long> delAction = (s, l) => s.DeleteRow(l);
yield return new object[] { -1L, delAction };
yield return new object[] { 100L, delAction };
// Update Cell
Action<Session, long> upAction = (s, l) => s.UpdateCell(l, 0, null);
yield return new object[] { -1L, upAction };
yield return new object[] { 100L, upAction };
}
}
#region Delete Row Tests
[Fact]
public void DeleteRowAddFailure()
{
// Setup:
// ... Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// ... Add a mock edit to the edit cache to cause the .TryAdd to fail
var mockEdit = new Mock<RowEditBase>().Object;
s.EditCache[0] = mockEdit;
// If: I delete a row in the session
// Then:
// ... An exception should be thrown
Assert.Throws<InvalidOperationException>(() => s.DeleteRow(0));
// ... The mock edit should still exist
Assert.Equal(mockEdit, s.EditCache[0]);
}
[Fact]
public void DeleteRowSuccess()
{
// Setup: Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// If: I add a row to the session
s.DeleteRow(0);
// Then: There should be a new row delete object in the cache
Assert.Contains(0, s.EditCache.Keys);
Assert.IsType<RowDelete>(s.EditCache[0]);
}
#endregion
#region Revert Row Tests
[Fact]
public void RevertRowOutOfRange()
{
// Setup: Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// If: I revert a row that doesn't have any pending changes
// Then: I should get an exception
Assert.Throws<ArgumentOutOfRangeException>(() => s.RevertRow(0));
}
[Fact]
public void RevertRowSuccess()
{
// Setup:
// ... Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// ... Add a mock edit to the edit cache to cause the .TryAdd to fail
var mockEdit = new Mock<RowEditBase>().Object;
s.EditCache[0] = mockEdit;
// If: I revert the row that has a pending update
s.RevertRow(0);
// Then:
// ... The edit cache should not contain a pending edit for the row
Assert.DoesNotContain(0, s.EditCache.Keys);
}
#endregion
#region Update Cell Tests
[Fact]
public void UpdateCellExisting()
{
// Setup:
// ... Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// ... Add a mock edit to the edit cache to cause the .TryAdd to fail
var mockEdit = new Mock<RowEditBase>();
mockEdit.Setup(e => e.SetCell(It.IsAny<int>(), It.IsAny<string>()));
s.EditCache[0] = mockEdit.Object;
// If: I update a cell on a row that already has a pending edit
s.UpdateCell(0, 0, null);
// Then:
// ... The mock update should still be in the cache
// ... And it should have had set cell called on it
Assert.Contains(mockEdit.Object, s.EditCache.Values);
}
[Fact]
public void UpdateCellNew()
{
// Setup:
// ... Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// If: I update a cell on a row that does not have a pending edit
s.UpdateCell(0, 0, "");
// Then:
// ... A new update row edit should have been added to the cache
Assert.Contains(0, s.EditCache.Keys);
Assert.IsType<RowUpdate>(s.EditCache[0]);
}
#endregion
#region Script Edits Tests
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" \t\r\n")]
public void ScriptNullOrEmptyOutput(string outputPath)
{
// Setup: Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// If: I try to script the edit cache with a null or whitespace output path
// Then: It should throw an exception
Assert.Throws<ArgumentNullException>(() => s.ScriptEdits(outputPath));
}
[Fact]
public void ScriptProvidedOutputPath()
{
// Setup:
// ... Create a session with a proper query and metadata
Query q = QueryExecution.Common.GetBasicExecutedQuery();
ResultSet rs = q.Batches[0].ResultSets[0];
IEditTableMetadata etm = Common.GetMetadata(rs.Columns);
Session s = new Session(rs, etm);
// ... Add two mock edits that will generate a script
Mock<RowEditBase> edit = new Mock<RowEditBase>();
edit.Setup(e => e.GetScript()).Returns("test");
s.EditCache[0] = edit.Object;
s.EditCache[1] = edit.Object;
using (SelfCleaningTempFile file = new SelfCleaningTempFile())
{
// If: I script the edit cache to a local output path
string outputPath = s.ScriptEdits(file.FilePath);
// Then:
// ... The output path used should be the same as the one we provided
Assert.Equal(file.FilePath, outputPath);
// ... The written file should have two lines, one for each edit
Assert.Equal(2, File.ReadAllLines(outputPath).Length);
}
}
#endregion
}
}