Commit 85a4cc71 authored by Nick Craver's avatar Nick Craver Committed by Nick Craver

Tests: add "LogToConsole" config option, allowing instant console output as well

This helps for real-time output on long-running or hanging tests.
parent fc06d78c
...@@ -23,7 +23,7 @@ public void PingOnce() ...@@ -23,7 +23,7 @@ public void PingOnce()
var task = conn.PingAsync(); var task = conn.PingAsync();
var duration = muxer.Wait(task); var duration = muxer.Wait(task);
Output.WriteLine("Ping took: " + duration); Log("Ping took: " + duration);
Assert.True(duration.TotalMilliseconds > 0); Assert.True(duration.TotalMilliseconds > 0);
} }
} }
...@@ -256,7 +256,7 @@ public async Task GetWithExpiryWrongTypeAsync() ...@@ -256,7 +256,7 @@ public async Task GetWithExpiryWrongTypeAsync()
{ {
try try
{ {
Output.WriteLine("Key: " + (string)key); Log("Key: " + (string)key);
var async = await db.StringGetWithExpiryAsync(key).ForAwait(); var async = await db.StringGetWithExpiryAsync(key).ForAwait();
} }
catch (AggregateException e) catch (AggregateException e)
...@@ -296,12 +296,12 @@ public void TestQuit() ...@@ -296,12 +296,12 @@ public void TestQuit()
db.KeyDelete(key, CommandFlags.FireAndForget); db.KeyDelete(key, CommandFlags.FireAndForget);
db.StringSet(key, key, flags: CommandFlags.FireAndForget); db.StringSet(key, key, flags: CommandFlags.FireAndForget);
GetServer(muxer).Execute("QUIT", null, CommandFlags.FireAndForget); GetServer(muxer).Execute("QUIT", null, CommandFlags.FireAndForget);
var watch = System.Diagnostics.Stopwatch.StartNew(); var watch = Stopwatch.StartNew();
Assert.Throws<RedisConnectionException>(() => db.Ping()); Assert.Throws<RedisConnectionException>(() => db.Ping());
watch.Stop(); watch.Stop();
Output.WriteLine("Time to notice quit: {0}ms (any order)", watch.ElapsedMilliseconds); Log("Time to notice quit: {0}ms (any order)", watch.ElapsedMilliseconds);
System.Threading.Thread.Sleep(20); Thread.Sleep(20);
System.Diagnostics.Debug.WriteLine("Pinging..."); Debug.WriteLine("Pinging...");
Assert.Equal(key, (string)db.StringGet(key)); Assert.Equal(key, (string)db.StringGet(key));
} }
} }
...@@ -322,7 +322,7 @@ public async Task TestSevered() ...@@ -322,7 +322,7 @@ public async Task TestSevered()
var watch = Stopwatch.StartNew(); var watch = Stopwatch.StartNew();
db.Ping(); db.Ping();
watch.Stop(); watch.Stop();
Output.WriteLine("Time to re-establish: {0}ms (any order)", watch.ElapsedMilliseconds); Log("Time to re-establish: {0}ms (any order)", watch.ElapsedMilliseconds);
await Task.Delay(2000).ForAwait(); await Task.Delay(2000).ForAwait();
Debug.WriteLine("Pinging..."); Debug.WriteLine("Pinging...");
Assert.Equal(key, db.StringGet(key)); Assert.Equal(key, db.StringGet(key));
......
...@@ -27,6 +27,23 @@ static BookSleeveTestBase() ...@@ -27,6 +27,23 @@ static BookSleeveTestBase()
}; };
} }
protected void Log(string message)
{
Output.WriteLine(message);
if (TestConfig.Current.LogToConsole)
{
Console.WriteLine(message);
}
}
protected void Log(string message, params object[] args)
{
Output.WriteLine(message, args);
if (TestConfig.Current.LogToConsole)
{
Console.WriteLine(message, args);
}
}
protected static string Me([CallerFilePath] string filePath = null, [CallerMemberName] string caller = null) => TestBase.Me(filePath, caller); protected static string Me([CallerFilePath] string filePath = null, [CallerMemberName] string caller = null) => TestBase.Me(filePath, caller);
internal static IServer GetServer(ConnectionMultiplexer conn) => conn.GetServer(conn.GetEndPoints()[0]); internal static IServer GetServer(ConnectionMultiplexer conn) => conn.GetServer(conn.GetEndPoints()[0]);
......
...@@ -44,7 +44,7 @@ public void CanNotOpenNonsenseConnection_IP() ...@@ -44,7 +44,7 @@ public void CanNotOpenNonsenseConnection_IP()
} }
finally finally
{ {
Output.WriteLine(log.ToString()); Log(log.ToString());
} }
}); });
} }
...@@ -63,10 +63,10 @@ public async Task CanNotOpenNonsenseConnection_DNS() ...@@ -63,10 +63,10 @@ public async Task CanNotOpenNonsenseConnection_DNS()
} }
finally finally
{ {
Output.WriteLine(log.ToString()); Log(log.ToString());
} }
}).ForAwait(); }).ForAwait();
Output.WriteLine(ex.ToString()); Log(ex.ToString());
} }
[Fact] [Fact]
...@@ -83,7 +83,7 @@ public void CreateDisconnectedNonsenseConnection_IP() ...@@ -83,7 +83,7 @@ public void CreateDisconnectedNonsenseConnection_IP()
} }
finally finally
{ {
Output.WriteLine(log.ToString()); Log(log.ToString());
} }
} }
...@@ -101,7 +101,7 @@ public void CreateDisconnectedNonsenseConnection_DNS() ...@@ -101,7 +101,7 @@ public void CreateDisconnectedNonsenseConnection_DNS()
} }
finally finally
{ {
Output.WriteLine(log.ToString()); Log(log.ToString());
} }
} }
......
...@@ -69,11 +69,11 @@ public async Task ExecuteMassiveDelete() ...@@ -69,11 +69,11 @@ public async Task ExecuteMassiveDelete()
} }
watch.Stop(); watch.Stop();
long remaining = await conn.SetLengthAsync(key).ForAwait(); long remaining = await conn.SetLengthAsync(key).ForAwait();
Output.WriteLine("From {0} to {1}; {2}ms", originally, remaining, Log("From {0} to {1}; {2}ms", originally, remaining,
watch.ElapsedMilliseconds); watch.ElapsedMilliseconds);
var counters = GetServer(muxer).GetCounters(); var counters = GetServer(muxer).GetCounters();
Output.WriteLine("Completions: {0} sync, {1} async", counters.Interactive.CompletedSynchronously, counters.Interactive.CompletedAsynchronously); Log("Completions: {0} sync, {1} async", counters.Interactive.CompletedSynchronously, counters.Interactive.CompletedAsynchronously);
} }
} }
} }
......
...@@ -42,7 +42,7 @@ public void VerifyPerformanceImprovement() ...@@ -42,7 +42,7 @@ public void VerifyPerformanceImprovement()
muxer.WaitAll(final); muxer.WaitAll(final);
timer.Stop(); timer.Stop();
asyncTimer = (int)timer.ElapsedMilliseconds; asyncTimer = (int)timer.ElapsedMilliseconds;
Output.WriteLine("async to completion (local): {0}ms", timer.ElapsedMilliseconds); Log("async to completion (local): {0}ms", timer.ElapsedMilliseconds);
for (int db = 0; db < 5; db++) for (int db = 0; db < 5; db++)
{ {
Assert.Equal(1000, (long)final[db].Result); // "async, db:" + db Assert.Equal(1000, (long)final[db].Result); // "async, db:" + db
...@@ -83,7 +83,7 @@ public void VerifyPerformanceImprovement() ...@@ -83,7 +83,7 @@ public void VerifyPerformanceImprovement()
} }
timer.Stop(); timer.Stop();
sync = (int)timer.ElapsedMilliseconds; sync = (int)timer.ElapsedMilliseconds;
Output.WriteLine("sync to completion (local): {0}ms", timer.ElapsedMilliseconds); Log("sync to completion (local): {0}ms", timer.ElapsedMilliseconds);
for (int db = 0; db < 5; db++) for (int db = 0; db < 5; db++)
{ {
Assert.Equal("1000", final[db]); // "async, db:" + db Assert.Equal("1000", final[db]); // "async, db:" + db
...@@ -91,9 +91,9 @@ public void VerifyPerformanceImprovement() ...@@ -91,9 +91,9 @@ public void VerifyPerformanceImprovement()
} }
int effectiveAsync = ((10 * asyncTimer) + 3) / 10; int effectiveAsync = ((10 * asyncTimer) + 3) / 10;
int effectiveSync = ((10 * sync) + (op * 3)) / 10; int effectiveSync = ((10 * sync) + (op * 3)) / 10;
Output.WriteLine("async to completion with assumed 0.3ms LAN latency: " + effectiveAsync); Log("async to completion with assumed 0.3ms LAN latency: " + effectiveAsync);
Output.WriteLine("sync to completion with assumed 0.3ms LAN latency: " + effectiveSync); Log("sync to completion with assumed 0.3ms LAN latency: " + effectiveSync);
Output.WriteLine("fire-and-forget: {0}ms sync vs {1}ms async ", syncFaF, asyncFaF); Log("fire-and-forget: {0}ms sync vs {1}ms async ", syncFaF, asyncFaF);
Assert.True(effectiveAsync < effectiveSync, "Everything"); Assert.True(effectiveAsync < effectiveSync, "Everything");
Assert.True(asyncFaF < syncFaF, "Fire and Forget"); Assert.True(asyncFaF < syncFaF, "Fire and Forget");
} }
...@@ -119,7 +119,7 @@ public async Task BasicStringGetPerf() ...@@ -119,7 +119,7 @@ public async Task BasicStringGetPerf()
asyncVal = await db.StringGetAsync(key); asyncVal = await db.StringGetAsync(key);
asyncTimer.Stop(); asyncTimer.Stop();
Output.WriteLine($"Sync: {syncTimer.ElapsedMilliseconds}; Async: {asyncTimer.ElapsedMilliseconds}"); Log($"Sync: {syncTimer.ElapsedMilliseconds}; Async: {asyncTimer.ElapsedMilliseconds}");
Assert.Equal("some value", syncVal); Assert.Equal("some value", syncVal);
Assert.Equal("some value", asyncVal); Assert.Equal("some value", asyncVal);
// let's allow 20% async overhead // let's allow 20% async overhead
......
...@@ -71,7 +71,7 @@ private void TestMassivePublish(ISubscriber conn, string channel, string caption ...@@ -71,7 +71,7 @@ private void TestMassivePublish(ISubscriber conn, string channel, string caption
conn.WaitAll(tasks); conn.WaitAll(tasks);
withAsync.Stop(); withAsync.Stop();
Output.WriteLine("{2}: {0}ms (F+F) vs {1}ms (async)", Log("{2}: {0}ms (F+F) vs {1}ms (async)",
withFAF.ElapsedMilliseconds, withAsync.ElapsedMilliseconds, caption); withFAF.ElapsedMilliseconds, withAsync.ElapsedMilliseconds, caption);
// We've made async so far, this test isn't really valid anymore // We've made async so far, this test isn't really valid anymore
// So let's check they're at least within a few seconds. // So let's check they're at least within a few seconds.
...@@ -97,7 +97,7 @@ public async Task PubSubGetAllAnyOrder() ...@@ -97,7 +97,7 @@ public async Task PubSubGetAllAnyOrder()
{ {
data.Add(int.Parse(Encoding.UTF8.GetString(val))); data.Add(int.Parse(Encoding.UTF8.GetString(val)));
pulse = data.Count == count; pulse = data.Count == count;
if ((data.Count % 100) == 99) Output.WriteLine(data.Count.ToString()); if ((data.Count % 100) == 99) Log(data.Count.ToString());
} }
if (pulse) if (pulse)
{ {
...@@ -153,7 +153,7 @@ async Task RunLoop() ...@@ -153,7 +153,7 @@ async Task RunLoop()
{ {
data.Add(i); data.Add(i);
if (data.Count == count) break; if (data.Count == count) break;
if ((data.Count % 100) == 99) Output.WriteLine(data.Count.ToString()); if ((data.Count % 100) == 99) Log(data.Count.ToString());
} }
} }
lock (syncLock) lock (syncLock)
...@@ -211,7 +211,7 @@ public async Task PubSubGetAllCorrectOrder_OnMessage_Sync() ...@@ -211,7 +211,7 @@ public async Task PubSubGetAllCorrectOrder_OnMessage_Sync()
{ {
data.Add(i); data.Add(i);
if (data.Count == count) pulse = true; if (data.Count == count) pulse = true;
if ((data.Count % 100) == 99) Output.WriteLine(data.Count.ToString()); if ((data.Count % 100) == 99) Log(data.Count.ToString());
} }
if (pulse) if (pulse)
{ {
...@@ -271,7 +271,7 @@ public async Task PubSubGetAllCorrectOrder_OnMessage_Async() ...@@ -271,7 +271,7 @@ public async Task PubSubGetAllCorrectOrder_OnMessage_Async()
{ {
data.Add(i); data.Add(i);
if (data.Count == count) pulse = true; if (data.Count == count) pulse = true;
if ((data.Count % 100) == 99) Output.WriteLine(data.Count.ToString()); if ((data.Count % 100) == 99) Log(data.Count.ToString());
} }
if (pulse) if (pulse)
{ {
......
...@@ -116,7 +116,7 @@ public void HackyGetPerf() ...@@ -116,7 +116,7 @@ public void HackyGetPerf()
redis.call('del', KEYS[1]) redis.call('del', KEYS[1])
return timeTaken return timeTaken
", new RedisKey[] { key }, null); ", new RedisKey[] { key }, null);
Output.WriteLine(result.ToString()); Log(result.ToString());
Assert.True(result > 0); Assert.True(result > 0);
} }
} }
...@@ -333,7 +333,7 @@ public void ChangeDbInScript() ...@@ -333,7 +333,7 @@ public void ChangeDbInScript()
muxer.GetDatabase(1).StringSet(key, "db 1"); muxer.GetDatabase(1).StringSet(key, "db 1");
muxer.GetDatabase(2).StringSet(key, "db 2"); muxer.GetDatabase(2).StringSet(key, "db 2");
Output.WriteLine("Key: " + key); Log("Key: " + key);
var conn = muxer.GetDatabase(2); var conn = muxer.GetDatabase(2);
var evalResult = conn.ScriptEvaluateAsync(@"redis.call('select', 1) var evalResult = conn.ScriptEvaluateAsync(@"redis.call('select', 1)
return redis.call('get','" + key +"')", null, null); return redis.call('get','" + key +"')", null, null);
......
...@@ -51,8 +51,8 @@ public async Task ConnectUsesSingleSocket() ...@@ -51,8 +51,8 @@ public async Task ConnectUsesSingleSocket()
{ {
var srv = muxer.GetServer(ep); var srv = muxer.GetServer(ep);
var counters = srv.GetCounters(); var counters = srv.GetCounters();
Output.WriteLine($"{i}; interactive, {ep}, count: {counters.Interactive.SocketCount}"); Log($"{i}; interactive, {ep}, count: {counters.Interactive.SocketCount}");
Output.WriteLine($"{i}; subscription, {ep}, count: {counters.Subscription.SocketCount}"); Log($"{i}; subscription, {ep}, count: {counters.Subscription.SocketCount}");
} }
foreach (var ep in muxer.GetEndPoints()) foreach (var ep in muxer.GetEndPoints())
{ {
...@@ -67,7 +67,7 @@ public async Task ConnectUsesSingleSocket() ...@@ -67,7 +67,7 @@ public async Task ConnectUsesSingleSocket()
finally finally
{ {
// Connection info goes at the end... // Connection info goes at the end...
Output.WriteLine(sw.ToString()); Log(sw.ToString());
} }
} }
} }
...@@ -78,17 +78,17 @@ public void CanGetTotalStats() ...@@ -78,17 +78,17 @@ public void CanGetTotalStats()
using (var muxer = Create()) using (var muxer = Create())
{ {
var counters = muxer.GetCounters(); var counters = muxer.GetCounters();
Output.WriteLine(counters.ToString()); Log(counters.ToString());
} }
} }
private void PrintEndpoints(EndPoint[] endpoints) private void PrintEndpoints(EndPoint[] endpoints)
{ {
Output.WriteLine($"Endpoints Expected: {TestConfig.Current.ClusterStartPort}+{TestConfig.Current.ClusterServerCount}"); Log($"Endpoints Expected: {TestConfig.Current.ClusterStartPort}+{TestConfig.Current.ClusterServerCount}");
Output.WriteLine("Endpoints Found:"); Log("Endpoints Found:");
foreach (var endpoint in endpoints) foreach (var endpoint in endpoints)
{ {
Output.WriteLine(" Endpoint: " + endpoint); Log(" Endpoint: " + endpoint);
} }
} }
...@@ -106,7 +106,7 @@ public void Connect() ...@@ -106,7 +106,7 @@ public void Connect()
} }
else else
{ {
Output.WriteLine(sw.ToString()); Log(sw.ToString());
} }
Assert.Equal(TestConfig.Current.ClusterServerCount, endpoints.Length); Assert.Equal(TestConfig.Current.ClusterServerCount, endpoints.Length);
...@@ -119,16 +119,16 @@ public void Connect() ...@@ -119,16 +119,16 @@ public void Connect()
{ {
failed.Add(endpoint); failed.Add(endpoint);
} }
Output.WriteLine("endpoint:" + endpoint); Log("endpoint:" + endpoint);
Assert.Equal(endpoint, server.EndPoint); Assert.Equal(endpoint, server.EndPoint);
Output.WriteLine("endpoint-type:" + endpoint); Log("endpoint-type:" + endpoint);
Assert.IsType<IPEndPoint>(endpoint); Assert.IsType<IPEndPoint>(endpoint);
Output.WriteLine("port:" + endpoint); Log("port:" + endpoint);
Assert.True(expectedPorts.Remove(((IPEndPoint)endpoint).Port)); Assert.True(expectedPorts.Remove(((IPEndPoint)endpoint).Port));
Output.WriteLine("server-type:" + endpoint); Log("server-type:" + endpoint);
Assert.Equal(ServerType.Cluster, server.ServerType); Assert.Equal(ServerType.Cluster, server.ServerType);
if (server.IsSlave) slaves++; if (server.IsSlave) slaves++;
...@@ -136,10 +136,10 @@ public void Connect() ...@@ -136,10 +136,10 @@ public void Connect()
} }
if (failed.Count != 0) if (failed.Count != 0)
{ {
Output.WriteLine("{0} failues", failed.Count); Log("{0} failues", failed.Count);
foreach (var fail in failed) foreach (var fail in failed)
{ {
Output.WriteLine(fail.ToString()); Log(fail.ToString());
} }
Assert.True(false, "not all servers connected"); Assert.True(false, "not all servers connected");
} }
...@@ -182,14 +182,14 @@ string StringGet(IServer server, RedisKey key, CommandFlags flags = CommandFlags ...@@ -182,14 +182,14 @@ string StringGet(IServer server, RedisKey key, CommandFlags flags = CommandFlags
int slot = conn.HashSlot(key); int slot = conn.HashSlot(key);
var rightMasterNode = config.GetBySlot(key); var rightMasterNode = config.GetBySlot(key);
Assert.NotNull(rightMasterNode); Assert.NotNull(rightMasterNode);
Output.WriteLine("Right Master: {0} {1}", rightMasterNode.EndPoint, rightMasterNode.NodeId); Log("Right Master: {0} {1}", rightMasterNode.EndPoint, rightMasterNode.NodeId);
string a = StringGet(conn.GetServer(rightMasterNode.EndPoint), key); string a = StringGet(conn.GetServer(rightMasterNode.EndPoint), key);
Assert.Equal(value, a); // right master Assert.Equal(value, a); // right master
var node = config.Nodes.FirstOrDefault(x => !x.IsSlave && x.NodeId != rightMasterNode.NodeId); var node = config.Nodes.FirstOrDefault(x => !x.IsSlave && x.NodeId != rightMasterNode.NodeId);
Assert.NotNull(node); Assert.NotNull(node);
Output.WriteLine("Using Master: {0}", node.EndPoint, node.NodeId); Log("Using Master: {0}", node.EndPoint, node.NodeId);
if (node != null) if (node != null)
{ {
string b = StringGet(conn.GetServer(node.EndPoint), key); string b = StringGet(conn.GetServer(node.EndPoint), key);
...@@ -246,8 +246,8 @@ public void TransactionWithMultiServerKeys() ...@@ -246,8 +246,8 @@ public void TransactionWithMultiServerKeys()
} while (--abort > 0 && config.GetBySlot(y) == xNode); } while (--abort > 0 && config.GetBySlot(y) == xNode);
if (abort == 0) Skip.Inconclusive("failed to find a different node to use"); if (abort == 0) Skip.Inconclusive("failed to find a different node to use");
var yNode = config.GetBySlot(y); var yNode = config.GetBySlot(y);
Output.WriteLine("x={0}, served by {1}", x, xNode.NodeId); Log("x={0}, served by {1}", x, xNode.NodeId);
Output.WriteLine("y={0}, served by {1}", y, yNode.NodeId); Log("y={0}, served by {1}", y, yNode.NodeId);
Assert.NotEqual(xNode.NodeId, yNode.NodeId); Assert.NotEqual(xNode.NodeId, yNode.NodeId);
// wipe those keys // wipe those keys
...@@ -302,8 +302,8 @@ public void TransactionWithSameServerKeys() ...@@ -302,8 +302,8 @@ public void TransactionWithSameServerKeys()
} while (--abort > 0 && config.GetBySlot(y) != xNode); } while (--abort > 0 && config.GetBySlot(y) != xNode);
if (abort == 0) Skip.Inconclusive("failed to find a key with the same node to use"); if (abort == 0) Skip.Inconclusive("failed to find a key with the same node to use");
var yNode = config.GetBySlot(y); var yNode = config.GetBySlot(y);
Output.WriteLine("x={0}, served by {1}", x, xNode.NodeId); Log("x={0}, served by {1}", x, xNode.NodeId);
Output.WriteLine("y={0}, served by {1}", y, yNode.NodeId); Log("y={0}, served by {1}", y, yNode.NodeId);
Assert.Equal(xNode.NodeId, yNode.NodeId); Assert.Equal(xNode.NodeId, yNode.NodeId);
// wipe those keys // wipe those keys
...@@ -353,8 +353,8 @@ public void TransactionWithSameSlotKeys() ...@@ -353,8 +353,8 @@ public void TransactionWithSameSlotKeys()
Assert.Equal(muxer.HashSlot(x), muxer.HashSlot(y)); Assert.Equal(muxer.HashSlot(x), muxer.HashSlot(y));
var xNode = config.GetBySlot(x); var xNode = config.GetBySlot(x);
var yNode = config.GetBySlot(y); var yNode = config.GetBySlot(y);
Output.WriteLine("x={0}, served by {1}", x, xNode.NodeId); Log("x={0}, served by {1}", x, xNode.NodeId);
Output.WriteLine("y={0}, served by {1}", y, yNode.NodeId); Log("y={0}, served by {1}", y, yNode.NodeId);
Assert.Equal(xNode.NodeId, yNode.NodeId); Assert.Equal(xNode.NodeId, yNode.NodeId);
// wipe those keys // wipe those keys
...@@ -396,11 +396,11 @@ public void Keys(string pattern, int pageSize) ...@@ -396,11 +396,11 @@ public void Keys(string pattern, int pageSize)
try try
{ {
Assert.False(server.Keys(pattern: pattern, pageSize: pageSize).Any()); Assert.False(server.Keys(pattern: pattern, pageSize: pageSize).Any());
Output.WriteLine("Complete: '{0}' / {1}", pattern, pageSize); Log("Complete: '{0}' / {1}", pattern, pageSize);
} }
catch catch
{ {
Output.WriteLine("Failed: '{0}' / {1}", pattern, pageSize); Log("Failed: '{0}' / {1}", pattern, pageSize);
throw; throw;
} }
} }
...@@ -472,17 +472,17 @@ public void GetConfig() ...@@ -472,17 +472,17 @@ public void GetConfig()
var server = muxer.GetServer(endpoints[0]); var server = muxer.GetServer(endpoints[0]);
var nodes = server.ClusterNodes(); var nodes = server.ClusterNodes();
Output.WriteLine("Endpoints:"); Log("Endpoints:");
foreach (var endpoint in endpoints) foreach (var endpoint in endpoints)
{ {
Output.WriteLine(endpoint.ToString()); Log(endpoint.ToString());
} }
Output.WriteLine("Nodes:"); Log("Nodes:");
foreach (var node in nodes.Nodes.OrderBy(x => x)) foreach (var node in nodes.Nodes.OrderBy(x => x))
{ {
Output.WriteLine(node.ToString()); Log(node.ToString());
} }
Output.WriteLine(sw.ToString()); Log(sw.ToString());
Assert.Equal(TestConfig.Current.ClusterServerCount, endpoints.Length); Assert.Equal(TestConfig.Current.ClusterServerCount, endpoints.Length);
Assert.Equal(TestConfig.Current.ClusterServerCount, nodes.Nodes.Count); Assert.Equal(TestConfig.Current.ClusterServerCount, nodes.Nodes.Count);
...@@ -498,7 +498,7 @@ public void AccessRandomKeys() ...@@ -498,7 +498,7 @@ public void AccessRandomKeys()
int slotMovedCount = 0; int slotMovedCount = 0;
conn.HashSlotMoved += (s, a) => conn.HashSlotMoved += (s, a) =>
{ {
Output.WriteLine("{0} moved from {1} to {2}", a.HashSlot, Describe(a.OldEndPoint), Describe(a.NewEndPoint)); Log("{0} moved from {1} to {2}", a.HashSlot, Describe(a.OldEndPoint), Describe(a.NewEndPoint));
Interlocked.Increment(ref slotMovedCount); Interlocked.Increment(ref slotMovedCount);
}; };
var pairs = new Dictionary<string, string>(); var pairs = new Dictionary<string, string>();
...@@ -546,7 +546,7 @@ public void AccessRandomKeys() ...@@ -546,7 +546,7 @@ public void AccessRandomKeys()
if (!server.IsSlave) if (!server.IsSlave)
{ {
int count = server.Keys(pageSize: 100).Count(); int count = server.Keys(pageSize: 100).Count();
Output.WriteLine("{0} has {1} keys", server.EndPoint, count); Log("{0} has {1} keys", server.EndPoint, count);
Interlocked.Add(ref total, count); Interlocked.Add(ref total, count);
} }
}); });
...@@ -554,7 +554,7 @@ public void AccessRandomKeys() ...@@ -554,7 +554,7 @@ public void AccessRandomKeys()
foreach (var server in servers) foreach (var server in servers)
{ {
var counters = server.GetCounters(); var counters = server.GetCounters();
Output.WriteLine(counters.ToString()); Log(counters.ToString());
} }
int final = Interlocked.CompareExchange(ref total, 0, 0); int final = Interlocked.CompareExchange(ref total, 0, 0);
Assert.Equal(COUNT, final); Assert.Equal(COUNT, final);
...@@ -662,7 +662,7 @@ public void GroupedQueriesWork() ...@@ -662,7 +662,7 @@ public void GroupedQueriesWork()
Assert.Equal(keys.Length, grouped.Sum(x => x.Count())); // check they're all there Assert.Equal(keys.Length, grouped.Sum(x => x.Count())); // check they're all there
Assert.Contains(grouped, x => x.Count() > 1); // check at least one group with multiple items (redundant from above, but... meh) Assert.Contains(grouped, x => x.Count() > 1); // check at least one group with multiple items (redundant from above, but... meh)
Output.WriteLine($"{grouped.Count()} groups, min: {grouped.Min(x => x.Count())}, max: {grouped.Max(x => x.Count())}, avg: {grouped.Average(x => x.Count())}"); Log($"{grouped.Count()} groups, min: {grouped.Min(x => x.Count())}, max: {grouped.Max(x => x.Count())}, avg: {grouped.Average(x => x.Count())}");
var db = conn.GetDatabase(0); var db = conn.GetDatabase(0);
var all = grouped.SelectMany(grp => { var all = grouped.SelectMany(grp => {
......
...@@ -26,7 +26,7 @@ public void TalkToNonsenseServer() ...@@ -26,7 +26,7 @@ public void TalkToNonsenseServer()
var log = new StringWriter(); var log = new StringWriter();
using (var conn = ConnectionMultiplexer.Connect(config, log)) using (var conn = ConnectionMultiplexer.Connect(config, log))
{ {
Output.WriteLine(log.ToString()); Log(log.ToString());
Assert.False(conn.IsConnected); Assert.False(conn.IsConnected);
} }
} }
...@@ -41,7 +41,7 @@ public void TestManaulHeartbeat() ...@@ -41,7 +41,7 @@ public void TestManaulHeartbeat()
var before = muxer.OperationCount; var before = muxer.OperationCount;
Output.WriteLine("sleeping to test heartbeat..."); Log("sleeping to test heartbeat...");
Thread.Sleep(TimeSpan.FromSeconds(5)); Thread.Sleep(TimeSpan.FromSeconds(5));
var after = muxer.OperationCount; var after = muxer.OperationCount;
...@@ -120,7 +120,7 @@ public void ReadConfig() ...@@ -120,7 +120,7 @@ public void ReadConfig()
{ {
using (var muxer = Create(allowAdmin: true)) using (var muxer = Create(allowAdmin: true))
{ {
Output.WriteLine("about to get config"); Log("about to get config");
var conn = GetAnyMaster(muxer); var conn = GetAnyMaster(muxer);
var all = conn.ConfigGet(); var all = conn.ConfigGet();
Assert.True(all.Length > 0, "any"); Assert.True(all.Length > 0, "any");
...@@ -144,7 +144,7 @@ public void GetTime() ...@@ -144,7 +144,7 @@ public void GetTime()
{ {
var server = GetAnyMaster(muxer); var server = GetAnyMaster(muxer);
var serverTime = server.Time(); var serverTime = server.Time();
Output.WriteLine(serverTime.ToString()); Log(serverTime.ToString());
var delta = Math.Abs((DateTime.UtcNow - serverTime).TotalSeconds); var delta = Math.Abs((DateTime.UtcNow - serverTime).TotalSeconds);
Assert.True(delta < 5); Assert.True(delta < 5);
...@@ -174,16 +174,16 @@ public void GetInfo() ...@@ -174,16 +174,16 @@ public void GetInfo()
var server = GetAnyMaster(muxer); var server = GetAnyMaster(muxer);
var info1 = server.Info(); var info1 = server.Info();
Assert.True(info1.Length > 5); Assert.True(info1.Length > 5);
Output.WriteLine("All sections"); Log("All sections");
foreach (var group in info1) foreach (var group in info1)
{ {
Output.WriteLine(group.Key); Log(group.Key);
} }
var first = info1[0]; var first = info1[0];
Output.WriteLine("Full info for: " + first.Key); Log("Full info for: " + first.Key);
foreach (var setting in first) foreach (var setting in first)
{ {
Output.WriteLine("{0} ==> {1}", setting.Key, setting.Value); Log("{0} ==> {1}", setting.Key, setting.Value);
} }
var info2 = server.Info("cpu"); var info2 = server.Info("cpu");
...@@ -253,7 +253,7 @@ public void TestAutomaticHeartbeat() ...@@ -253,7 +253,7 @@ public void TestAutomaticHeartbeat()
var before = innerMuxer.OperationCount; var before = innerMuxer.OperationCount;
Output.WriteLine("sleeping to test heartbeat..."); Log("sleeping to test heartbeat...");
Thread.Sleep(TimeSpan.FromSeconds(8)); Thread.Sleep(TimeSpan.FromSeconds(8));
var after = innerMuxer.OperationCount; var after = innerMuxer.OperationCount;
......
...@@ -18,9 +18,9 @@ public async Task NoticesConnectFail() ...@@ -18,9 +18,9 @@ public async Task NoticesConnectFail()
{ {
var server = conn.GetServer(conn.GetEndPoints()[0]); var server = conn.GetServer(conn.GetEndPoints()[0]);
conn.ConnectionFailed += (s, a) => conn.ConnectionFailed += (s, a) =>
Output.WriteLine("Disconnected: " + EndPointCollection.ToString(a.EndPoint)); Log("Disconnected: " + EndPointCollection.ToString(a.EndPoint));
conn.ConnectionRestored += (s, a) => conn.ConnectionRestored += (s, a) =>
Output.WriteLine("Reconnected: " + EndPointCollection.ToString(a.EndPoint)); Log("Reconnected: " + EndPointCollection.ToString(a.EndPoint));
// No need to delay, we're going to try a disconnected connection immediately so it'll fail... // No need to delay, we're going to try a disconnected connection immediately so it'll fail...
conn.IgnoreConnect = true; conn.IgnoreConnect = true;
...@@ -32,7 +32,7 @@ public async Task NoticesConnectFail() ...@@ -32,7 +32,7 @@ public async Task NoticesConnectFail()
await Task.Delay(5000).ConfigureAwait(false); await Task.Delay(5000).ConfigureAwait(false);
var time = server.Ping(); var time = server.Ping();
Output.WriteLine(time.ToString()); Log(time.ToString());
} }
} }
#endif #endif
......
...@@ -33,8 +33,8 @@ public void FailsWithinTimeout() ...@@ -33,8 +33,8 @@ public void FailsWithinTimeout()
catch (RedisConnectionException) catch (RedisConnectionException)
{ {
var elapsed = sw.ElapsedMilliseconds; var elapsed = sw.ElapsedMilliseconds;
Output.WriteLine("Elapsed time: " + elapsed); Log("Elapsed time: " + elapsed);
Output.WriteLine("Timeout: " + timeout); Log("Timeout: " + timeout);
Assert.True(elapsed < 9000, "Connect should fail within ConnectTimeout, ElapsedMs: " + elapsed); Assert.True(elapsed < 9000, "Connect should fail within ConnectTimeout, ElapsedMs: " + elapsed);
} }
} }
......
...@@ -37,7 +37,7 @@ public void FastNoticesFailOnConnectingSyncComlpetion() ...@@ -37,7 +37,7 @@ public void FastNoticesFailOnConnectingSyncComlpetion()
// should reconnect within 1 keepalive interval // should reconnect within 1 keepalive interval
muxer.AllowConnect = true; muxer.AllowConnect = true;
Output.WriteLine("Waiting for reconnect"); Log("Waiting for reconnect");
Thread.Sleep(2000); Thread.Sleep(2000);
Assert.True(muxer.IsConnected); Assert.True(muxer.IsConnected);
...@@ -96,7 +96,7 @@ public void FastNoticesFailOnConnectingAsyncComlpetion() ...@@ -96,7 +96,7 @@ public void FastNoticesFailOnConnectingAsyncComlpetion()
// should reconnect within 1 keepalive interval // should reconnect within 1 keepalive interval
muxer.AllowConnect = true; muxer.AllowConnect = true;
Output.WriteLine("Waiting for reconnect"); Log("Waiting for reconnect");
Thread.Sleep(2000); Thread.Sleep(2000);
Assert.True(muxer.IsConnected); Assert.True(muxer.IsConnected);
......
...@@ -19,12 +19,12 @@ public void ShutdownRaisesConnectionFailedAndRestore() ...@@ -19,12 +19,12 @@ public void ShutdownRaisesConnectionFailedAndRestore()
Stopwatch watch = Stopwatch.StartNew(); Stopwatch watch = Stopwatch.StartNew();
conn.ConnectionFailed += (sender, args) => conn.ConnectionFailed += (sender, args) =>
{ {
Output.WriteLine(watch.Elapsed + ": failed: " + EndPointCollection.ToString(args.EndPoint) + "/" + args.ConnectionType); Log(watch.Elapsed + ": failed: " + EndPointCollection.ToString(args.EndPoint) + "/" + args.ConnectionType);
Interlocked.Increment(ref failed); Interlocked.Increment(ref failed);
}; };
conn.ConnectionRestored += (sender, args) => conn.ConnectionRestored += (sender, args) =>
{ {
Output.WriteLine(watch.Elapsed + ": restored: " + EndPointCollection.ToString(args.EndPoint) + "/" + args.ConnectionType); Log(watch.Elapsed + ": restored: " + EndPointCollection.ToString(args.EndPoint) + "/" + args.ConnectionType);
Interlocked.Increment(ref restored); Interlocked.Increment(ref restored);
}; };
var db = conn.GetDatabase(); var db = conn.GetDatabase();
......
...@@ -58,7 +58,7 @@ public void TestBasicExpiryDateTime(bool disablePTimes, bool utc) ...@@ -58,7 +58,7 @@ public void TestBasicExpiryDateTime(bool disablePTimes, bool utc)
conn.KeyDelete(key, CommandFlags.FireAndForget); conn.KeyDelete(key, CommandFlags.FireAndForget);
var now = utc ? DateTime.UtcNow : DateTime.Now; var now = utc ? DateTime.UtcNow : DateTime.Now;
Output.WriteLine("Now: {0}", now); Log("Now: {0}", now);
conn.StringSet(key, "new value", flags: CommandFlags.FireAndForget); conn.StringSet(key, "new value", flags: CommandFlags.FireAndForget);
var a = conn.KeyTimeToLiveAsync(key); var a = conn.KeyTimeToLiveAsync(key);
conn.KeyExpire(key, now.AddHours(1), CommandFlags.FireAndForget); conn.KeyExpire(key, now.AddHours(1), CommandFlags.FireAndForget);
...@@ -73,7 +73,7 @@ public void TestBasicExpiryDateTime(bool disablePTimes, bool utc) ...@@ -73,7 +73,7 @@ public void TestBasicExpiryDateTime(bool disablePTimes, bool utc)
Assert.Null(muxer.Wait(a)); Assert.Null(muxer.Wait(a));
var time = muxer.Wait(b); var time = muxer.Wait(b);
Assert.NotNull(time); Assert.NotNull(time);
Output.WriteLine("Time: {0}, Expected: {1}-{2}", time, TimeSpan.FromMinutes(59), TimeSpan.FromMinutes(60)); Log("Time: {0}, Expected: {1}-{2}", time, TimeSpan.FromMinutes(59), TimeSpan.FromMinutes(60));
Assert.True(time >= TimeSpan.FromMinutes(59)); Assert.True(time >= TimeSpan.FromMinutes(59));
Assert.True(time <= TimeSpan.FromMinutes(60)); Assert.True(time <= TimeSpan.FromMinutes(60));
Assert.Null(muxer.Wait(c)); Assert.Null(muxer.Wait(c));
......
...@@ -17,14 +17,14 @@ public Failover(ITestOutputHelper output) : base(output) ...@@ -17,14 +17,14 @@ public Failover(ITestOutputHelper output) : base(output)
var shouldBeMaster = mutex.GetServer(TestConfig.Current.FailoverMasterServerAndPort); var shouldBeMaster = mutex.GetServer(TestConfig.Current.FailoverMasterServerAndPort);
if (shouldBeMaster.IsSlave) if (shouldBeMaster.IsSlave)
{ {
Output.WriteLine(shouldBeMaster.EndPoint + " should be master, fixing..."); Log(shouldBeMaster.EndPoint + " should be master, fixing...");
shouldBeMaster.MakeMaster(ReplicationChangeOptions.SetTiebreaker); shouldBeMaster.MakeMaster(ReplicationChangeOptions.SetTiebreaker);
} }
var shouldBeReplica = mutex.GetServer(TestConfig.Current.FailoverSlaveServerAndPort); var shouldBeReplica = mutex.GetServer(TestConfig.Current.FailoverSlaveServerAndPort);
if (!shouldBeReplica.IsSlave) if (!shouldBeReplica.IsSlave)
{ {
Output.WriteLine(shouldBeReplica.EndPoint + " should be a slave, fixing..."); Log(shouldBeReplica.EndPoint + " should be a slave, fixing...");
shouldBeReplica.SlaveOf(shouldBeMaster.EndPoint); shouldBeReplica.SlaveOf(shouldBeMaster.EndPoint);
Thread.Sleep(2000); Thread.Sleep(2000);
} }
...@@ -51,9 +51,9 @@ public async Task ConfigureAsync() ...@@ -51,9 +51,9 @@ public async Task ConfigureAsync()
using (var muxer = Create()) using (var muxer = Create())
{ {
Thread.Sleep(1000); Thread.Sleep(1000);
Output.WriteLine("About to reconfigure....."); Log("About to reconfigure.....");
await muxer.ConfigureAsync().ForAwait(); await muxer.ConfigureAsync().ForAwait();
Output.WriteLine("Reconfigured"); Log("Reconfigured");
} }
} }
...@@ -63,9 +63,9 @@ public void ConfigureSync() ...@@ -63,9 +63,9 @@ public void ConfigureSync()
using (var muxer = Create()) using (var muxer = Create())
{ {
Thread.Sleep(1000); Thread.Sleep(1000);
Output.WriteLine("About to reconfigure....."); Log("About to reconfigure.....");
muxer.Configure(); muxer.Configure();
Output.WriteLine("Reconfigured"); Log("Reconfigured");
} }
} }
...@@ -79,7 +79,7 @@ public async Task ConfigVerifyReceiveConfigChangeBroadcast() ...@@ -79,7 +79,7 @@ public async Task ConfigVerifyReceiveConfigChangeBroadcast()
int total = 0; int total = 0;
receiver.ConfigurationChangedBroadcast += (s, a) => receiver.ConfigurationChangedBroadcast += (s, a) =>
{ {
Output.WriteLine("Config changed: " + (a.EndPoint == null ? "(none)" : a.EndPoint.ToString())); Log("Config changed: " + (a.EndPoint == null ? "(none)" : a.EndPoint.ToString()));
Interlocked.Increment(ref total); Interlocked.Increment(ref total);
}; };
// send a reconfigure/reconnect message // send a reconfigure/reconnect message
...@@ -208,20 +208,20 @@ public async Task SubscriptionsSurviveMasterSwitchAsync() ...@@ -208,20 +208,20 @@ public async Task SubscriptionsSurviveMasterSwitchAsync()
long masterChanged = 0, aCount = 0, bCount = 0; long masterChanged = 0, aCount = 0, bCount = 0;
a.ConfigurationChangedBroadcast += delegate a.ConfigurationChangedBroadcast += delegate
{ {
Output.WriteLine("A noticed config broadcast: " + Interlocked.Increment(ref masterChanged)); Log("A noticed config broadcast: " + Interlocked.Increment(ref masterChanged));
}; };
b.ConfigurationChangedBroadcast += delegate b.ConfigurationChangedBroadcast += delegate
{ {
Output.WriteLine("B noticed config broadcast: " + Interlocked.Increment(ref masterChanged)); Log("B noticed config broadcast: " + Interlocked.Increment(ref masterChanged));
}; };
subA.Subscribe(channel, (_, message) => subA.Subscribe(channel, (_, message) =>
{ {
Output.WriteLine("A got message: " + message); Log("A got message: " + message);
Interlocked.Increment(ref aCount); Interlocked.Increment(ref aCount);
}); });
subB.Subscribe(channel, (_, message) => subB.Subscribe(channel, (_, message) =>
{ {
Output.WriteLine("B got message: " + message); Log("B got message: " + message);
Interlocked.Increment(ref bCount); Interlocked.Increment(ref bCount);
}); });
...@@ -232,8 +232,8 @@ public async Task SubscriptionsSurviveMasterSwitchAsync() ...@@ -232,8 +232,8 @@ public async Task SubscriptionsSurviveMasterSwitchAsync()
var epA = subA.SubscribedEndpoint(channel); var epA = subA.SubscribedEndpoint(channel);
var epB = subB.SubscribedEndpoint(channel); var epB = subB.SubscribedEndpoint(channel);
Output.WriteLine("A: " + EndPointCollection.ToString(epA)); Log("A: " + EndPointCollection.ToString(epA));
Output.WriteLine("B: " + EndPointCollection.ToString(epB)); Log("B: " + EndPointCollection.ToString(epB));
subA.Publish(channel, "A1"); subA.Publish(channel, "A1");
subB.Publish(channel, "B1"); subB.Publish(channel, "B1");
subA.Ping(); subA.Ping();
...@@ -248,41 +248,41 @@ public async Task SubscriptionsSurviveMasterSwitchAsync() ...@@ -248,41 +248,41 @@ public async Task SubscriptionsSurviveMasterSwitchAsync()
Interlocked.Exchange(ref masterChanged, 0); Interlocked.Exchange(ref masterChanged, 0);
Interlocked.Exchange(ref aCount, 0); Interlocked.Exchange(ref aCount, 0);
Interlocked.Exchange(ref bCount, 0); Interlocked.Exchange(ref bCount, 0);
Output.WriteLine("Changing master..."); Log("Changing master...");
using (var sw = new StringWriter()) using (var sw = new StringWriter())
{ {
a.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).MakeMaster(ReplicationChangeOptions.All, sw); a.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).MakeMaster(ReplicationChangeOptions.All, sw);
Output.WriteLine(sw.ToString()); Log(sw.ToString());
} }
await Task.Delay(5000).ForAwait(); await Task.Delay(5000).ForAwait();
subA.Ping(); subA.Ping();
subB.Ping(); subB.Ping();
Output.WriteLine("Pausing..."); Log("Pausing...");
Output.WriteLine("A " + TestConfig.Current.FailoverMasterServerAndPort + " status: " + (a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsSlave ? "Slave" : "Master")); Log("A " + TestConfig.Current.FailoverMasterServerAndPort + " status: " + (a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsSlave ? "Slave" : "Master"));
Output.WriteLine("A " + TestConfig.Current.FailoverSlaveServerAndPort + " status: " + (a.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).IsSlave ? "Slave" : "Master")); Log("A " + TestConfig.Current.FailoverSlaveServerAndPort + " status: " + (a.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).IsSlave ? "Slave" : "Master"));
Output.WriteLine("B " + TestConfig.Current.FailoverMasterServerAndPort + " status: " + (b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsSlave ? "Slave" : "Master")); Log("B " + TestConfig.Current.FailoverMasterServerAndPort + " status: " + (b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsSlave ? "Slave" : "Master"));
Output.WriteLine("B " + TestConfig.Current.FailoverSlaveServerAndPort + " status: " + (b.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).IsSlave ? "Slave" : "Master")); Log("B " + TestConfig.Current.FailoverSlaveServerAndPort + " status: " + (b.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).IsSlave ? "Slave" : "Master"));
Assert.True(a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsSlave, $"A Connection: {TestConfig.Current.FailoverMasterServerAndPort} should be a slave"); Assert.True(a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsSlave, $"A Connection: {TestConfig.Current.FailoverMasterServerAndPort} should be a slave");
Assert.False(a.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).IsSlave, $"A Connection: {TestConfig.Current.FailoverSlaveServerAndPort} should be a master"); Assert.False(a.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).IsSlave, $"A Connection: {TestConfig.Current.FailoverSlaveServerAndPort} should be a master");
Assert.True(b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsSlave, $"B Connection: {TestConfig.Current.FailoverMasterServerAndPort} should be a slave"); Assert.True(b.GetServer(TestConfig.Current.FailoverMasterServerAndPort).IsSlave, $"B Connection: {TestConfig.Current.FailoverMasterServerAndPort} should be a slave");
Assert.False(b.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).IsSlave, $"B Connection: {TestConfig.Current.FailoverSlaveServerAndPort} should be a master"); Assert.False(b.GetServer(TestConfig.Current.FailoverSlaveServerAndPort).IsSlave, $"B Connection: {TestConfig.Current.FailoverSlaveServerAndPort} should be a master");
Output.WriteLine("Pause complete"); Log("Pause complete");
Output.WriteLine("A outstanding: " + a.GetCounters().TotalOutstanding); Log("A outstanding: " + a.GetCounters().TotalOutstanding);
Output.WriteLine("B outstanding: " + b.GetCounters().TotalOutstanding); Log("B outstanding: " + b.GetCounters().TotalOutstanding);
subA.Ping(); subA.Ping();
subB.Ping(); subB.Ping();
await Task.Delay(2000).ForAwait(); await Task.Delay(2000).ForAwait();
epA = subA.SubscribedEndpoint(channel); epA = subA.SubscribedEndpoint(channel);
epB = subB.SubscribedEndpoint(channel); epB = subB.SubscribedEndpoint(channel);
Output.WriteLine("A: " + EndPointCollection.ToString(epA)); Log("A: " + EndPointCollection.ToString(epA));
Output.WriteLine("B: " + EndPointCollection.ToString(epB)); Log("B: " + EndPointCollection.ToString(epB));
Output.WriteLine("A2 sent to: " + subA.Publish(channel, "A2")); Log("A2 sent to: " + subA.Publish(channel, "A2"));
Output.WriteLine("B2 sent to: " + subB.Publish(channel, "B2")); Log("B2 sent to: " + subB.Publish(channel, "B2"));
subA.Ping(); subA.Ping();
subB.Ping(); subB.Ping();
Output.WriteLine("Checking..."); Log("Checking...");
Assert.Equal(2, Interlocked.Read(ref aCount)); Assert.Equal(2, Interlocked.Read(ref aCount));
Assert.Equal(2, Interlocked.Read(ref bCount)); Assert.Equal(2, Interlocked.Read(ref bCount));
...@@ -291,7 +291,7 @@ public async Task SubscriptionsSurviveMasterSwitchAsync() ...@@ -291,7 +291,7 @@ public async Task SubscriptionsSurviveMasterSwitchAsync()
} }
finally finally
{ {
Output.WriteLine("Restoring configuration..."); Log("Restoring configuration...");
try try
{ {
a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).MakeMaster(ReplicationChangeOptions.All); a.GetServer(TestConfig.Current.FailoverMasterServerAndPort).MakeMaster(ReplicationChangeOptions.All);
......
...@@ -44,6 +44,7 @@ static TestConfig() ...@@ -44,6 +44,7 @@ static TestConfig()
public class Config public class Config
{ {
public bool RunLongRunning { get; set; } public bool RunLongRunning { get; set; }
public bool LogToConsole { get; set; }
public string MasterServer { get; set; } = "127.0.0.1"; public string MasterServer { get; set; } = "127.0.0.1";
public int MasterPort { get; set; } = 6379; public int MasterPort { get; set; } = 6379;
......
...@@ -10,7 +10,8 @@ public class TextWriterOutputHelper : TextWriter ...@@ -10,7 +10,8 @@ public class TextWriterOutputHelper : TextWriter
private StringBuilder Buffer { get; } = new StringBuilder(2048); private StringBuilder Buffer { get; } = new StringBuilder(2048);
public override Encoding Encoding => Encoding.UTF8; public override Encoding Encoding => Encoding.UTF8;
private readonly ITestOutputHelper Output; private readonly ITestOutputHelper Output;
public TextWriterOutputHelper(ITestOutputHelper outputHelper) => Output = outputHelper; private readonly bool ToConsole;
public TextWriterOutputHelper(ITestOutputHelper outputHelper, bool echoToConsole) => (Output, ToConsole) = (outputHelper, echoToConsole);
public override void WriteLine(string value) public override void WriteLine(string value)
{ {
...@@ -57,6 +58,10 @@ private void FlushBuffer() ...@@ -57,6 +58,10 @@ private void FlushBuffer()
{ {
var text = Buffer.ToString(); var text = Buffer.ToString();
Output.WriteLine(text); Output.WriteLine(text);
if (ToConsole)
{
Console.WriteLine(text);
}
Buffer.Clear(); Buffer.Clear();
} }
} }
......
...@@ -35,7 +35,7 @@ public void ConfigurationOptions_UnspecifiedDefaultDb() ...@@ -35,7 +35,7 @@ public void ConfigurationOptions_UnspecifiedDefaultDb()
} }
finally finally
{ {
Output.WriteLine(log.ToString()); Log(log.ToString());
} }
} }
...@@ -52,7 +52,7 @@ public void ConfigurationOptions_SpecifiedDefaultDb() ...@@ -52,7 +52,7 @@ public void ConfigurationOptions_SpecifiedDefaultDb()
} }
finally finally
{ {
Output.WriteLine(log.ToString()); Log(log.ToString());
} }
} }
} }
......
...@@ -19,9 +19,9 @@ public async Task SetMembers() ...@@ -19,9 +19,9 @@ public async Task SetMembers()
{ {
conn.ConnectionFailed += (s, a) => conn.ConnectionFailed += (s, a) =>
{ {
Output.WriteLine(a.FailureType.ToString()); Log(a.FailureType.ToString());
Output.WriteLine(a.Exception.Message); Log(a.Exception.Message);
Output.WriteLine(a.Exception.StackTrace); Log(a.Exception.StackTrace);
}; };
var db = conn.GetDatabase(); var db = conn.GetDatabase();
......
...@@ -12,10 +12,10 @@ public void ShouldWorkWithoutEchoOrPing() ...@@ -12,10 +12,10 @@ public void ShouldWorkWithoutEchoOrPing()
{ {
using(var conn = Create(proxy: Proxy.Twemproxy)) using(var conn = Create(proxy: Proxy.Twemproxy))
{ {
Output.WriteLine("config: " + conn.Configuration); Log("config: " + conn.Configuration);
var db = conn.GetDatabase(); var db = conn.GetDatabase();
var time = db.Ping(); var time = db.Ping();
Output.WriteLine("ping time: " + time); Log("ping time: " + time);
} }
} }
} }
......
...@@ -29,7 +29,7 @@ public void Execute() ...@@ -29,7 +29,7 @@ public void Execute()
var watch = Stopwatch.StartNew(); var watch = Stopwatch.StartNew();
var isOperationSuccessful = tran.Execute(); var isOperationSuccessful = tran.Execute();
watch.Stop(); watch.Stop();
Output.WriteLine("{0}ms", watch.ElapsedMilliseconds); Log("{0}ms", watch.ElapsedMilliseconds);
Assert.True(isOperationSuccessful); Assert.True(isOperationSuccessful);
} }
} }
......
...@@ -36,7 +36,7 @@ public async Task MassiveBulkOpsAsync(bool withContinuation) ...@@ -36,7 +36,7 @@ public async Task MassiveBulkOpsAsync(bool withContinuation)
} }
Assert.Equal(AsyncOpsQty, await conn.StringGetAsync(key).ForAwait()); Assert.Equal(AsyncOpsQty, await conn.StringGetAsync(key).ForAwait());
watch.Stop(); watch.Stop();
Output.WriteLine("{2}: Time for {0} ops: {1}ms ({3}, any order); ops/s: {4}", AsyncOpsQty, watch.ElapsedMilliseconds, Me(), Log("{2}: Time for {0} ops: {1}ms ({3}, any order); ops/s: {4}", AsyncOpsQty, watch.ElapsedMilliseconds, Me(),
withContinuation ? "with continuation" : "no continuation", AsyncOpsQty / watch.Elapsed.TotalSeconds); withContinuation ? "with continuation" : "no continuation", AsyncOpsQty / watch.Elapsed.TotalSeconds);
} }
} }
...@@ -67,11 +67,11 @@ public void MassiveBulkOpsSync(int threads) ...@@ -67,11 +67,11 @@ public void MassiveBulkOpsSync(int threads)
int val = (int)conn.StringGet(key); int val = (int)conn.StringGet(key);
Assert.Equal(workPerThread * threads, val); Assert.Equal(workPerThread * threads, val);
Output.WriteLine("{2}: Time for {0} ops on {3} threads: {1}ms (any order); ops/s: {4}", Log("{2}: Time for {0} ops on {3} threads: {1}ms (any order); ops/s: {4}",
threads * workPerThread, timeTaken.TotalMilliseconds, Me(), threads, (workPerThread * threads) / timeTaken.TotalSeconds); threads * workPerThread, timeTaken.TotalMilliseconds, Me(), threads, (workPerThread * threads) / timeTaken.TotalSeconds);
#if DEBUG #if DEBUG
long newAlloc = ConnectionMultiplexer.GetResultBoxAllocationCount(); long newAlloc = ConnectionMultiplexer.GetResultBoxAllocationCount();
Output.WriteLine("ResultBox allocations: {0}", newAlloc - oldAlloc); Log("ResultBox allocations: {0}", newAlloc - oldAlloc);
Assert.True(newAlloc - oldAlloc <= 2 * threads, "number of box allocations"); Assert.True(newAlloc - oldAlloc <= 2 * threads, "number of box allocations");
#endif #endif
} }
...@@ -104,12 +104,12 @@ public void MassiveBulkOpsFireAndForget(int threads) ...@@ -104,12 +104,12 @@ public void MassiveBulkOpsFireAndForget(int threads)
var val = (long)conn.StringGet(key); var val = (long)conn.StringGet(key);
Assert.Equal(perThread * threads, val); Assert.Equal(perThread * threads, val);
Output.WriteLine("{2}: Time for {0} ops over {4} threads: {1:###,###}ms (any order); ops/s: {3:###,###,##0}", Log("{2}: Time for {0} ops over {4} threads: {1:###,###}ms (any order); ops/s: {3:###,###,##0}",
val, elapsed.TotalMilliseconds, Me(), val, elapsed.TotalMilliseconds, Me(),
val / elapsed.TotalSeconds, threads); val / elapsed.TotalSeconds, threads);
#if DEBUG #if DEBUG
long newAlloc = ConnectionMultiplexer.GetResultBoxAllocationCount(); long newAlloc = ConnectionMultiplexer.GetResultBoxAllocationCount();
Output.WriteLine("ResultBox allocations: {0}", Log("ResultBox allocations: {0}",
newAlloc - oldAlloc); newAlloc - oldAlloc);
Assert.True(newAlloc - oldAlloc <= 4); Assert.True(newAlloc - oldAlloc <= 4);
#endif #endif
......
...@@ -34,7 +34,7 @@ public void TestMultiNoTieBreak() ...@@ -34,7 +34,7 @@ public void TestMultiNoTieBreak()
using (var log = new StringWriter()) using (var log = new StringWriter())
using (var conn = Create(log: log, tieBreaker: "")) using (var conn = Create(log: log, tieBreaker: ""))
{ {
Output.WriteLine(log.ToString()); Log(log.ToString());
Assert.Contains("Choosing master arbitrarily", log.ToString()); Assert.Contains("Choosing master arbitrarily", log.ToString());
} }
} }
...@@ -72,7 +72,7 @@ public void TestMultiWithTiebreak(string a, string b, string elected) ...@@ -72,7 +72,7 @@ public void TestMultiWithTiebreak(string a, string b, string elected)
using (var conn = Create(log: log, tieBreaker: TieBreak)) using (var conn = Create(log: log, tieBreaker: TieBreak))
{ {
string text = log.ToString(); string text = log.ToString();
Output.WriteLine(text); Log(text);
Assert.False(text.Contains("failed to nominate"), "failed to nominate"); Assert.False(text.Contains("failed to nominate"), "failed to nominate");
if (elected != null) if (elected != null)
{ {
......
...@@ -8,10 +8,9 @@ ...@@ -8,10 +8,9 @@
namespace StackExchange.Redis.Tests namespace StackExchange.Redis.Tests
{ {
public class Naming public class Naming : TestBase
{ {
public ITestOutputHelper Output; public Naming(ITestOutputHelper output) : base(output) { }
public Naming(ITestOutputHelper output) => Output = output;
[Theory] [Theory]
[InlineData(typeof(IDatabase), false)] [InlineData(typeof(IDatabase), false)]
...@@ -50,21 +49,21 @@ public void ShowReadOnlyOperations() ...@@ -50,21 +49,21 @@ public void ShowReadOnlyOperations()
if (!isMasterOnly) if (!isMasterOnly)
{ {
Output.WriteLine(val?.ToString()); Log(val?.ToString());
} }
} }
Output.WriteLine("master-only: {0}, vs master/slave: {1}", masterOnly.Count, masterSlave.Count); Log("master-only: {0}, vs master/slave: {1}", masterOnly.Count, masterSlave.Count);
Output.WriteLine(""); Log("");
Output.WriteLine("master-only:"); Log("master-only:");
foreach (var val in masterOnly) foreach (var val in masterOnly)
{ {
Output.WriteLine(val?.ToString()); Log(val?.ToString());
} }
Output.WriteLine(""); Log("");
Output.WriteLine("master/slave:"); Log("master/slave:");
foreach (var val in masterSlave) foreach (var val in masterSlave)
{ {
Output.WriteLine(val?.ToString()); Log(val?.ToString());
} }
} }
...@@ -169,7 +168,7 @@ public void CheckSyncAsyncMethodsMatch(Type from, Type to) ...@@ -169,7 +168,7 @@ public void CheckSyncAsyncMethodsMatch(Type from, Type to)
} }
var pFrom = method.GetParameters(); var pFrom = method.GetParameters();
Type[] args = pFrom.Select(x => x.ParameterType).ToArray(); Type[] args = pFrom.Select(x => x.ParameterType).ToArray();
Output.WriteLine("Checking: {0}.{1}", from.Name, method.Name); Log("Checking: {0}.{1}", from.Name, method.Name);
Assert.Equal(typeof(CommandFlags), args.Last()); Assert.Equal(typeof(CommandFlags), args.Last());
var found = to.GetMethod(huntName, flags, null, method.CallingConvention, args, null); var found = to.GetMethod(huntName, flags, null, method.CallingConvention, args, null);
Assert.NotNull(found); // "Found " + name + ", no " + huntName Assert.NotNull(found); // "Found " + name + ", no " + huntName
...@@ -183,7 +182,7 @@ public void CheckSyncAsyncMethodsMatch(Type from, Type to) ...@@ -183,7 +182,7 @@ public void CheckSyncAsyncMethodsMatch(Type from, Type to)
count++; count++;
} }
Output.WriteLine("Validated: {0} ({1} methods)", from.Name, count); Log("Validated: {0} ({1} methods)", from.Name, count);
} }
private static readonly Type ignoreType = typeof(ConnectionMultiplexer).Assembly.GetType("StackExchange.Redis.IgnoreNamePrefixAttribute"); private static readonly Type ignoreType = typeof(ConnectionMultiplexer).Assembly.GetType("StackExchange.Redis.IgnoreNamePrefixAttribute");
......
...@@ -18,7 +18,7 @@ public void Execute() ...@@ -18,7 +18,7 @@ public void Execute()
{ {
var sub = conn.GetSubscriber(); var sub = conn.GetSubscriber();
var received = new List<int>(); var received = new List<int>();
Output.WriteLine("Subscribing..."); Log("Subscribing...");
const int COUNT = 1000; const int COUNT = 1000;
sub.Subscribe("foo", (channel, message) => sub.Subscribe("foo", (channel, message) =>
{ {
...@@ -31,8 +31,8 @@ public void Execute() ...@@ -31,8 +31,8 @@ public void Execute()
Thread.Sleep(1); // you kinda need to be slow, otherwise Thread.Sleep(1); // you kinda need to be slow, otherwise
// the pool will end up doing everything on one thread // the pool will end up doing everything on one thread
}); });
Output.WriteLine(""); Log("");
Output.WriteLine("Sending (any order)..."); Log("Sending (any order)...");
lock (received) lock (received)
{ {
received.Clear(); received.Clear();
...@@ -45,23 +45,23 @@ public void Execute() ...@@ -45,23 +45,23 @@ public void Execute()
sub.Publish("foo", i); sub.Publish("foo", i);
} }
Output.WriteLine("Allowing time for delivery etc..."); Log("Allowing time for delivery etc...");
var watch = Stopwatch.StartNew(); var watch = Stopwatch.StartNew();
if (!Monitor.Wait(received, 10000)) if (!Monitor.Wait(received, 10000))
{ {
Output.WriteLine("Timed out; expect less data"); Log("Timed out; expect less data");
} }
watch.Stop(); watch.Stop();
Output.WriteLine("Checking..."); Log("Checking...");
lock (received) lock (received)
{ {
Output.WriteLine("Received: {0} in {1}ms", received.Count, watch.ElapsedMilliseconds); Log("Received: {0} in {1}ms", received.Count, watch.ElapsedMilliseconds);
int wrongOrder = 0; int wrongOrder = 0;
for (int i = 0; i < Math.Min(COUNT, received.Count); i++) for (int i = 0; i < Math.Min(COUNT, received.Count); i++)
{ {
if (received[i] != i) wrongOrder++; if (received[i] != i) wrongOrder++;
} }
Output.WriteLine("Out of order: " + wrongOrder); Log("Out of order: " + wrongOrder);
} }
} }
} }
......
...@@ -69,7 +69,7 @@ public void TestBasicPubSub(string channelPrefix, bool wildCard, string breaker) ...@@ -69,7 +69,7 @@ public void TestBasicPubSub(string channelPrefix, bool wildCard, string breaker)
} }
else else
{ {
Output.WriteLine((string)channel); Log((string)channel);
} }
} }
} }
......
...@@ -11,21 +11,21 @@ public class RealWorld : TestBase ...@@ -11,21 +11,21 @@ public class RealWorld : TestBase
[Fact] [Fact]
public void WhyDoesThisNotWork() public void WhyDoesThisNotWork()
{ {
Output.WriteLine("first:"); Log("first:");
var config = ConfigurationOptions.Parse("localhost:6379,localhost:6380,name=Core (Q&A),tiebreaker=:RedisMaster,abortConnect=False"); var config = ConfigurationOptions.Parse("localhost:6379,localhost:6380,name=Core (Q&A),tiebreaker=:RedisMaster,abortConnect=False");
Assert.Equal(2, config.EndPoints.Count); Assert.Equal(2, config.EndPoints.Count);
Output.WriteLine("Endpoint 0: {0} (AddressFamily: {1})", config.EndPoints[0], config.EndPoints[0].AddressFamily); Log("Endpoint 0: {0} (AddressFamily: {1})", config.EndPoints[0], config.EndPoints[0].AddressFamily);
Output.WriteLine("Endpoint 1: {0} (AddressFamily: {1})", config.EndPoints[1], config.EndPoints[1].AddressFamily); Log("Endpoint 1: {0} (AddressFamily: {1})", config.EndPoints[1], config.EndPoints[1].AddressFamily);
using (var conn = ConnectionMultiplexer.Connect("localhost:6379,localhost:6380,name=Core (Q&A),tiebreaker=:RedisMaster,abortConnect=False", Writer)) using (var conn = ConnectionMultiplexer.Connect("localhost:6379,localhost:6380,name=Core (Q&A),tiebreaker=:RedisMaster,abortConnect=False", Writer))
{ {
Output.WriteLine(""); Log("");
Output.WriteLine("pausing..."); Log("pausing...");
Thread.Sleep(200); Thread.Sleep(200);
Output.WriteLine("second:"); Log("second:");
bool result = conn.Configure(Writer); bool result = conn.Configure(Writer);
Output.WriteLine("Returned: {0}", result); Log("Returned: {0}", result);
} }
} }
} }
......
...@@ -33,11 +33,11 @@ public void ConnectToAzure(int? port, bool ssl) ...@@ -33,11 +33,11 @@ public void ConnectToAzure(int? port, bool ssl)
} }
options.Ssl = ssl; options.Ssl = ssl;
options.Password = TestConfig.Current.AzureCachePassword; options.Password = TestConfig.Current.AzureCachePassword;
Output.WriteLine(options.ToString()); Log(options.ToString());
using (var connection = ConnectionMultiplexer.Connect(options)) using (var connection = ConnectionMultiplexer.Connect(options))
{ {
var ttl = connection.GetDatabase().Ping(); var ttl = connection.GetDatabase().Ping();
Output.WriteLine(ttl.ToString()); Log(ttl.ToString());
} }
} }
...@@ -83,23 +83,23 @@ public async Task ConnectToSSLServer(bool useSsl, bool specifyHost) ...@@ -83,23 +83,23 @@ public async Task ConnectToSSLServer(bool useSsl, bool specifyHost)
} }
config.CertificateValidation += (sender, cert, chain, errors) => config.CertificateValidation += (sender, cert, chain, errors) =>
{ {
Output.WriteLine("errors: " + errors); Log("errors: " + errors);
Output.WriteLine("cert issued to: " + cert.Subject); Log("cert issued to: " + cert.Subject);
return true; // fingers in ears, pretend we don't know this is wrong return true; // fingers in ears, pretend we don't know this is wrong
}; };
} }
var configString = config.ToString(); var configString = config.ToString();
Output.WriteLine("config: " + configString); Log("config: " + configString);
var clone = ConfigurationOptions.Parse(configString); var clone = ConfigurationOptions.Parse(configString);
Assert.Equal(configString, clone.ToString()); Assert.Equal(configString, clone.ToString());
using (var log = new StringWriter()) using (var log = new StringWriter())
using (var muxer = ConnectionMultiplexer.Connect(config, log)) using (var muxer = ConnectionMultiplexer.Connect(config, log))
{ {
Output.WriteLine("Connect log:"); Log("Connect log:");
Output.WriteLine(log.ToString()); Log(log.ToString());
Output.WriteLine("===="); Log("====");
muxer.ConnectionFailed += OnConnectionFailed; muxer.ConnectionFailed += OnConnectionFailed;
muxer.InternalError += OnInternalError; muxer.InternalError += OnInternalError;
var db = muxer.GetDatabase(); var db = muxer.GetDatabase();
...@@ -122,7 +122,7 @@ public async Task ConnectToSSLServer(bool useSsl, bool specifyHost) ...@@ -122,7 +122,7 @@ public async Task ConnectToSSLServer(bool useSsl, bool specifyHost)
} }
catch (Exception ex) catch (Exception ex)
{ {
Output.WriteLine($"Failure on i={i}: {ex.Message}"); Log($"Failure on i={i}: {ex.Message}");
throw; throw;
} }
} }
...@@ -130,7 +130,7 @@ public async Task ConnectToSSLServer(bool useSsl, bool specifyHost) ...@@ -130,7 +130,7 @@ public async Task ConnectToSSLServer(bool useSsl, bool specifyHost)
long value = (long)await db.StringGetAsync(key); long value = (long)await db.StringGetAsync(key);
watch.Stop(); watch.Stop();
Assert.Equal(AsyncLoop, value); Assert.Equal(AsyncLoop, value);
Output.WriteLine("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}", Log("F&F: {0} INCR, {1:###,##0}ms, {2} ops/s; final value: {3}",
AsyncLoop, AsyncLoop,
(long)watch.ElapsedMilliseconds, (long)watch.ElapsedMilliseconds,
(long)(AsyncLoop / watch.Elapsed.TotalSeconds), (long)(AsyncLoop / watch.Elapsed.TotalSeconds),
...@@ -158,7 +158,7 @@ private void TestConcurrent(IDatabase db, RedisKey key, int SyncLoop, int Thread ...@@ -158,7 +158,7 @@ private void TestConcurrent(IDatabase db, RedisKey key, int SyncLoop, int Thread
}, Threads, timeout: 45000); }, Threads, timeout: 45000);
value = (long)db.StringGet(key); value = (long)db.StringGet(key);
Assert.Equal(SyncLoop * Threads, value); Assert.Equal(SyncLoop * Threads, value);
Output.WriteLine("Sync: {0} INCR using {1} threads, {2:###,##0}ms, {3} ops/s; final value: {4}", Log("Sync: {0} INCR using {1} threads, {2:###,##0}ms, {3} ops/s; final value: {4}",
SyncLoop * Threads, Threads, SyncLoop * Threads, Threads,
(long)time.TotalMilliseconds, (long)time.TotalMilliseconds,
(long)((SyncLoop * Threads) / time.TotalSeconds), (long)((SyncLoop * Threads) / time.TotalSeconds),
...@@ -203,7 +203,7 @@ public void RedisLabsSSL() ...@@ -203,7 +203,7 @@ public void RedisLabsSSL()
Assert.Equal("abc", s); Assert.Equal("abc", s);
var latency = db.Ping(); var latency = db.Ping();
Output.WriteLine("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds); Log("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds);
using (var file = File.Create("RedisLabs.zip")) using (var file = File.Create("RedisLabs.zip"))
{ {
...@@ -256,7 +256,7 @@ public void RedisLabsEnvironmentVariableClientCertificate(bool setEnv) ...@@ -256,7 +256,7 @@ public void RedisLabsEnvironmentVariableClientCertificate(bool setEnv)
Assert.Equal("abc", s); Assert.Equal("abc", s);
var latency = db.Ping(); var latency = db.Ping();
Output.WriteLine("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds); Log("RedisLabs latency: {0:###,##0.##}ms", latency.TotalMilliseconds);
using (var file = File.Create("RedisLabs.zip")) using (var file = File.Create("RedisLabs.zip"))
{ {
......
...@@ -117,7 +117,7 @@ public void ScanResume() ...@@ -117,7 +117,7 @@ public void ScanResume()
snapCursor = ((IScanningCursor)seq).Cursor; snapCursor = ((IScanningCursor)seq).Cursor;
snapOffset = ((IScanningCursor)seq).PageOffset; snapOffset = ((IScanningCursor)seq).PageOffset;
snapPageSize = ((IScanningCursor)seq).PageSize; snapPageSize = ((IScanningCursor)seq).PageSize;
Output.WriteLine($"i: {i}, Cursor: {snapCursor}, Offset: {snapOffset}, PageSize: {snapPageSize}"); Log($"i: {i}, Cursor: {snapCursor}, Offset: {snapOffset}, PageSize: {snapPageSize}");
} }
if (i >= 57) if (i >= 57)
{ {
...@@ -125,7 +125,7 @@ public void ScanResume() ...@@ -125,7 +125,7 @@ public void ScanResume()
} }
i++; i++;
} }
Output.WriteLine($"Expected: 43, Actual: {expected.Count}, Cursor: {snapCursor}, Offset: {snapOffset}, PageSize: {snapPageSize}"); Log($"Expected: 43, Actual: {expected.Count}, Cursor: {snapCursor}, Offset: {snapOffset}, PageSize: {snapPageSize}");
Assert.Equal(43, expected.Count); Assert.Equal(43, expected.Count);
Assert.NotEqual(0, snapCursor); Assert.NotEqual(0, snapCursor);
Assert.Equal(15, snapPageSize); Assert.Equal(15, snapPageSize);
......
...@@ -141,7 +141,7 @@ public void CompareScriptToDirect() ...@@ -141,7 +141,7 @@ public void CompareScriptToDirect()
Assert.Equal(LOOP, (long)scriptResult); Assert.Equal(LOOP, (long)scriptResult);
Assert.Equal(LOOP, directResult); Assert.Equal(LOOP, directResult);
Output.WriteLine("script: {0}ms; direct: {1}ms", Log("script: {0}ms; direct: {1}ms",
scriptTime.TotalMilliseconds, scriptTime.TotalMilliseconds,
directTime.TotalMilliseconds); directTime.TotalMilliseconds);
} }
......
...@@ -35,11 +35,11 @@ public void MassiveBulkOpsFireAndForgetSecure() ...@@ -35,11 +35,11 @@ public void MassiveBulkOpsFireAndForgetSecure()
int val = (int)conn.StringGet(key); int val = (int)conn.StringGet(key);
Assert.Equal(AsyncOpsQty, val); Assert.Equal(AsyncOpsQty, val);
watch.Stop(); watch.Stop();
Output.WriteLine("{2}: Time for {0} ops: {1}ms (any order); ops/s: {3}", AsyncOpsQty, watch.ElapsedMilliseconds, Me(), Log("{2}: Time for {0} ops: {1}ms (any order); ops/s: {3}", AsyncOpsQty, watch.ElapsedMilliseconds, Me(),
AsyncOpsQty / watch.Elapsed.TotalSeconds); AsyncOpsQty / watch.Elapsed.TotalSeconds);
#if DEBUG #if DEBUG
long newAlloc = ConnectionMultiplexer.GetResultBoxAllocationCount(); long newAlloc = ConnectionMultiplexer.GetResultBoxAllocationCount();
Output.WriteLine("ResultBox allocations: {0}", newAlloc - oldAlloc); Log("ResultBox allocations: {0}", newAlloc - oldAlloc);
Assert.True(newAlloc - oldAlloc <= 2, $"NewAllocs: {newAlloc}, OldAllocs: {oldAlloc}"); Assert.True(newAlloc - oldAlloc <= 2, $"NewAllocs: {newAlloc}, OldAllocs: {oldAlloc}");
#endif #endif
} }
...@@ -51,7 +51,7 @@ public void CheckConfig() ...@@ -51,7 +51,7 @@ public void CheckConfig()
var config = ConfigurationOptions.Parse(GetConfiguration()); var config = ConfigurationOptions.Parse(GetConfiguration());
foreach (var ep in config.EndPoints) foreach (var ep in config.EndPoints)
{ {
Output.WriteLine(ep.ToString()); Log(ep.ToString());
} }
Assert.Single(config.EndPoints); Assert.Single(config.EndPoints);
Assert.Equal("changeme", config.Password); Assert.Equal("changeme", config.Password);
...@@ -83,7 +83,7 @@ public async Task ConnectWithWrongPassword(string password) ...@@ -83,7 +83,7 @@ public async Task ConnectWithWrongPassword(string password)
conn.GetDatabase().Ping(); conn.GetDatabase().Ping();
} }
}).ConfigureAwait(false); }).ConfigureAwait(false);
Output.WriteLine("Exception: " + ex.Message); Log("Exception: " + ex.Message);
Assert.StartsWith("It was not possible to connect to the redis server(s). There was an authentication failure; check that passwords (or client certificates) are configured correctly.", ex.Message); Assert.StartsWith("It was not possible to connect to the redis server(s). There was an authentication failure; check that passwords (or client certificates) are configured correctly.", ex.Message);
} }
} }
......
...@@ -7,19 +7,17 @@ ...@@ -7,19 +7,17 @@
namespace StackExchange.Redis.Tests namespace StackExchange.Redis.Tests
{ {
public class Sentinel public class Sentinel : TestBase
{ {
private string ServiceName => TestConfig.Current.SentinelSeviceName; private string ServiceName => TestConfig.Current.SentinelSeviceName;
private ConnectionMultiplexer Conn { get; } private ConnectionMultiplexer Conn { get; }
private IServer Server { get; } private IServer Server { get; }
protected StringWriter Log { get; } protected StringWriter ConnectionLog { get; }
public ITestOutputHelper Output { get; } public Sentinel(ITestOutputHelper output) : base(output)
public Sentinel(ITestOutputHelper output)
{ {
Output = output; ConnectionLog = new StringWriter();
Log = new StringWriter();
Skip.IfNoConfig(nameof(TestConfig.Config.SentinelServer), TestConfig.Current.SentinelServer); Skip.IfNoConfig(nameof(TestConfig.Config.SentinelServer), TestConfig.Current.SentinelServer);
Skip.IfNoConfig(nameof(TestConfig.Config.SentinelSeviceName), TestConfig.Current.SentinelSeviceName); Skip.IfNoConfig(nameof(TestConfig.Config.SentinelSeviceName), TestConfig.Current.SentinelSeviceName);
...@@ -33,7 +31,7 @@ public Sentinel(ITestOutputHelper output) ...@@ -33,7 +31,7 @@ public Sentinel(ITestOutputHelper output)
ServiceName = TestConfig.Current.SentinelSeviceName, ServiceName = TestConfig.Current.SentinelSeviceName,
SyncTimeout = 5000 SyncTimeout = 5000
}; };
Conn = ConnectionMultiplexer.Connect(options, Log); Conn = ConnectionMultiplexer.Connect(options, ConnectionLog);
Thread.Sleep(3000); Thread.Sleep(3000);
Assert.True(Conn.IsConnected); Assert.True(Conn.IsConnected);
Server = Conn.GetServer(TestConfig.Current.SentinelServer, TestConfig.Current.SentinelPort); Server = Conn.GetServer(TestConfig.Current.SentinelServer, TestConfig.Current.SentinelPort);
...@@ -43,7 +41,7 @@ public Sentinel(ITestOutputHelper output) ...@@ -43,7 +41,7 @@ public Sentinel(ITestOutputHelper output)
public void PingTest() public void PingTest()
{ {
var test = Server.Ping(); var test = Server.Ping();
Output.WriteLine("ping took {0} ms", test.TotalMilliseconds); Log("ping took {0} ms", test.TotalMilliseconds);
} }
[Fact] [Fact]
...@@ -53,7 +51,7 @@ public void SentinelGetMasterAddressByNameTest() ...@@ -53,7 +51,7 @@ public void SentinelGetMasterAddressByNameTest()
Assert.NotNull(endpoint); Assert.NotNull(endpoint);
var ipEndPoint = endpoint as IPEndPoint; var ipEndPoint = endpoint as IPEndPoint;
Assert.NotNull(ipEndPoint); Assert.NotNull(ipEndPoint);
Output.WriteLine("{0}:{1}", ipEndPoint.Address, ipEndPoint.Port); Log("{0}:{1}", ipEndPoint.Address, ipEndPoint.Port);
} }
[Fact] [Fact]
...@@ -77,7 +75,7 @@ public void SentinelMasterTest() ...@@ -77,7 +75,7 @@ public void SentinelMasterTest()
Assert.Equal(ServiceName, dict["name"]); Assert.Equal(ServiceName, dict["name"]);
foreach (var kvp in dict) foreach (var kvp in dict)
{ {
Output.WriteLine("{0}:{1}", kvp.Key, kvp.Value); Log("{0}:{1}", kvp.Key, kvp.Value);
} }
} }
...@@ -90,7 +88,7 @@ public void SentinelMastersTest() ...@@ -90,7 +88,7 @@ public void SentinelMastersTest()
{ {
foreach (var kvp in config) foreach (var kvp in config)
{ {
Output.WriteLine("{0}:{1}", kvp.Key, kvp.Value); Log("{0}:{1}", kvp.Key, kvp.Value);
} }
} }
} }
...@@ -106,7 +104,7 @@ public void SentinelSlavesTest() ...@@ -106,7 +104,7 @@ public void SentinelSlavesTest()
foreach (var config in slaveConfigs) foreach (var config in slaveConfigs)
{ {
foreach (var kvp in config) { foreach (var kvp in config) {
Output.WriteLine("{0}:{1}", kvp.Key, kvp.Value); Log("{0}:{1}", kvp.Key, kvp.Value);
} }
} }
} }
......
...@@ -15,7 +15,7 @@ namespace StackExchange.Redis.Tests ...@@ -15,7 +15,7 @@ namespace StackExchange.Redis.Tests
{ {
public abstract class TestBase : IDisposable public abstract class TestBase : IDisposable
{ {
protected ITestOutputHelper Output { get; } private ITestOutputHelper Output { get; }
protected TextWriterOutputHelper Writer { get; } protected TextWriterOutputHelper Writer { get; }
protected static bool RunningInCI { get; } = Environment.GetEnvironmentVariable("APPVEYOR") != null; protected static bool RunningInCI { get; } = Environment.GetEnvironmentVariable("APPVEYOR") != null;
protected virtual string GetConfiguration() => TestConfig.Current.MasterServerAndPort + "," + TestConfig.Current.SlaveServerAndPort; protected virtual string GetConfiguration() => TestConfig.Current.MasterServerAndPort + "," + TestConfig.Current.SlaveServerAndPort;
...@@ -24,10 +24,27 @@ protected TestBase(ITestOutputHelper output) ...@@ -24,10 +24,27 @@ protected TestBase(ITestOutputHelper output)
{ {
Output = output; Output = output;
Output.WriteFrameworkVersion(); Output.WriteFrameworkVersion();
Writer = new TextWriterOutputHelper(output); Writer = new TextWriterOutputHelper(output, TestConfig.Current.LogToConsole);
ClearAmbientFailures(); ClearAmbientFailures();
} }
protected void Log(string message)
{
Output.WriteLine(message);
if (TestConfig.Current.LogToConsole)
{
Console.WriteLine(message);
}
}
protected void Log(string message, params object[] args)
{
Output.WriteLine(message, args);
if (TestConfig.Current.LogToConsole)
{
Console.WriteLine(message, args);
}
}
protected void CollectGarbage() protected void CollectGarbage()
{ {
for (int i = 0; i < 3; i++) for (int i = 0; i < 3; i++)
...@@ -142,14 +159,14 @@ public void Teardown() ...@@ -142,14 +159,14 @@ public void Teardown()
{ {
foreach (var item in privateExceptions.Take(5)) foreach (var item in privateExceptions.Take(5))
{ {
Output.WriteLine(item); Log(item);
} }
} }
lock (backgroundExceptions) lock (backgroundExceptions)
{ {
foreach (var item in backgroundExceptions.Take(5)) foreach (var item in backgroundExceptions.Take(5))
{ {
Output.WriteLine(item); Log(item);
} }
} }
Assert.True(false, $"There were {privateFailCount} private and {sharedFailCount.Value} ambient exceptions; expected {expectedFailCount}."); Assert.True(false, $"There were {privateFailCount} private and {sharedFailCount.Value} ambient exceptions; expected {expectedFailCount}.");
...@@ -245,7 +262,7 @@ protected IServer GetAnyMaster(ConnectionMultiplexer muxer) ...@@ -245,7 +262,7 @@ protected IServer GetAnyMaster(ConnectionMultiplexer muxer)
{ {
Assert.True(false, "Failure: Be sure to call the TestBase constuctor like this: BasicOpsTests(ITestOutputHelper output) : base(output) { }"); Assert.True(false, "Failure: Be sure to call the TestBase constuctor like this: BasicOpsTests(ITestOutputHelper output) : base(output) { }");
} }
Output.WriteLine("Connect took: " + watch.ElapsedMilliseconds + "ms"); Log("Connect took: " + watch.ElapsedMilliseconds + "ms");
var muxer = task.Result; var muxer = task.Result;
if (checkConnect && (muxer == null || !muxer.IsConnected)) if (checkConnect && (muxer == null || !muxer.IsConnected))
{ {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment