Commit 5b5d43cc authored by Marc Gravell's avatar Marc Gravell

Add BookSleeve test suite; so far Strings+Issues migrated (rest commented)

parent a2add23c
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
\ No newline at end of file
//using NUnit.Framework;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//namespace Tests
//{
// [TestFixture]
// public class Batches
// {
// [Test]
// public void TestBatchNotSent()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(0, "batch");
// conn.Strings.Set(0, "batch", "batch-not-sent");
// var tasks = new List<Task>();
// using (var batch = conn.CreateBatch())
// {
// tasks.Add(batch.Keys.Remove(0, "batch"));
// tasks.Add(batch.Sets.Add(0, "batch", "a"));
// tasks.Add(batch.Sets.Add(0, "batch", "b"));
// tasks.Add(batch.Sets.Add(0, "batch", "c"));
// }
// Assert.AreEqual("batch-not-sent", conn.Wait(conn.Strings.GetString(0, "batch")));
// }
// }
// [Test]
// public void TestBatchSentTogether()
// {
// TestBatchSent(true);
// }
// [Test]
// public void TestBatchSentApart()
// {
// TestBatchSent(false);
// }
// private void TestBatchSent(bool together)
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(0, "batch");
// conn.Strings.Set(0, "batch", "batch-sent");
// var tasks = new List<Task>();
// using (var batch = conn.CreateBatch())
// {
// tasks.Add(batch.Keys.Remove(0, "batch"));
// tasks.Add(batch.Sets.Add(0, "batch", "a"));
// tasks.Add(batch.Sets.Add(0, "batch", "b"));
// tasks.Add(batch.Sets.Add(0, "batch", "c"));
// batch.Send(together);
// }
// var result = conn.Sets.GetAllString(0, "batch");
// tasks.Add(result);
// Task.WhenAll(tasks.ToArray());
// var arr = result.Result;
// Array.Sort(arr);
// Assert.AreEqual(3, arr.Length);
// Assert.AreEqual("a", arr[0]);
// Assert.AreEqual("b", arr[1]);
// Assert.AreEqual("c", arr[2]);
// }
// }
// }
//}
using System;
using System.Net.Sockets;
using NUnit.Framework;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using System.IO;
using StackExchange.Redis;
namespace Tests
{
[TestFixture(Description = "Validates that the test environment is configured and responding")]
public class Config
{
public static string CreateUniqueName()
{
return Guid.NewGuid().ToString("N");
}
internal static IServer GetServer(ConnectionMultiplexer conn)
{
return conn.GetServer(conn.GetEndPoints()[0]);
}
static readonly SocketManager socketManager = new SocketManager();
static Config()
{
TaskScheduler.UnobservedTaskException += (sender, args) =>
{
Trace.WriteLine(args.Exception, "UnobservedTaskException");
args.SetObserved();
};
}
public const string LocalHost = "127.0.0.1"; //"192.168.0.10"; //"127.0.0.1";
public const string RemoteHost = "ubuntu";
const int unsecuredPort = 6379, securedPort = 6381,
clusterPort0 = 7000, clusterPort1 = 7001, clusterPort2 = 7002;
#if CLUSTER
internal static RedisCluster GetCluster(TextWriter log = null)
{
string clusterConfiguration =
RemoteHost + ":" + clusterPort0 + "," +
RemoteHost + ":" + clusterPort1 + "," +
RemoteHost + ":" + clusterPort2;
return RedisCluster.Connect(clusterConfiguration, log);
}
#endif
//const int unsecuredPort = 6380, securedPort = 6381;
internal static ConnectionMultiplexer GetRemoteConnection(bool open = true, bool allowAdmin = false, bool waitForOpen = false, int syncTimeout = 5000, int ioTimeout = 5000)
{
return GetConnection(RemoteHost, unsecuredPort, open, allowAdmin, waitForOpen, syncTimeout, ioTimeout);
}
private static ConnectionMultiplexer GetConnection(string host, int port, bool open = true, bool allowAdmin = false, bool waitForOpen = false, int syncTimeout = 5000, int ioTimeout = 5000)
{
var options = new ConfigurationOptions
{
EndPoints = { { host, port } },
AllowAdmin = allowAdmin,
SyncTimeout = syncTimeout,
SocketManager = socketManager
};
var conn = ConnectionMultiplexer.Connect(options);
conn.InternalError += (s, args) =>
{
Trace.WriteLine(args.Exception.Message, args.Origin);
};
if (open)
{
if (waitForOpen) conn.GetDatabase().Ping();
}
return conn;
}
internal static ConnectionMultiplexer GetUnsecuredConnection(bool open = true, bool allowAdmin = false, bool waitForOpen = false, int syncTimeout = 5000, int ioTimeout = 5000)
{
return GetConnection(LocalHost, unsecuredPort, open, allowAdmin, waitForOpen, syncTimeout, ioTimeout);
}
internal static ConnectionMultiplexer GetSecuredConnection(bool open = true)
{
var options = new ConfigurationOptions
{
EndPoints = { { LocalHost, securedPort } },
Password = "changeme",
SyncTimeout = 6000,
SocketManager = socketManager
};
var conn = ConnectionMultiplexer.Connect(options);
conn.InternalError += (s, args) =>
{
Trace.WriteLine(args.Exception.Message, args.Origin);
};
return conn;
}
internal static RedisFeatures GetFeatures(ConnectionMultiplexer muxer)
{
return GetServer(muxer).Features;
}
[Test]
public void CanOpenUnsecuredConnection()
{
using (var conn = GetUnsecuredConnection(false))
{
var server = GetServer(conn);
server.Ping();
}
}
[Test]
public void CanOpenSecuredConnection()
{
using (var conn = GetSecuredConnection(false))
{
var server = GetServer(conn);
server.Ping();
}
}
[Test, ExpectedException(typeof(SocketException))]
public void CanNotOpenNonsenseConnection_IP()
{
using (var conn = ConnectionMultiplexer.Connect(Config.LocalHost + ":6500"))
{
}
}
[Test, ExpectedException(typeof(SocketException))]
public void CanNotOpenNonsenseConnection_DNS()
{
using (var conn = ConnectionMultiplexer.Connect("doesnot.exist.ds.aasd981230d.com:6500"))
{
}
}
internal static void AssertNearlyEqual(double x, double y)
{
if (Math.Abs(x - y) > 0.00001) Assert.AreEqual(x, y);
}
}
}
\ No newline at end of file
//using BookSleeve;
//using NUnit.Framework;
//using System.Linq;
//using System;
//using System.Diagnostics;
//using System.IO;
//using System.Threading;
//using System.Collections.Generic;
//using System.Threading.Tasks;
//namespace Tests
//{
// [TestFixture]
// public class Connections // http://redis.io/commands#connection
// {
// [Test]
// public void TestConnectWithDownedNodeMustBeFast_multipletimes()
// {
// for (int i = 0; i < 5; i++) TestConnectWithDownedNodeMustBeFast();
// }
// [Test]
// public void TestConnectWithDownedNodeMustBeFast()
// {
// using (var good = ConnectionUtils.Connect(Config.LocalHost + ":6379"))
// using (var bad = ConnectionUtils.Connect(Config.LocalHost + ":6666"))
// {
// Assert.IsNotNull(good, "6379 should exist for this test");
// Assert.IsNull(bad, "6666 should not exist for this test");
// }
// StringWriter log = new StringWriter();
// var watch = Stopwatch.StartNew();
// using (var selected = ConnectionUtils.Connect(Config.LocalHost +":6379," + Config.LocalHost + ":6666,name=Core(Q&A)", log))
// {}
// watch.Stop();
// Console.WriteLine(log);
// Assert.Less(1, 2, "I always get this wrong!");
// Assert.Less(watch.ElapsedMilliseconds, 1200, "I always get this wrong!");
// }
// [Test]
// public void TestConnectViaSentinel()
// {
// string[] endpoints;
// StringWriter sw = new StringWriter();
// var selected = ConnectionUtils.SelectConfiguration(Config.RemoteHost+":26379,serviceName=mymaster", out endpoints, sw);
// string log = sw.ToString();
// Console.WriteLine(log);
// Assert.IsNotNull(selected, NO_SERVER);
// Assert.AreEqual(Config.RemoteHost + ":6379", selected);
// }
// [Test]
// public void TestConnectViaSentinelInvalidServiceName()
// {
// string[] endpoints;
// StringWriter sw = new StringWriter();
// var selected = ConnectionUtils.SelectConfiguration(Config.RemoteHost + ":26379,serviceName=garbage", out endpoints, sw);
// string log = sw.ToString();
// Console.WriteLine(log);
// Assert.IsNull(selected);
// }
// const string NO_SERVER = "No server available";
// [Test]
// public void TestDirectConnect()
// {
// string[] endpoints;
// StringWriter sw = new StringWriter();
// var selected = ConnectionUtils.SelectConfiguration(Config.RemoteHost + ":6379", out endpoints, sw);
// string log = sw.ToString();
// Console.WriteLine(log);
// Assert.IsNotNull(selected, NO_SERVER);
// Assert.AreEqual(Config.RemoteHost + ":6379", selected);
// }
// [Test]
// public void TestName()
// {
// using (var conn = Config.GetUnsecuredConnection(open: false, allowAdmin: true))
// {
// string name = Config.CreateUniqueName();
// conn.Name = name;
// conn.Wait(conn.Open());
// if (!conn.Features.ClientName) Assert.Inconclusive();
// var client = conn.Wait(conn.Server.ListClients()).SingleOrDefault(c => c.Name == name);
// Assert.IsNotNull(client, "found client");
// }
// }
// [Test]
// public void CheckInProgressCountersGoToZero()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.CompletionMode = ResultCompletionMode.Concurrent;
// Task<Counters> counters = null;
// Task[] allTasks = new Task[5000];
// for (int i = 0; i < 5000; i++)
// {
// var tmp = conn.Strings.Get(5, "foo" + i);
// if (i == 2500)
// {
// counters = tmp.ContinueWith(x =>
// {
// return conn.GetCounters(false);
// },TaskContinuationOptions.ExecuteSynchronously);
// }
// allTasks[i] = tmp;
// }
// var c = conn.Wait(counters);
// Console.WriteLine("in progress during: {0}", c.AsyncCallbacksInProgress);
// Assert.AreNotEqual(0, c.AsyncCallbacksInProgress, "async during");
// conn.WaitAll(allTasks);
// PubSub.AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(0, conn.GetCounters(false).AsyncCallbacksInProgress, "async @ end");
// Assert.AreEqual(0, c.SyncCallbacksInProgress, "sync @ end");
// }
// }
// [Test]
// public void TestSubscriberName()
// {
// using (var conn = Config.GetUnsecuredConnection(open: false, allowAdmin: true))
// {
// string name = Config.CreateUniqueName();
// conn.Name = name;
// conn.Wait(conn.Open());
// if (!conn.Features.ClientName) Assert.Inconclusive();
// using (var subscriber = conn.GetOpenSubscriberChannel())
// {
// var evt = new ManualResetEvent(false);
// var tmp = subscriber.Subscribe("test-subscriber-name", delegate
// {
// evt.Set();
// });
// subscriber.Wait(tmp);
// conn.Publish("test-subscriber-name", "foo");
// Assert.IsTrue(evt.WaitOne(1000), "event was set");
// var clients = conn.Wait(conn.Server.ListClients()).Where(c => c.Name == name).ToList();
// Assert.AreEqual(2, clients.Count, "number of clients");
// }
// }
// }
// [Test]
// public void TestSubscriberNameOnRemote_WithName()
// {
// TestSubscriberNameOnRemote(true);
// }
// [Test]
// public void TestSubscriberNameOnRemote_WithoutName()
// {
// TestSubscriberNameOnRemote(false);
// }
// private void TestSubscriberNameOnRemote(bool setName)
// {
// string id = Config.CreateUniqueName();
// using (var pub = new RedisConnection(Config.RemoteHost, allowAdmin: true))
// using (var sub = new RedisSubscriberConnection(Config.RemoteHost))
// {
// List<string> errors = new List<string>();
// EventHandler<BookSleeve.ErrorEventArgs> errorHandler = (sender, args) =>
// {
// lock (errors) errors.Add(args.Exception.Message);
// };
// pub.Error += errorHandler;
// sub.Error += errorHandler;
// if (setName)
// {
// pub.Name = "pub_" + id;
// sub.Name = "sub_" + id;
// }
// int count = 0;
// var subscribe = sub.Subscribe("foo"+id, (key,payload) => Interlocked.Increment(ref count));
// Task pOpen = pub.Open(), sOpen = sub.Open();
// pub.WaitAll(pOpen, sOpen, subscribe);
// Assert.AreEqual(0, Interlocked.CompareExchange(ref count, 0, 0), "init message count");
// pub.Wait(pub.Publish("foo" + id, "hello"));
// PubSub.AllowReasonableTimeToPublishAndProcess();
// var clients = setName ? pub.Wait(pub.Server.ListClients()) : null;
// Assert.AreEqual(1, Interlocked.CompareExchange(ref count, 0, 0), "got message");
// lock (errors)
// {
// foreach (var error in errors)
// {
// Console.WriteLine(error);
// }
// Assert.AreEqual(0, errors.Count, "zero errors");
// }
// if (setName)
// {
// Assert.AreEqual(1, clients.Count(x => x.Name == pub.Name), "pub has name");
// Assert.AreEqual(1, clients.Count(x => x.Name == sub.Name), "sub has name");
// }
// }
// }
// [Test]
// public void TestForcedSubscriberName()
// {
// using (var conn = Config.GetUnsecuredConnection(allowAdmin: true, open: true, waitForOpen: true))
// using (var sub = new RedisSubscriberConnection(conn.Host, conn.Port))
// {
// var task = sub.Subscribe("foo", delegate { });
// string name = Config.CreateUniqueName();
// sub.Name = name;
// sub.SetServerVersion(new Version("2.6.9"), ServerType.Master);
// sub.Wait(sub.Open());
// sub.Wait(task);
// Assert.AreEqual(1, sub.SubscriptionCount);
// if (!conn.Features.ClientName) Assert.Inconclusive();
// var clients = conn.Wait(conn.Server.ListClients()).Where(c => c.Name == name).ToList();
// Assert.AreEqual(1, clients.Count, "number of clients");
// }
// }
// [Test]
// public void TestNameViaConnect()
// {
// string name = Config.CreateUniqueName();
// using (var conn = ConnectionUtils.Connect(Config.RemoteHost+",allowAdmin=true,name=" + name))
// {
// Assert.IsNotNull(conn, NO_SERVER, "connection");
// Assert.AreEqual(name, conn.Name, "connection name");
// if (!conn.Features.ClientName) Assert.Inconclusive();
// var client = conn.Wait(conn.Server.ListClients()).SingleOrDefault(c => c.Name == name);
// Assert.IsNotNull(client, "find client");
// }
// }
// // AUTH is already tested by secured connection
// // QUIT is implicit in dispose
// // ECHO has little utility in an application
// [Test]
// public void TestGetSetOnDifferentDbHasDifferentValues()
// {
// // note: we don't expose SELECT directly, but we can verify that we have different DBs in play:
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(1, "select", "abc");
// conn.Strings.Set(2, "select", "def");
// var x = conn.Strings.GetString(1, "select");
// var y = conn.Strings.GetString(2, "select");
// conn.WaitAll(x, y);
// Assert.AreEqual("abc", x.Result);
// Assert.AreEqual("def", y.Result);
// }
// }
// [Test, ExpectedException(typeof(ArgumentOutOfRangeException))]
// public void TestGetOnInvalidDbThrows()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.GetString(-1, "select");
// }
// }
// [Test]
// public void Ping()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// var ms = conn.Wait(conn.Server.Ping());
// Assert.GreaterOrEqual(ms, 0);
// }
// }
// [Test]
// public void CheckCounters()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen:true))
// {
// conn.Wait(conn.Strings.GetString(0, "CheckCounters"));
// var first = conn.GetCounters();
// conn.Wait(conn.Strings.GetString(0, "CheckCounters"));
// var second = conn.GetCounters();
// // +2 = ping + one select
// Assert.AreEqual(first.MessagesSent + 2, second.MessagesSent, "MessagesSent");
// Assert.AreEqual(first.MessagesReceived + 2, second.MessagesReceived, "MessagesReceived");
// Assert.AreEqual(0, second.ErrorMessages, "ErrorMessages");
// Assert.AreEqual(0, second.MessagesCancelled, "MessagesCancelled");
// Assert.AreEqual(0, second.SentQueue, "SentQueue");
// Assert.AreEqual(0, second.UnsentQueue, "UnsentQueue");
// Assert.AreEqual(0, second.QueueJumpers, "QueueJumpers");
// Assert.AreEqual(0, second.Timeouts, "Timeouts");
// Assert.IsTrue(second.Ping >= 0, "Ping");
// Assert.IsTrue(second.ToString().Length > 0, "ToString");
// }
// }
// }
//}
//using BookSleeve;
//using NUnit.Framework;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//namespace Tests
//{
// [TestFixture]
// public class Constraints
// {
// [Test]
// public void TestManualIncr()
// {
// using (var conn = Config.GetUnsecuredConnection(syncTimeout: 120000)) // big timeout while debugging
// {
// for (int i = 0; i < 200; i++)
// {
// conn.Keys.Remove(0, "foo");
// Assert.AreEqual(1, conn.Wait(ManualIncr(conn, 0, "foo")));
// Assert.AreEqual(2, conn.Wait(ManualIncr(conn, 0, "foo")));
// Assert.AreEqual(2, conn.Wait(conn.Strings.GetInt64(0, "foo")));
// }
// }
// }
// public async Task<long?> ManualIncr(RedisConnection connection, int db, string key)
// {
// var oldVal = await connection.Strings.GetInt64(db, key).SafeAwaitable();
// var newVal = (oldVal ?? 0) + 1;
// using (var tran = connection.CreateTransaction())
// { // check hasn't changed
//#pragma warning disable 4014
// tran.AddCondition(Condition.KeyEquals(db, key, oldVal));
// tran.Strings.Set(db, key, newVal);
//#pragma warning restore 4014
// if (!await tran.Execute().SafeAwaitable()) return null; // aborted
// return newVal;
// }
// }
// }
//}
//using System;
//using System.Collections.Generic;
//using System.Text;
//using System.Linq;
//using NUnit.Framework;
//namespace Tests
//{
// [TestFixture]
// public class Hashes // http://redis.io/commands#hash
// {
// [Test]
// public void TestIncrBy()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(5, "hash-test");
// for (int i = 1; i < 1000; i++)
// {
// Assert.AreEqual(i, conn.Hashes.Increment(5, "hash-test", "a", 1).Result);
// Assert.AreEqual(-i, conn.Hashes.Increment(5, "hash-test", "b", -1).Result);
// //Assert.AreEqual(i, conn.Wait(conn.Hashes.Increment(5, "hash-test", "a", 1)));
// //Assert.AreEqual(-i, conn.Wait(conn.Hashes.Increment(5, "hash-test", "b", -1)));
// }
// }
// }
// [Test]
// public void Scan()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// if (!conn.Features.Scan) Assert.Inconclusive();
// const int db = 3;
// const string key = "hash-scan";
// conn.Keys.Remove(db, key);
// conn.Hashes.Set(db, key, "abc", "def");
// conn.Hashes.Set(db, key, "ghi", "jkl");
// conn.Hashes.Set(db, key, "mno", "pqr");
// var t1 = conn.Hashes.Scan(db, key);
// var t2 = conn.Hashes.Scan(db, key, "*h*");
// var t3 = conn.Hashes.ScanString(db, key);
// var t4 = conn.Hashes.ScanString(db, key, "*h*");
// var v1 = t1.ToArray();
// var v2 = t2.ToArray();
// var v3 = t3.ToArray();
// var v4 = t4.ToArray();
// Assert.AreEqual(3, v1.Length);
// Assert.AreEqual(1, v2.Length);
// Assert.AreEqual(3, v3.Length);
// Assert.AreEqual(1, v4.Length);
// Array.Sort(v1, (x, y) => string.Compare(x.Key, y.Key));
// Array.Sort(v2, (x, y) => string.Compare(x.Key, y.Key));
// Array.Sort(v3, (x, y) => string.Compare(x.Key, y.Key));
// Array.Sort(v4, (x, y) => string.Compare(x.Key, y.Key));
// Assert.AreEqual("abc=def,ghi=jkl,mno=pqr", string.Join(",", v1.Select(pair => pair.Key + "=" + Encoding.UTF8.GetString(pair.Value))));
// Assert.AreEqual("ghi=jkl", string.Join(",", v2.Select(pair => pair.Key + "=" + Encoding.UTF8.GetString(pair.Value))));
// Assert.AreEqual("abc=def,ghi=jkl,mno=pqr", string.Join(",", v3.Select(pair => pair.Key + "=" + pair.Value)));
// Assert.AreEqual("ghi=jkl", string.Join(",", v4.Select(pair => pair.Key + "=" + pair.Value)));
// }
// }
// [Test]
// public void TestIncrementOnHashThatDoesntExist()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(0, "keynotexist");
// var result1 = conn.Wait(conn.Hashes.Increment(0, "keynotexist", "fieldnotexist", 1));
// var result2 = conn.Wait(conn.Hashes.Increment(0, "keynotexist", "anotherfieldnotexist", 1));
// Assert.AreEqual(1, result1);
// Assert.AreEqual(1, result2);
// }
// }
// [Test]
// public void TestIncrByFloat()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen:true))
// {
// if (conn.Features.IncrementFloat)
// {
// conn.Keys.Remove(5, "hash-test");
// for (int i = 1; i < 1000; i++)
// {
// Assert.AreEqual((double)i, conn.Hashes.Increment(5, "hash-test", "a", 1.0).Result);
// Assert.AreEqual((double)(-i), conn.Hashes.Increment(5, "hash-test", "b", -1.0).Result);
// }
// }
// }
// }
// [Test]
// public void TestGetAll()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// const string key = "hash test";
// conn.Keys.Remove(6, key);
// var shouldMatch = new Dictionary<Guid, int>();
// var random = new Random();
// for (int i = 1; i < 1000; i++)
// {
// var guid = Guid.NewGuid();
// var value = random.Next(Int32.MaxValue);
// shouldMatch[guid] = value;
// var x = conn.Hashes.Increment(6, key, guid.ToString(), value).Result; // Kill Async
// }
//#pragma warning disable 618
// var inRedisRaw = conn.GetHash(6, key).Result;
//#pragma warning restore 618
// var inRedis = new Dictionary<Guid, int>();
// for (var i = 0; i < inRedisRaw.Length; i += 2)
// {
// var guid = inRedisRaw[i];
// var num = inRedisRaw[i + 1];
// inRedis[Guid.Parse(Encoding.ASCII.GetString(guid))] = int.Parse(Encoding.ASCII.GetString(num));
// }
// Assert.AreEqual(shouldMatch.Count, inRedis.Count);
// foreach (var k in shouldMatch.Keys)
// {
// Assert.AreEqual(shouldMatch[k], inRedis[k]);
// }
// }
// }
// [Test]
// public void TestGet()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// var key = "hash test";
// var shouldMatch = new Dictionary<Guid, int>();
// var random = new Random();
// for (int i = 1; i < 1000; i++)
// {
// var guid = Guid.NewGuid();
// var value = random.Next(Int32.MaxValue);
// shouldMatch[guid] = value;
// var x = conn.Hashes.Increment(6, key, guid.ToString(), value).Result; // Kill Async
// }
// foreach (var k in shouldMatch.Keys)
// {
// var inRedis = conn.Hashes.Get(6, key, k.ToString()).Result;
// var num = int.Parse(Encoding.ASCII.GetString(inRedis));
// Assert.AreEqual(shouldMatch[k], num);
// }
// }
// }
// [Test]
// public void TestSet() // http://redis.io/commands/hset
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var val0 = conn.Hashes.GetString(9, "hashkey", "field");
// var set0 = conn.Hashes.Set(9, "hashkey", "field", "value1");
// var val1 = conn.Hashes.GetString(9, "hashkey", "field");
// var set1 = conn.Hashes.Set(9, "hashkey", "field", "value2");
// var val2 = conn.Hashes.GetString(9, "hashkey", "field");
// var set2 = conn.Hashes.Set(9, "hashkey", "field-blob", Encoding.UTF8.GetBytes("value3"));
// var val3 = conn.Hashes.Get(9, "hashkey", "field-blob");
// Assert.AreEqual(null, val0.Result);
// Assert.AreEqual(true, set0.Result);
// Assert.AreEqual("value1", val1.Result);
// Assert.AreEqual(false, set1.Result);
// Assert.AreEqual("value2", val2.Result);
// Assert.AreEqual(true, set2.Result);
// Assert.AreEqual("value3", Encoding.UTF8.GetString(val3.Result));
// }
// }
// [Test]
// public void TestSetNotExists() // http://redis.io/commands/hsetnx
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var val0 = conn.Hashes.GetString(9, "hashkey", "field");
// var set0 = conn.Hashes.SetIfNotExists(9, "hashkey", "field", "value1");
// var val1 = conn.Hashes.GetString(9, "hashkey", "field");
// var set1 = conn.Hashes.SetIfNotExists(9, "hashkey", "field", "value2");
// var val2 = conn.Hashes.GetString(9, "hashkey", "field");
// var set2 = conn.Hashes.SetIfNotExists(9, "hashkey", "field-blob", Encoding.UTF8.GetBytes("value3"));
// var val3 = conn.Hashes.Get(9, "hashkey", "field-blob");
// var set3 = conn.Hashes.SetIfNotExists(9, "hashkey", "field-blob", Encoding.UTF8.GetBytes("value3"));
// Assert.AreEqual(null, val0.Result);
// Assert.AreEqual(true, set0.Result);
// Assert.AreEqual("value1", val1.Result);
// Assert.AreEqual(false, set1.Result);
// Assert.AreEqual("value1", val2.Result);
// Assert.AreEqual(true, set2.Result);
// Assert.AreEqual("value3", Encoding.UTF8.GetString(val3.Result));
// Assert.AreEqual(false, set3.Result);
// }
// }
// [Test]
// public void TestDelSingle() // http://redis.io/commands/hdel
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var del0 = conn.Hashes.Remove(9, "hashkey", "field");
// conn.Hashes.Set(9, "hashkey", "field", "value");
// var del1 = conn.Hashes.Remove(9, "hashkey", "field");
// var del2 = conn.Hashes.Remove(9, "hashkey", "field");
// Assert.AreEqual(false, del0.Result);
// Assert.AreEqual(true, del1.Result);
// Assert.AreEqual(false, del2.Result);
// }
// }
// [Test]
// public void TestDelMulti() // http://redis.io/commands/hdel
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Hashes.Set(3, "TestDelMulti", "key1", "val1");
// conn.Hashes.Set(3, "TestDelMulti", "key2", "val2");
// conn.Hashes.Set(3, "TestDelMulti", "key3", "val3");
// var s1 = conn.Hashes.Exists(3, "TestDelMulti", "key1");
// var s2 = conn.Hashes.Exists(3, "TestDelMulti", "key2");
// var s3 = conn.Hashes.Exists(3, "TestDelMulti", "key3");
// var removed = conn.Hashes.Remove(3, "TestDelMulti", new[] { "key1", "key3" });
// var d1 = conn.Hashes.Exists(3, "TestDelMulti", "key1");
// var d2 = conn.Hashes.Exists(3, "TestDelMulti", "key2");
// var d3 = conn.Hashes.Exists(3, "TestDelMulti", "key3");
// Assert.IsTrue(conn.Wait(s1));
// Assert.IsTrue(conn.Wait(s2));
// Assert.IsTrue(conn.Wait(s3));
// Assert.AreEqual(2, conn.Wait(removed));
// Assert.IsFalse(conn.Wait(d1));
// Assert.IsTrue(conn.Wait(d2));
// Assert.IsFalse(conn.Wait(d3));
// var removeFinal = conn.Hashes.Remove(3, "TestDelMulti", new[] {"key2"});
// Assert.AreEqual(0, conn.Wait(conn.Hashes.GetLength(3, "TestDelMulti")));
// Assert.AreEqual(1, conn.Wait(removeFinal));
// }
// }
// [Test]
// public void TestDelMultiInsideTransaction() // http://redis.io/commands/hdel
// {
// using (var outer = Config.GetUnsecuredConnection())
// {
// using (var conn = outer.CreateTransaction())
// {
// conn.Hashes.Set(3, "TestDelMulti", "key1", "val1");
// conn.Hashes.Set(3, "TestDelMulti", "key2", "val2");
// conn.Hashes.Set(3, "TestDelMulti", "key3", "val3");
// var s1 = conn.Hashes.Exists(3, "TestDelMulti", "key1");
// var s2 = conn.Hashes.Exists(3, "TestDelMulti", "key2");
// var s3 = conn.Hashes.Exists(3, "TestDelMulti", "key3");
// var removed = conn.Hashes.Remove(3, "TestDelMulti", new[] { "key1", "key3" });
// var d1 = conn.Hashes.Exists(3, "TestDelMulti", "key1");
// var d2 = conn.Hashes.Exists(3, "TestDelMulti", "key2");
// var d3 = conn.Hashes.Exists(3, "TestDelMulti", "key3");
// conn.Execute();
// Assert.IsTrue(conn.Wait(s1));
// Assert.IsTrue(conn.Wait(s2));
// Assert.IsTrue(conn.Wait(s3));
// Assert.AreEqual(2, conn.Wait(removed));
// Assert.IsFalse(conn.Wait(d1));
// Assert.IsTrue(conn.Wait(d2));
// Assert.IsFalse(conn.Wait(d3));
// }
// }
// }
// [Test]
// public void TestExists() // http://redis.io/commands/hexists
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var ex0 = conn.Hashes.Exists(9, "hashkey", "field");
// conn.Hashes.Set(9, "hashkey", "field", "value");
// var ex1 = conn.Hashes.Exists(9, "hashkey", "field");
// conn.Hashes.Remove(9, "hashkey", "field");
// var ex2 = conn.Hashes.Exists(9, "hashkey", "field");
// Assert.AreEqual(false, ex0.Result);
// Assert.AreEqual(true, ex1.Result);
// Assert.AreEqual(false, ex0.Result);
// }
// }
// [Test]
// public void TestHashKeys() // http://redis.io/commands/hkeys
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var keys0 = conn.Hashes.GetKeys(9, "hashkey");
// conn.Hashes.Set(9, "hashkey", "foo", "abc");
// conn.Hashes.Set(9, "hashkey", "bar", "def");
// var keys1 = conn.Hashes.GetKeys(9, "hashkey");
// Assert.AreEqual(0, keys0.Result.Length);
// var arr = keys1.Result;
// Assert.AreEqual(2, arr.Length);
// Assert.AreEqual("foo", arr[0]);
// Assert.AreEqual("bar", arr[1]);
// }
// }
// [Test]
// public void TestHashValues() // http://redis.io/commands/hvals
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var keys0 = conn.Hashes.GetValues(9, "hashkey");
// conn.Hashes.Set(9, "hashkey", "foo", "abc");
// conn.Hashes.Set(9, "hashkey", "bar", "def");
// var keys1 = conn.Hashes.GetValues(9, "hashkey");
// Assert.AreEqual(0, keys0.Result.Length);
// var arr = keys1.Result;
// Assert.AreEqual(2, arr.Length);
// Assert.AreEqual("abc", Encoding.UTF8.GetString(arr[0]));
// Assert.AreEqual("def", Encoding.UTF8.GetString(arr[1]));
// }
// }
// [Test]
// public void TestHashLength() // http://redis.io/commands/hlen
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var len0 = conn.Hashes.GetLength(9, "hashkey");
// conn.Hashes.Set(9, "hashkey", "foo", "abc");
// conn.Hashes.Set(9, "hashkey", "bar", "def");
// var len1 = conn.Hashes.GetLength(9, "hashkey");
// Assert.AreEqual(0, len0.Result);
// Assert.AreEqual(2, len1.Result);
// }
// }
// [Test]
// public void TestGetMulti() // http://redis.io/commands/hmget
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// string[] fields = { "foo", "bar", "blop" };
// var result0 = conn.Hashes.GetString(9, "hashkey", fields);
// conn.Hashes.Set(9, "hashkey", "foo", "abc");
// conn.Hashes.Set(9, "hashkey", "bar", "def");
// var result1 = conn.Hashes.GetString(9, "hashkey", fields);
// var result2 = conn.Hashes.Get(9, "hashkey", fields);
// var arr0 = result0.Result;
// var arr1 = result1.Result;
// var arr2 = result2.Result;
// Assert.AreEqual(3, arr0.Length);
// Assert.IsNull(arr0[0]);
// Assert.IsNull(arr0[1]);
// Assert.IsNull(arr0[2]);
// Assert.AreEqual(3, arr1.Length);
// Assert.AreEqual("abc", arr1[0]);
// Assert.AreEqual("def", arr1[1]);
// Assert.IsNull(arr1[2]);
// Assert.AreEqual(3, arr2.Length);
// Assert.AreEqual("abc", Encoding.UTF8.GetString(arr2[0]));
// Assert.AreEqual("def", Encoding.UTF8.GetString(arr2[1]));
// Assert.IsNull(arr2[2]);
// }
// }
// [Test]
// public void TestGetPairs() // http://redis.io/commands/hgetall
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var result0 = conn.Hashes.GetAll(9, "hashkey");
// conn.Hashes.Set(9, "hashkey", "foo", "abc");
// conn.Hashes.Set(9, "hashkey", "bar", "def");
// var result1 = conn.Hashes.GetAll(9, "hashkey");
// Assert.AreEqual(0, result0.Result.Count);
// var result = result1.Result;
// Assert.AreEqual(2, result.Count);
// Assert.AreEqual("abc", Encoding.UTF8.GetString(result["foo"]));
// Assert.AreEqual("def", Encoding.UTF8.GetString(result["bar"]));
// }
// }
// [Test]
// public void TestSetPairs() // http://redis.io/commands/hmset
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(9, "hashkey");
// var result0 = conn.Hashes.GetAll(9, "hashkey");
// var data = new Dictionary<string, byte[]> {
// {"foo", Encoding.UTF8.GetBytes("abc")},
// {"bar", Encoding.UTF8.GetBytes("def")}
// };
// conn.Hashes.Set(9, "hashkey", data);
// var result1 = conn.Hashes.GetAll(9, "hashkey");
// Assert.AreEqual(0, result0.Result.Count);
// var result = result1.Result;
// Assert.AreEqual(2, result.Count);
// Assert.AreEqual("abc", Encoding.UTF8.GetString(result["foo"]));
// Assert.AreEqual("def", Encoding.UTF8.GetString(result["bar"]));
// }
// }
// }
//}
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tests.Issues
{
[TestFixture]
public class Issue10
{
[Test]
public void Execute()
{
using (var muxer = Config.GetUnsecuredConnection())
{
const int DB = 5;
const string Key = "issue-10-list";
var conn = muxer.GetDatabase(DB);
conn.KeyDeleteAsync(Key); // contents: nil
conn.ListLeftPushAsync(Key, "abc"); // "abc"
conn.ListLeftPushAsync(Key, "def"); // "def", "abc"
conn.ListLeftPushAsync(Key, "ghi"); // "ghi", "def", "abc",
conn.ListSetByIndexAsync(Key, 1, "jkl"); // "ghi", "jkl", "abc"
var contents = conn.Wait(conn.ListRangeAsync(Key, 0, -1));
Assert.AreEqual(3, contents.Length);
Assert.AreEqual("ghi", (string)contents[0]);
Assert.AreEqual("jkl", (string)contents[1]);
Assert.AreEqual("abc", (string)contents[2]);
}
}
}
}
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Tests.Issues
{
[TestFixture]
public class Massive_Delete
{
[TestFixtureSetUp]
public void Init()
{
using (var muxer = Config.GetUnsecuredConnection(allowAdmin: true))
{
Config.GetServer(muxer).FlushDatabase(db);
Task last = null;
var conn = muxer.GetDatabase(db);
for (int i = 0; i < 100000; i++)
{
string key = "key" + i;
conn.StringSetAsync(key, key);
last = conn.SetAddAsync(todoKey, key);
}
conn.Wait(last);
}
}
const int db = 4;
const string todoKey = "todo";
[Test]
public void ExecuteMassiveDelete()
{
var watch = Stopwatch.StartNew();
using (var muxer = Config.GetUnsecuredConnection())
using (var throttle = new SemaphoreSlim(1))
{
var conn = muxer.GetDatabase(db);
var originallyTask = conn.SetLengthAsync(todoKey);
int keepChecking = 1;
Task last = null;
while (Thread.VolatileRead(ref keepChecking) == 1)
{
throttle.Wait(); // acquire
conn.SetPopAsync(todoKey).ContinueWith(task =>
{
throttle.Release();
if (task.IsCompleted)
{
if ((string)task.Result == null)
{
Thread.VolatileWrite(ref keepChecking, 0);
}
else
{
last = conn.KeyDeleteAsync((string)task.Result);
}
}
});
}
if (last != null)
{
conn.Wait(last);
}
watch.Stop();
long originally = conn.Wait(originallyTask),
remaining = conn.SetLength(todoKey);
Console.WriteLine("From {0} to {1}; {2}ms", originally, remaining,
watch.ElapsedMilliseconds);
var counters = Config.GetServer(muxer).GetCounters();
Console.WriteLine("Completions: {0} sync, {1} async", counters.Interactive.CompletedSynchronously, counters.Interactive.CompletedAsynchronously);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Diagnostics;
using StackExchange.Redis;
namespace Tests.Issues
{
[TestFixture]
public class SO10504853
{
[Test]
public void LoopLotsOfTrivialStuff()
{
Trace.WriteLine("### init");
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(0);
conn.KeyDelete("lots-trivial");
}
const int COUNT = 2;
for (int i = 0; i < COUNT; i++)
{
Trace.WriteLine("### incr:" + i);
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(0);
Assert.AreEqual(i + 1, conn.StringIncrement("lots-trivial"));
}
}
Trace.WriteLine("### close");
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(0);
Assert.AreEqual(COUNT, (long)conn.StringGet("lots-trivial"));
}
}
[Test]
public void ExecuteWithEmptyStartingPoint()
{
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(0);
var task = new { priority = 3 };
conn.KeyDeleteAsync("item:1");
conn.HashSetAsync("item:1", "something else", "abc");
conn.HashSetAsync("item:1", "priority", task.priority.ToString());
var taskResult = conn.HashGetAsync("item:1", "priority");
conn.Wait(taskResult);
var priority = Int32.Parse(taskResult.Result);
Assert.AreEqual(3, priority);
}
}
[Test, ExpectedException(typeof(RedisServerException), ExpectedMessage = "WRONGTYPE Operation against a key holding the wrong kind of value")]
public void ExecuteWithNonHashStartingPoint()
{
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(0);
var task = new { priority = 3 };
conn.KeyDeleteAsync("item:1");
conn.StringSetAsync("item:1", "not a hash");
conn.HashSetAsync("item:1", "priority", task.priority.ToString());
var taskResult = conn.HashGetAsync("item:1", "priority");
try
{
conn.Wait(taskResult);
Assert.Fail();
} catch(AggregateException ex)
{
throw ex.InnerExceptions[0];
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using StackExchange.Redis;
namespace Tests.Issues
{
[TestFixture]
public class SO10825542
{
[Test]
public void Execute()
{
using (var muxer = Config.GetUnsecuredConnection())
{
var key = "somekey1";
var con = muxer.GetDatabase(1);
// set the field value and expiration
con.HashSetAsync(key, "field1", Encoding.UTF8.GetBytes("hello world"));
con.KeyExpireAsync(key, TimeSpan.FromSeconds(7200));
con.HashSetAsync(key, "field2", "fooobar");
var task = con.HashGetAllAsync(key);
con.Wait(task);
Assert.AreEqual(2, task.Result.Length);
var dict = task.Result.ToStringDictionary();
Assert.AreEqual("hello world", dict["field1"]);
Assert.AreEqual("fooobar", dict["field2"]);
}
}
}
}
using System;
using NUnit.Framework;
namespace Tests.Issues
{
[TestFixture]
public class SO11766033
{
[Test]
public void TestNullString()
{
const int db = 3;
using (var muxer = Config.GetUnsecuredConnection(true))
{
var redis = muxer.GetDatabase(db);
string expectedTestValue = null;
var uid = Config.CreateUniqueName();
redis.StringSetAsync(uid, "abc");
redis.StringSetAsync(uid, expectedTestValue);
string testValue = redis.StringGet(uid);
Assert.IsNull(testValue);
}
}
[Test]
public void TestEmptyString()
{
const int db = 3;
using (var muxer = Config.GetUnsecuredConnection(true))
{
var redis = muxer.GetDatabase(db);
string expectedTestValue = "";
var uid = Config.CreateUniqueName();
redis.StringSetAsync(uid, expectedTestValue);
string testValue = redis.StringGet(uid);
Assert.AreEqual(expectedTestValue, testValue);
}
}
}
}
//using System.Threading;
//using BookSleeve;
//using NUnit.Framework;
//using System.Text.RegularExpressions;
//using System.Linq;
//using System;
//namespace Tests
//{
// [TestFixture]
// public class Keys // http://redis.io/commands#generic
// {
// // note we don't expose EXPIREAT as it raises all sorts of problems with
// // time synchronisation, UTC vs local, DST, etc; easier for the caller
// // to use EXPIRE
// [Test]
// public void TestDeleteValidKey()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(0, "del", "abcdef");
// var x = conn.Strings.GetString(0, "del");
// var del = conn.Keys.Remove(0, "del");
// var y = conn.Strings.GetString(0, "del");
// conn.WaitAll(x, del, y);
// Assert.AreEqual("abcdef", x.Result);
// Assert.IsTrue(del.Result);
// Assert.AreEqual(null, y.Result);
// }
// }
// [Test]
// public void TestLargeIntegers()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// const long expected = 20L * int.MaxValue;
// conn.Strings.Set(0, "large-int", expected);
// var result = conn.Strings.GetInt64(0, "large-int");
// Assert.AreEqual(expected, conn.Wait(result));
// }
// }
// [Test]
// public void TestDeleteInvalidKey()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(0, "exists", "abcdef");
// var x = conn.Keys.Remove(0, "exists");
// var y = conn.Keys.Remove(0, "exists");
// conn.WaitAll(x, y);
// Assert.IsTrue(x.Result);
// Assert.IsFalse(y.Result);
// }
// }
// [Test]
// public void TestDeleteMultiple()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(0, "del", "abcdef");
// var x = conn.Keys.Remove(0, "del");
// var y = conn.Keys.Remove(0, "del");
// conn.WaitAll(x, y);
// Assert.IsTrue(x.Result);
// Assert.IsFalse(y.Result);
// }
// }
// [Test]
// public void Scan()
// {
// using (var conn = Config.GetUnsecuredConnection(allowAdmin: true, waitForOpen: true))
// {
// if (!conn.Features.Scan) Assert.Inconclusive();
// const int DB = 3;
// conn.Wait(conn.Server.FlushDb(DB));
// conn.Strings.Set(DB, "foo", "foo");
// conn.Strings.Set(DB, "bar", "bar");
// conn.Strings.Set(DB, "blap", "blap");
// var keys = conn.Keys.Scan(DB).ToArray();
// Array.Sort(keys);
// Assert.AreEqual(3, keys.Length);
// Assert.AreEqual("bar", keys[0]);
// Assert.AreEqual("blap", keys[1]);
// Assert.AreEqual("foo", keys[2]);
// keys = conn.Keys.Scan(DB, "b*").ToArray();
// Array.Sort(keys);
// Assert.AreEqual(2, keys.Length);
// Assert.AreEqual("bar", keys[0]);
// Assert.AreEqual("blap", keys[1]);
// }
// }
// [Test]
// public void TestExpireAgainstInvalidKey()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(0, "delA", "abcdef");
// conn.Keys.Remove(0, "delB");
// conn.Strings.Set(0, "delC", "abcdef");
// var del = conn.Keys.Remove(0, new[] {"delA", "delB", "delC"});
// Assert.AreEqual(2, conn.Wait(del));
// }
// }
// [Test]
// public void TestExists()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(0, "exists", "abcdef");
// var x = conn.Keys.Exists(0, "exists");
// conn.Keys.Remove(0, "exists");
// var y = conn.Keys.Exists(0, "exists");
// conn.WaitAll(x, y);
// Assert.IsTrue(x.Result);
// Assert.IsFalse (y.Result);
// }
// }
// [Test]
// public void TestExpireAgainstValidKey()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(0, "expire", "abcdef");
// var x = conn.Keys.TimeToLive(0, "expire");
// var exp1 = conn.Keys.Expire(0, "expire", 100);
// var y = conn.Keys.TimeToLive(0, "expire");
// var exp2 = conn.Keys.Expire(0, "expire", 150);
// var z = conn.Keys.TimeToLive(0, "expire");
// conn.WaitAll(x, exp1, y, exp2, z);
// Assert.AreEqual(-1, x.Result);
// Assert.IsTrue(exp1.Result);
// Assert.GreaterOrEqual(y.Result, 90);
// Assert.LessOrEqual(y.Result, 100);
// if (conn.Features.ExpireOverwrite)
// {
// Assert.IsTrue(exp2.Result);
// Assert.GreaterOrEqual(z.Result, 140);
// Assert.LessOrEqual(z.Result, 150);
// }
// else
// {
// Assert.IsFalse(exp2.Result);
// Assert.GreaterOrEqual(z.Result, 90);
// Assert.LessOrEqual(z.Result, 100);
// }
// }
// }
// [Test]
// public void TestSuccessfulMove()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(1, "move", "move-value");
// conn.Keys.Remove(2, "move");
// var succ = conn.Keys.Move(1, "move", 2);
// var in1 = conn.Strings.GetString(1, "move");
// var in2 = conn.Strings.GetString(2, "move");
// Assert.IsTrue(conn.Wait(succ));
// Assert.IsNull(conn.Wait(in1));
// Assert.AreEqual("move-value", conn.Wait(in2));
// }
// }
// [Test]
// public void TestFailedMoveWhenNotExistsInSource()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "move");
// conn.Strings.Set(2, "move", "move-value");
// var succ = conn.Keys.Move(1, "move", 2);
// var in1 = conn.Strings.GetString(1, "move");
// var in2 = conn.Strings.GetString(2, "move");
// Assert.IsFalse(conn.Wait(succ));
// Assert.IsNull(conn.Wait(in1));
// Assert.AreEqual("move-value", conn.Wait(in2));
// }
// }
// [Test]
// public void TestFailedMoveWhenNotExistsInTarget()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Strings.Set(1, "move", "move-valueA");
// conn.Strings.Set(2, "move", "move-valueB");
// var succ = conn.Keys.Move(1, "move", 2);
// var in1 = conn.Strings.GetString(1, "move");
// var in2 = conn.Strings.GetString(2, "move");
// Assert.IsFalse(conn.Wait(succ));
// Assert.AreEqual("move-valueA", conn.Wait(in1));
// Assert.AreEqual("move-valueB", conn.Wait(in2));
// }
// }
// [Test]
// public void RemoveExpiry()
// {
// int errors = 0, expectedErrors;
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.Error += delegate
// {
// Interlocked.Increment(ref errors);
// };
// conn.Keys.Remove(1, "persist");
// conn.Strings.Set(1, "persist", "persist");
// var persist1 = conn.Keys.Persist(1, "persist");
// conn.Keys.Expire(1, "persist", 100);
// var before = conn.Keys.TimeToLive(1, "persist");
// var persist2 = conn.Keys.Persist(1, "persist");
// var after = conn.Keys.TimeToLive(1, "persist");
// Assert.GreaterOrEqual(conn.Wait(before), 90);
// if (conn.Features.Persist)
// {
// Assert.IsFalse(conn.Wait(persist1));
// Assert.IsTrue(conn.Wait(persist2));
// Assert.AreEqual(-1, conn.Wait(after));
// expectedErrors = 0;
// }
// else
// {
// try{
// conn.Wait(persist1);
// Assert.Fail();
// }
// catch (RedisException){}
// try
// {
// conn.Wait(persist2);
// Assert.Fail();
// }
// catch (RedisException) { }
// Assert.GreaterOrEqual(conn.Wait(after), 90);
// expectedErrors = 2;
// }
// }
// Assert.AreEqual(expectedErrors, Interlocked.CompareExchange(ref errors,0,0));
// }
// [Test]
// public void RandomKeys()
// {
// using (var conn = Config.GetUnsecuredConnection(allowAdmin: true, waitForOpen: true))
// {
// conn.Server.FlushDb(6);
// var key1 = conn.Keys.Random(6);
// conn.Strings.Set(6, "random1", "random1");
// var key2 = conn.Keys.Random(6);
// for (int i = 2; i < 100; i++)
// {
// string key = "random" + i;
// conn.Strings.Set(6, key, key);
// }
// var key3 = conn.Keys.Random(6);
// Assert.IsNull(conn.Wait(key1));
// Assert.AreEqual("random1", conn.Wait(key2));
// string s = conn.Wait(key3);
// Assert.IsTrue(s.StartsWith("random"));
// s = s.Substring(6);
// int result = int.Parse(s);
// Assert.GreaterOrEqual(result, 1);
// Assert.Less(result, 100);
// }
// }
// [Test]
// public void Sort()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "sort");
// conn.Lists.AddLast(1, "sort", "10");
// conn.Lists.AddLast(1, "sort", "3");
// conn.Lists.AddLast(1, "sort", "1.1");
// conn.Lists.AddLast(1, "sort", "2");
// var a = conn.Keys.SortString(1, "sort");
// var b = conn.Keys.SortString(1, "sort", ascending: false, offset: 1, count: 2);
// var c = conn.Keys.SortString(1, "sort", alpha: true);
// var d = conn.Keys.SortAndStore(1, "sort-store", "sort");
// var e = conn.Lists.RangeString(1, "sort-store", 0, -1);
// var f = conn.Lists.RangeString(1, "sort", 0, -1);
// Assert.AreEqual("1.1;2;3;10",string.Join(";", conn.Wait(a)));
// Assert.AreEqual("3;2",string.Join(";", conn.Wait(b)));
// Assert.AreEqual("10;1.1;2;3", string.Join(";", conn.Wait(c)));
// Assert.AreEqual(4, conn.Wait(d));
// Assert.AreEqual("1.1;2;3;10", string.Join(";", conn.Wait(e)));
// Assert.AreEqual("10;3;1.1;2", string.Join(";", conn.Wait(f)));
// }
// }
// [Test]
// public void ItemType()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(4, new[]{"type-none", "type-list", "type-string",
// "type-set", "type-zset", "type-hash"});
// conn.Strings.Set(4, "type-string", "blah");
// conn.Lists.AddLast(4, "type-list", "blah");
// conn.Sets.Add(4, "type-set", "blah");
// conn.SortedSets.Add(4, "type-zset", "blah", 123);
// conn.Hashes.Set(4, "type-hash", "foo", "blah");
// var x0 = conn.Keys.Type(4, "type-none");
// var x1 = conn.Keys.Type(4, "type-list");
// var x2 = conn.Keys.Type(4, "type-string");
// var x3 = conn.Keys.Type(4, "type-set");
// var x4 = conn.Keys.Type(4, "type-zset");
// var x5 = conn.Keys.Type(4, "type-hash");
// Assert.AreEqual(RedisConnection.ItemTypes.None, conn.Wait(x0));
// Assert.AreEqual(RedisConnection.ItemTypes.List, conn.Wait(x1));
// Assert.AreEqual(RedisConnection.ItemTypes.String, conn.Wait(x2));
// Assert.AreEqual(RedisConnection.ItemTypes.Set, conn.Wait(x3));
// Assert.AreEqual(RedisConnection.ItemTypes.SortedSet, conn.Wait(x4));
// Assert.AreEqual(RedisConnection.ItemTypes.Hash, conn.Wait(x5));
// }
// }
// [Test]
// public void RenameKeyWithOverwrite()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "foo");
// conn.Keys.Remove(1, "bar");
// var check1 = conn.Keys.Rename(1, "foo", "bar"); // neither
// var after1_foo = conn.Strings.GetString(1, "foo");
// var after1_bar = conn.Strings.GetString(1, "bar");
// conn.Strings.Set(1, "foo", "foo-value");
// var check2 = conn.Keys.Rename(1, "foo", "bar"); // source only
// var after2_foo = conn.Strings.GetString(1, "foo");
// var after2_bar = conn.Strings.GetString(1, "bar");
// var check3 = conn.Keys.Rename(1, "foo", "bar"); // dest only
// var after3_foo = conn.Strings.GetString(1, "foo");
// var after3_bar = conn.Strings.GetString(1, "bar");
// conn.Strings.Set(1, "foo", "new-value");
// var check4 = conn.Keys.Rename(1, "foo", "bar"); // both
// var after4_foo = conn.Strings.GetString(1, "foo");
// var after4_bar = conn.Strings.GetString(1, "bar");
// try
// {
// conn.Wait(check1);
// Assert.Fail();
// }
// catch (RedisException) { }
// Assert.IsNull(conn.Wait(after1_foo));
// Assert.IsNull(conn.Wait(after1_bar));
// conn.Wait(check2);
// Assert.IsNull(conn.Wait(after2_foo));
// Assert.AreEqual("foo-value", conn.Wait(after2_bar));
// try
// {
// conn.Wait(check3);
// Assert.Fail();
// }
// catch (RedisException) { }
// Assert.IsNull(conn.Wait(after3_foo));
// Assert.AreEqual("foo-value", conn.Wait(after3_bar));
// conn.Wait(check4);
// Assert.IsNull(conn.Wait(after4_foo));
// Assert.AreEqual("new-value", conn.Wait(after4_bar));
// }
// }
// [Test]
// public void RenameKeyWithoutOverwrite()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "foo");
// conn.Keys.Remove(1, "bar");
// var check1 = conn.Keys.RenameIfNotExists(1, "foo", "bar"); // neither
// var after1_foo = conn.Strings.GetString(1, "foo");
// var after1_bar = conn.Strings.GetString(1, "bar");
// conn.Strings.Set(1, "foo", "foo-value");
// var check2 = conn.Keys.RenameIfNotExists(1, "foo", "bar"); // source only
// var after2_foo = conn.Strings.GetString(1, "foo");
// var after2_bar = conn.Strings.GetString(1, "bar");
// var check3 = conn.Keys.RenameIfNotExists(1, "foo", "bar"); // dest only
// var after3_foo = conn.Strings.GetString(1, "foo");
// var after3_bar = conn.Strings.GetString(1, "bar");
// conn.Strings.Set(1, "foo", "new-value");
// var check4 = conn.Keys.RenameIfNotExists(1, "foo", "bar"); // both
// var after4_foo = conn.Strings.GetString(1, "foo");
// var after4_bar = conn.Strings.GetString(1, "bar");
// try
// {
// conn.Wait(check1);
// Assert.Fail();
// }
// catch (RedisException) { }
// Assert.IsNull(conn.Wait(after1_foo));
// Assert.IsNull(conn.Wait(after1_bar));
// Assert.IsTrue(conn.Wait(check2));
// Assert.IsNull(conn.Wait(after2_foo));
// Assert.AreEqual("foo-value", conn.Wait(after2_bar));
// try
// {
// conn.Wait(check3);
// Assert.Fail();
// }
// catch (RedisException) { }
// Assert.IsNull(conn.Wait(after3_foo));
// Assert.AreEqual("foo-value", conn.Wait(after3_bar));
// Assert.IsFalse(conn.Wait(check4));
// Assert.AreEqual("new-value", conn.Wait(after4_foo));
// Assert.AreEqual("foo-value", conn.Wait(after4_bar));
// }
// }
// [Test]
// public void TestFind()
// {
// using(var conn = Config.GetUnsecuredConnection(allowAdmin:true))
// {
// conn.Server.FlushDb(5);
// conn.Strings.Set(5, "abc", "def");
// conn.Strings.Set(5, "abd", "ghi");
// conn.Strings.Set(5, "aef", "jkl");
// var arr = conn.Wait(conn.Keys.Find(5, "ab*"));
// Assert.AreEqual(2, arr.Length);
// Assert.Contains("abc", arr);
// Assert.Contains("abd", arr);
// }
// }
// [Test]
// public void TestDBSize()
// {
// using(var conn = Config.GetUnsecuredConnection(allowAdmin:true))
// {
// conn.Server.FlushDb(5);
// var empty = conn.Keys.GetLength(5);
// for (int i = 0; i < 10; i++ )
// conn.Strings.Set(5, "abc" + i, "def" + i);
// var withData = conn.Keys.GetLength(5);
// Assert.AreEqual(0, conn.Wait(empty));
// Assert.AreEqual(10, conn.Wait(withData));
// }
// }
// [Test]
// public void TestDebugObject()
// {
// using (var conn = Config.GetUnsecuredConnection(allowAdmin: true))
// {
// conn.Strings.Set(3, "test-debug", "some value");
// var s = conn.Wait(conn.Keys.DebugObject(3, "test-debug"));
// Assert.IsTrue(Regex.IsMatch(s, @"\bserializedlength:([0-9]+)\b"));
// }
// }
// }
//}
//using System.Text;
//using NUnit.Framework;
//using System.Linq;
//using System;
//using System.Threading;
//namespace Tests
//{
// [TestFixture]
// public class Lists // http://redis.io/commands#list
// {
// [Test]
// public void CheckLengthWhenEmpty()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(4, "mylist");
// var len = conn.Lists.GetLength(4, "mylist");
// Assert.AreEqual(0, conn.Wait(len));
// }
// }
// [Test]
// public void CheckLengthWithContents()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(4, "mylist");
// for (int i = 0; i < 100; i++)
// conn.Lists.AddLast(4, "mylist", new[] { (byte)i });
// var len = conn.Lists.GetLength(4, "mylist");
// Assert.AreEqual(100, conn.Wait(len));
// }
// }
// static byte[] Encode(string value) { return Encoding.UTF8.GetBytes(value); }
// static string Decode(byte[] value) { return Encoding.UTF8.GetString(value); }
// [Test]
// public void CheckRightPush()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.Keys.Remove(4, "mylist");
// var lenNil = conn.Features.PushIfNotExists ? conn.Lists.AddLast(4, "mylist", Encode("value1"), createIfMissing: false) : null;
// var len1 = conn.Lists.AddLast(4, "mylist", Encode("value1"));
// var len2 = conn.Lists.AddLast(4, "mylist", Encode("value2"));
// var items = conn.Lists.Range(4, "mylist", 0, -1);
// if (lenNil != null) Assert.AreEqual(0, conn.Wait(lenNil));
// Assert.AreEqual(1, conn.Wait(len1));
// Assert.AreEqual(2, conn.Wait(len2));
// var arr = conn.Wait(items);
// Assert.AreEqual(2, arr.Length);
// Assert.AreEqual("value1", Decode(arr[0]));
// Assert.AreEqual("value2", Decode(arr[1]));
// }
// }
// [Test]
// public void CheckLeftPush()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.Keys.Remove(4, "mylist");
// var lenNil = conn.Features.PushIfNotExists ? conn.Lists.AddLast(4, "mylist", Encode("value1"), createIfMissing: false) : null;
// var len1 = conn.Lists.AddFirst(4, "mylist", Encode("value1"));
// var len2 = conn.Lists.AddFirst(4, "mylist", Encode("value2"));
// var items = conn.Lists.Range(4, "mylist", 0, -1);
// if(lenNil != null) Assert.AreEqual(0, conn.Wait(lenNil));
// Assert.AreEqual(1, conn.Wait(len1));
// Assert.AreEqual(2, conn.Wait(len2));
// var arr = conn.Wait(items);
// Assert.AreEqual(2, arr.Length);
// Assert.AreEqual("value2", Decode(arr[0]));
// Assert.AreEqual("value1", Decode(arr[1]));
// }
// }
// [Test]
// public void CheckLeftPop()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(4, "mylist");
// conn.Lists.AddLast(4, "mylist", Encode("value1"));
// conn.Lists.AddLast(4, "mylist", Encode("value2"));
// var first = conn.Lists.RemoveFirst(4, "mylist");
// var second = conn.Lists.RemoveFirstString(4, "mylist");
// var third = conn.Lists.RemoveFirst(4, "mylist");
// var len = conn.Lists.GetLength(4, "mylist");
// Assert.AreEqual("value1", Decode(conn.Wait(first)));
// Assert.AreEqual("value2", conn.Wait(second));
// Assert.IsNull(conn.Wait(third));
// Assert.AreEqual(0, conn.Wait(len));
// }
// }
// [Test]
// public void CheckRightPop()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(4, "mylist");
// conn.Lists.AddLast(4, "mylist", Encode("value1"));
// conn.Lists.AddLast(4, "mylist", Encode("value2"));
// var first = conn.Lists.RemoveLast(4, "mylist");
// var second = conn.Lists.RemoveLastString(4, "mylist");
// var third = conn.Lists.RemoveLast(4, "mylist");
// var len = conn.Lists.GetLength(4, "mylist");
// Assert.AreEqual("value2", Decode(conn.Wait(first)));
// Assert.AreEqual("value1", conn.Wait(second));
// Assert.IsNull(conn.Wait(third));
// Assert.AreEqual(0, conn.Wait(len));
// }
// }
// [Test]
// public void CheckPushPop()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(4, "source");
// conn.Keys.Remove(4, "dest");
// var empty0 = conn.Lists.RemoveLastAndAddFirst(4, "source", "dest");
// var empty1 = conn.Lists.RemoveLastAndAddFirstString(4, "source", "dest");
// conn.Lists.AddLast(4, "source", "abc");
// conn.Lists.AddLast(4, "source", "def");
// var s = conn.Lists.RemoveLastAndAddFirstString(4, "source", "dest");
// var b = conn.Lists.RemoveLastAndAddFirst(4, "source", "dest");
// var l0 = conn.Lists.GetLength(4, "source");
// var l1 = conn.Lists.GetLength(4, "dest");
// var final = conn.Lists.RangeString(4, "dest", 0, 3);
// Assert.IsNull(conn.Wait(empty0));
// Assert.IsNull(conn.Wait(empty1));
// Assert.AreEqual("def", conn.Wait(s));
// Assert.AreEqual("abc", Decode(conn.Wait(b)));
// Assert.AreEqual(0, conn.Wait(l0));
// Assert.AreEqual(2, conn.Wait(l1));
// var arr = conn.Wait(final);
// Assert.AreEqual(2, arr.Length);
// Assert.AreEqual("abc", arr[0]);
// Assert.AreEqual("def", arr[1]);
// }
// }
// [Test]
// public void GetStringFromList()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(4, "mylist");
// var missing = conn.Lists.GetString(4, "mylist", 0);
// conn.Lists.AddLast(4, "mylist", "abc");
// conn.Lists.AddLast(4, "mylist", "def");
// conn.Lists.AddLast(4, "mylist", "ghi");
// var x0 = conn.Lists.GetString(4, "mylist", 0);
// var x1 = conn.Lists.GetString(4, "mylist", 1);
// var x2 = conn.Lists.GetString(4, "mylist", 2);
// var x3 = conn.Lists.GetString(4, "mylist", 3);
// var m1 = conn.Lists.GetString(4, "mylist", -1);
// var m2 = conn.Lists.GetString(4, "mylist", -2);
// var m3 = conn.Lists.GetString(4, "mylist", -3);
// var m4 = conn.Lists.GetString(4, "mylist", -4);
// Assert.IsNull(conn.Wait(missing));
// Assert.AreEqual("abc", conn.Wait(x0));
// Assert.AreEqual("def", conn.Wait(x1));
// Assert.AreEqual("ghi", conn.Wait(x2));
// Assert.IsNull(conn.Wait(x3));
// Assert.AreEqual("ghi", conn.Wait(m1));
// Assert.AreEqual("def", conn.Wait(m2));
// Assert.AreEqual("abc", conn.Wait(m3));
// Assert.IsNull(conn.Wait(m4));
// }
// }
// [Test]
// public void GetBytesFromList()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(4, "mylist");
// var missing = conn.Lists.GetString(4, "mylist", 0);
// conn.Lists.AddLast(4, "mylist", Encode("abc"));
// conn.Lists.AddLast(4, "mylist", Encode("def"));
// conn.Lists.AddLast(4, "mylist", Encode("ghi"));
// var x0 = conn.Lists.Get(4, "mylist", 0);
// var x1 = conn.Lists.Get(4, "mylist", 1);
// var x2 = conn.Lists.Get(4, "mylist", 2);
// var x3 = conn.Lists.Get(4, "mylist", 3);
// var m1 = conn.Lists.Get(4, "mylist", -1);
// var m2 = conn.Lists.Get(4, "mylist", -2);
// var m3 = conn.Lists.Get(4, "mylist", -3);
// var m4 = conn.Lists.Get(4, "mylist", -4);
// Assert.IsNull(conn.Wait(missing));
// Assert.AreEqual("abc", Decode(conn.Wait(x0)));
// Assert.AreEqual("def", Decode(conn.Wait(x1)));
// Assert.AreEqual("ghi", Decode(conn.Wait(x2)));
// Assert.IsNull(conn.Wait(x3));
// Assert.AreEqual("ghi", Decode(conn.Wait(m1)));
// Assert.AreEqual("def", Decode(conn.Wait(m2)));
// Assert.AreEqual("abc", Decode(conn.Wait(m3)));
// Assert.IsNull(conn.Wait(m4));
// }
// }
// [Test]
// public void TestListInsertString()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen:true))
// {
// if (conn.Features.ListInsert)
// {
// conn.Keys.Remove(2, "ins");
// conn.Lists.AddFirst(2, "ins", "x");
// var missingB = conn.Lists.InsertBefore(2, "ins", "abc", "AAA");
// var missingA = conn.Lists.InsertAfter(2, "ins", "abc", "BBB");
// conn.Lists.AddFirst(2, "ins", "abc");
// conn.Lists.AddFirst(2, "ins", "y");
// var existB = conn.Lists.InsertBefore(2, "ins", "abc", "CCC");
// var existA = conn.Lists.InsertAfter(2, "ins", "abc", "DDD");
// var all = conn.Lists.RangeString(2, "ins", 0, -1);
// Assert.AreEqual(-1, conn.Wait(missingB));
// Assert.AreEqual(-1, conn.Wait(missingA));
// Assert.AreEqual(4, conn.Wait(existB));
// Assert.AreEqual(5, conn.Wait(existA));
// string seq = string.Join(" ", conn.Wait(all));
// Assert.AreEqual("y CCC abc DDD x", seq);
// }
// }
// }
// [Test]
// public void TestListInsertBlob()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen:true))
// {
// if (conn.Features.ListInsert)
// {
// conn.Keys.Remove(2, "ins");
// conn.Lists.AddFirst(2, "ins", Encode("x"));
// var missingB = conn.Lists.InsertBefore(2, "ins", Encode("abc"), Encode("AAA"));
// var missingA = conn.Lists.InsertAfter(2, "ins", Encode("abc"), Encode("BBB"));
// conn.Lists.AddFirst(2, "ins", Encode("abc"));
// conn.Lists.AddFirst(2, "ins", Encode("y"));
// var existB = conn.Lists.InsertBefore(2, "ins", Encode("abc"), Encode("CCC"));
// var existA = conn.Lists.InsertAfter(2, "ins", Encode("abc"), Encode("DDD"));
// var all = conn.Lists.Range(2, "ins", 0, -1);
// Assert.AreEqual(-1, conn.Wait(missingB));
// Assert.AreEqual(-1, conn.Wait(missingA));
// Assert.AreEqual(4, conn.Wait(existB));
// Assert.AreEqual(5, conn.Wait(existA));
// string seq = string.Join(" ", conn.Wait(all).Select(Decode));
// Assert.AreEqual("y CCC abc DDD x", seq);
// }
// }
// }
// [Test]
// public void TestListByIndexString()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(2, "byindex");
// var notExists = conn.Lists.GetString(2, "byindex", 1);
// conn.Lists.AddLast(2, "byindex", "a");
// conn.Lists.AddLast(2, "byindex", "b");
// conn.Lists.AddLast(2, "byindex", "c");
// var item = conn.Lists.GetString(2, "byindex", 1);
// var outOfRange = conn.Lists.GetString(3, "byindex", 1);
// Assert.IsNull(conn.Wait(notExists));
// Assert.AreEqual("b", conn.Wait(item));
// Assert.IsNull(conn.Wait(outOfRange));
// }
// }
// [Test]
// public void TestListByIndexBlob()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(2, "byindex");
// var notExists = conn.Lists.Get(2, "byindex", 1);
// conn.Lists.AddLast(2, "byindex", Encode("a"));
// conn.Lists.AddLast(2, "byindex", Encode("b"));
// conn.Lists.AddLast(2, "byindex", Encode("c"));
// var item = conn.Lists.Get(2, "byindex", 1);
// var outOfRange = conn.Lists.Get(3, "byindex", 1);
// Assert.IsNull(conn.Wait(notExists));
// Assert.AreEqual("b", Decode(conn.Wait(item)));
// Assert.IsNull(conn.Wait(outOfRange));
// }
// }
// [Test]
// public void TestTrim()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(2, "trim");
// conn.Lists.Trim(2, "trim", 1);
// var ne = conn.Lists.GetLength(2, "trim");
// conn.Lists.AddLast(2, "trim", Encode("a"));
// conn.Lists.AddLast(2, "trim", Encode("b"));
// conn.Lists.AddLast(2, "trim", Encode("c"));
// conn.Lists.Trim(2, "trim", 1);
// var e = conn.Lists.GetLength(2, "trim");
// Assert.AreEqual(0, conn.Wait(ne));
// Assert.AreEqual(1, conn.Wait(e));
// }
// }
// [Test]
// public void TestSetByIndexString()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(2, "setbyindex");
// conn.Lists.AddLast(2, "setbyindex", "a");
// conn.Lists.AddLast(2, "setbyindex", "b");
// conn.Lists.AddLast(2, "setbyindex", "c");
// conn.Lists.Set(2, "setbyindex", 1, "d");
// var item = conn.Lists.GetString(2, "setbyindex", 1);
// Assert.AreEqual("d", conn.Wait(item));
// }
// }
// [Test]
// public void TestSetByIndexBlob()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(2, "setbyindex");
// conn.Lists.AddLast(2, "setbyindex", Encode("a"));
// conn.Lists.AddLast(2, "setbyindex", Encode("b"));
// conn.Lists.AddLast(2, "setbyindex", Encode("c"));
// conn.Lists.Set(2, "setbyindex", 1, Encode("d"));
// var item = conn.Lists.Get(2, "setbyindex", 1);
// Assert.AreEqual("d", Decode(conn.Wait(item)));
// }
// }
// [Test]
// public void TestRemoveString()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(2, "remove");
// var ne = conn.Lists.Remove(2, "remove", "b");
// conn.Lists.AddLast(2, "remove", "b");
// conn.Lists.AddLast(2, "remove", "a");
// conn.Lists.AddLast(2, "remove", "b");
// conn.Lists.AddLast(2, "remove", "c");
// conn.Lists.AddLast(2, "remove", "b");
// var e = conn.Lists.Remove(2, "remove", "b", count: 2);
// var count = conn.Lists.GetLength(2, "remove");
// Assert.AreEqual(0, conn.Wait(ne));
// Assert.AreEqual(2, conn.Wait(e));
// Assert.AreEqual(3, conn.Wait(count));
// }
// }
// [Test]
// public void TestRemoveBlob()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(2, "remove");
// var ne = conn.Lists.Remove(2, "remove", Encode("b"));
// conn.Lists.AddLast(2, "remove", Encode("b"));
// conn.Lists.AddLast(2, "remove", Encode("a"));
// conn.Lists.AddLast(2, "remove", Encode("b"));
// conn.Lists.AddLast(2, "remove", Encode("c"));
// conn.Lists.AddLast(2, "remove", Encode("b"));
// var e = conn.Lists.Remove(2, "remove", Encode("b"), count: 2);
// var count = conn.Lists.GetLength(2, "remove");
// Assert.AreEqual(0, conn.Wait(ne));
// Assert.AreEqual(2, conn.Wait(e));
// Assert.AreEqual(3, conn.Wait(count));
// }
// }
// [Test, ExpectedException(typeof(ArgumentOutOfRangeException))]
// public void TestTrimNeg()
// {
// using(var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "trim");
// conn.Lists.AddLast(1, "trim", "x");
// conn.Lists.AddLast(1, "trim", "x");
// conn.Lists.Trim(1, "trim", -1);
// }
// }
// [Test]
// public void TestTrimZero()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "trim");
// conn.Lists.AddLast(1, "trim", "x");
// conn.Lists.AddLast(1, "trim", "x");
// conn.Lists.Trim(1, "trim", 0);
// Assert.IsFalse(conn.Wait(conn.Keys.Exists(1, "trim")));
// Assert.AreEqual(0, conn.Wait(conn.Lists.GetLength(1, "trim")));
// }
// }
// [Test]
// public void TestTrimOne()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "trim");
// conn.Lists.AddLast(1, "trim", "x");
// conn.Lists.AddLast(1, "trim", "x");
// conn.Lists.Trim(1, "trim", 1);
// Assert.IsTrue(conn.Wait(conn.Keys.Exists(1, "trim")));
// Assert.AreEqual(1, conn.Wait(conn.Lists.GetLength(1, "trim")));
// }
// }
// [Test, ExpectedException(typeof(TimeoutException), ExpectedMessage = "The operation has timed out; possibly blocked by: 1: BLPOP \"blocking\" 5")]
// public void TestBlockingTimeout()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "blocking");
// conn.Lists.BlockingRemoveFirst(1, new[]{"blocking"}, 5);
// var next = conn.Strings.Get(1, "foofoo");
// conn.Wait(next);
// }
// }
// [Test]
// public void TestLeftBlockingPop()
// {
// using (var conn = Config.GetUnsecuredConnection())
// using (var conn2 = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "blocking");
// conn.Keys.Remove(1, "blocking-A");
// conn.Keys.Remove(1, "blocking-B");
// // empty, no data
// Assert.IsNull(conn.Lists.BlockingRemoveFirstString(1, new[] { "blocking" }, 1).Result);
// // empty, successful blocking getting data from another client
// var found = conn.Lists.BlockingRemoveFirstString(1, new[] { "blocking" }, 1);
// var len = conn2.Lists.AddLast(1, "blocking", "another client");
// Assert.AreEqual("blocking", conn.Wait(found).Item1);
// Assert.AreEqual("another client", conn.Wait(found).Item2);
// Assert.AreEqual(1, conn2.Wait(len));
// // empty, successful blocking getting data from another client, multiple keys
// found = conn.Lists.BlockingRemoveFirstString(1, new[] { "blocking-A", "blocking", "blocking-B" }, 1);
// len = conn2.Lists.AddLast(1, "blocking", "another client");
// Assert.AreEqual("blocking", conn.Wait(found).Item1);
// Assert.AreEqual("another client", conn.Wait(found).Item2);
// Assert.AreEqual(1, conn2.Wait(len));
// // data, no need to block
// conn.Lists.AddLast(1, "blocking", "abc");
// len = conn.Lists.AddLast(1, "blocking", "def");
// var found0 = conn.Lists.BlockingRemoveFirstString(1, new[] { "blocking" }, 1);
// var found1 = conn.Lists.BlockingRemoveFirstString(1, new[] { "blocking" }, 1);
// var found2 = conn.Lists.BlockingRemoveFirstString(1, new[] { "blocking" }, 1);
// Assert.AreEqual(2, conn.Wait(len));
// Assert.AreEqual("blocking", conn.Wait(found0).Item1);
// Assert.AreEqual("abc", conn.Wait(found0).Item2);
// Assert.AreEqual("blocking", conn.Wait(found1).Item1);
// Assert.AreEqual("def", conn.Wait(found1).Item2);
// Assert.IsNull(found2.Result);
// }
// }
// [Test]
// public void TestRightBlockingPop()
// {
// using (var conn = Config.GetUnsecuredConnection())
// using (var conn2 = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "blocking");
// conn.Keys.Remove(1, "blocking-A");
// conn.Keys.Remove(1, "blocking-B");
// // empty, no data
// Assert.IsNull(conn.Lists.BlockingRemoveLastString(1, new[] { "blocking" }, 1).Result);
// // empty, successful blocking getting data from another client
// var found = conn.Lists.BlockingRemoveLastString(1, new[] { "blocking" }, 1);
// var len = conn2.Lists.AddLast(1, "blocking", "another client");
// Assert.AreEqual("blocking", conn.Wait(found).Item1);
// Assert.AreEqual("another client", conn.Wait(found).Item2);
// Assert.AreEqual(1, conn2.Wait(len));
// // empty, successful blocking getting data from another client, multiple keys
// found = conn.Lists.BlockingRemoveLastString(1, new[] { "blocking-A", "blocking", "blocking-B" }, 1);
// len = conn2.Lists.AddLast(1, "blocking", "another client");
// Assert.AreEqual("blocking", conn.Wait(found).Item1);
// Assert.AreEqual("another client", conn.Wait(found).Item2);
// Assert.AreEqual(1, conn2.Wait(len));
// // data, no need to block
// conn.Lists.AddLast(1, "blocking", "abc");
// len = conn.Lists.AddLast(1, "blocking", "def");
// var found0 = conn.Lists.BlockingRemoveLastString(1, new[] { "blocking" }, 1);
// var found1 = conn.Lists.BlockingRemoveLastString(1, new[] { "blocking" }, 1);
// var found2 = conn.Lists.BlockingRemoveLastString(1, new[] { "blocking" }, 1);
// Assert.AreEqual(2, conn.Wait(len));
// Assert.AreEqual("blocking", conn.Wait(found0).Item1);
// Assert.AreEqual("def", conn.Wait(found0).Item2);
// Assert.AreEqual("blocking", conn.Wait(found1).Item1);
// Assert.AreEqual("abc", conn.Wait(found1).Item2);
// Assert.IsNull(found2.Result);
// }
// }
// [Test]
// public void TestLeftBlockingPopBytes()
// {
// using (var conn = Config.GetUnsecuredConnection())
// using (var conn2 = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "blocking");
// conn.Keys.Remove(1, "blocking-A");
// conn.Keys.Remove(1, "blocking-B");
// // empty, no data
// Assert.IsNull(conn.Lists.BlockingRemoveFirst(1, new[] { "blocking" }, 1).Result);
// // empty, successful blocking getting data from another client
// var found = conn.Lists.BlockingRemoveFirst(1, new[] { "blocking" }, 1);
// var len = conn2.Lists.AddLast(1, "blocking", "another client");
// Assert.AreEqual("blocking", conn.Wait(found).Item1);
// Assert.AreEqual("another client", Encoding.UTF8.GetString(conn.Wait(found).Item2));
// Assert.AreEqual(1, conn2.Wait(len));
// // empty, successful blocking getting data from another client, multiple keys
// found = conn.Lists.BlockingRemoveFirst(1, new[] { "blocking-A", "blocking", "blocking-B" }, 1);
// len = conn2.Lists.AddLast(1, "blocking", "another client");
// Assert.AreEqual("blocking", conn.Wait(found).Item1);
// Assert.AreEqual("another client", Encoding.UTF8.GetString(conn.Wait(found).Item2));
// Assert.AreEqual(1, conn2.Wait(len));
// // data, no need to block
// conn.Lists.AddLast(1, "blocking", "abc");
// len = conn.Lists.AddLast(1, "blocking", "def");
// var found0 = conn.Lists.BlockingRemoveFirst(1, new[] { "blocking" }, 1);
// var found1 = conn.Lists.BlockingRemoveFirst(1, new[] { "blocking" }, 1);
// var found2 = conn.Lists.BlockingRemoveFirst(1, new[] { "blocking" }, 1);
// Assert.AreEqual(2, conn.Wait(len));
// Assert.AreEqual("blocking", conn.Wait(found0).Item1);
// Assert.AreEqual("abc", Encoding.UTF8.GetString(conn.Wait(found0).Item2));
// Assert.AreEqual("blocking", conn.Wait(found1).Item1);
// Assert.AreEqual("def", Encoding.UTF8.GetString(conn.Wait(found1).Item2));
// Assert.IsNull(found2.Result);
// }
// }
// [Test]
// public void TestRightBlockingPopBytes()
// {
// using (var conn = Config.GetUnsecuredConnection())
// using (var conn2 = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "blocking");
// conn.Keys.Remove(1, "blocking-A");
// conn.Keys.Remove(1, "blocking-B");
// // empty, no data
// Assert.IsNull(conn.Lists.BlockingRemoveLast(1, new[] { "blocking" }, 1).Result);
// // empty, successful blocking getting data from another client
// var found = conn.Lists.BlockingRemoveLast(1, new[] { "blocking" }, 1);
// var len = conn2.Lists.AddLast(1, "blocking", "another client");
// Assert.AreEqual("blocking", conn.Wait(found).Item1);
// Assert.AreEqual("another client", Encoding.UTF8.GetString(conn.Wait(found).Item2));
// Assert.AreEqual(1, conn2.Wait(len));
// // empty, successful blocking getting data from another client, multiple keys
// found = conn.Lists.BlockingRemoveLast(1, new[] { "blocking-A", "blocking", "blocking-B" }, 1);
// len = conn2.Lists.AddLast(1, "blocking", "another client");
// Assert.AreEqual("blocking", conn.Wait(found).Item1);
// Assert.AreEqual("another client", Encoding.UTF8.GetString(conn.Wait(found).Item2));
// Assert.AreEqual(1, conn2.Wait(len));
// // data, no need to block
// conn.Lists.AddLast(1, "blocking", "abc");
// len = conn.Lists.AddLast(1, "blocking", "def");
// var found0 = conn.Lists.BlockingRemoveLast(1, new[] { "blocking" }, 1);
// var found1 = conn.Lists.BlockingRemoveLast(1, new[] { "blocking" }, 1);
// var found2 = conn.Lists.BlockingRemoveLast(1, new[] { "blocking" }, 1);
// Assert.AreEqual(2, conn.Wait(len));
// Assert.AreEqual("blocking", conn.Wait(found0).Item1);
// Assert.AreEqual("def", Encoding.UTF8.GetString(conn.Wait(found0).Item2));
// Assert.AreEqual("blocking", conn.Wait(found1).Item1);
// Assert.AreEqual("abc", Encoding.UTF8.GetString(conn.Wait(found1).Item2));
// Assert.IsNull(found2.Result);
// }
// }
// [Test]
// public void TestBlockingPopPush()
// {
// using (var conn = Config.GetUnsecuredConnection())
// using (var conn2 = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "source");
// conn.Keys.Remove(1, "target");
// // empty
// var found = conn.Lists.BlockingRemoveLastAndAddFirstString(1, "source", "target", 1);
// Assert.IsNull(found.Result);
// // already data
// conn.Lists.AddLast(1, "source", "abc");
// conn.Lists.AddLast(1, "source", "def");
// var found0 = conn.Lists.BlockingRemoveLastAndAddFirstString(1, "source", "target", 1);
// var found1 = conn.Lists.BlockingRemoveLastAndAddFirstString(1, "source", "target", 1);
// var found2 = conn.Lists.BlockingRemoveLastAndAddFirstString(1, "source", "target", 1);
// Assert.AreEqual("def", found0.Result);
// Assert.AreEqual("abc", found1.Result);
// Assert.IsNull(found2.Result);
// // add data from another client
// conn.Lists.AddFirst(1, "source", "abc");
// found0 = conn.Lists.BlockingRemoveLastAndAddFirstString(1, "source", "target", 1);
// found1 = conn.Lists.BlockingRemoveLastAndAddFirstString(1, "source", "target", 1);
// found2 = conn.Lists.BlockingRemoveLastAndAddFirstString(1, "source", "target", 1);
// var found3 = conn.Lists.BlockingRemoveLastAndAddFirstString(1, "source", "target", 1);
// conn2.Lists.AddFirst(1, "source", "def");
// conn2.Lists.AddFirst(1, "source", "ghi");
// Assert.AreEqual("abc", found0.Result);
// Assert.AreEqual("def", found1.Result);
// Assert.AreEqual("ghi", found2.Result);
// Assert.IsNull(found3.Result);
// }
// }
// [Test]
// public void TestBlockingPopPushBytes()
// {
// using (var conn = Config.GetUnsecuredConnection())
// using (var conn2 = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "source");
// conn.Keys.Remove(1, "target");
// // empty
// var found = conn.Lists.BlockingRemoveLastAndAddFirst(1, "source", "target", 1);
// Assert.IsNull(found.Result);
// // already data
// conn.Lists.AddLast(1, "source", "abc");
// conn.Lists.AddLast(1, "source", "def");
// var found0 = conn.Lists.BlockingRemoveLastAndAddFirst(1, "source", "target", 1);
// var found1 = conn.Lists.BlockingRemoveLastAndAddFirst(1, "source", "target", 1);
// var found2 = conn.Lists.BlockingRemoveLastAndAddFirst(1, "source", "target", 1);
// Assert.AreEqual("def", Encoding.UTF8.GetString(found0.Result));
// Assert.AreEqual("abc", Encoding.UTF8.GetString(found1.Result));
// Assert.IsNull(found2.Result);
// // add data from another client
// conn.Lists.AddFirst(1, "source", "abc");
// found0 = conn.Lists.BlockingRemoveLastAndAddFirst(1, "source", "target", 1);
// found1 = conn.Lists.BlockingRemoveLastAndAddFirst(1, "source", "target", 1);
// found2 = conn.Lists.BlockingRemoveLastAndAddFirst(1, "source", "target", 1);
// var found3 = conn.Lists.BlockingRemoveLastAndAddFirst(1, "source", "target", 1);
// Thread.Sleep(100); // make sure those commands at least get queued before conn2 starts monkeying
// conn2.Lists.AddFirst(1, "source", "def");
// conn2.Lists.AddFirst(1, "source", "ghi");
// Assert.AreEqual("abc", Encoding.UTF8.GetString(found0.Result));
// Assert.AreEqual("def", Encoding.UTF8.GetString(found1.Result));
// Assert.AreEqual("ghi", Encoding.UTF8.GetString(found2.Result));
// Assert.IsNull(found3.Result);
// }
// }
// }
//}
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using BookSleeve;
//using NUnit.Framework;
//using System.Threading;
//using System.Threading.Tasks;
//namespace Tests
//{
// [TestFixture]
// public class Locking
// {
// [Test]
// public void AggressiveParallel()
// {
// int count = 2;
// int errorCount = 0;
// ManualResetEvent evt = new ManualResetEvent(false);
// using (var c1 = Config.GetUnsecuredConnection(waitForOpen: true))
// using (var c2 = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// WaitCallback cb = obj =>
// {
// var conn = (RedisConnection)obj;
// conn.Error += delegate { Interlocked.Increment(ref errorCount); };
// for(int i = 0 ; i < 1000 ; i++)
// {
// conn.Strings.TakeLock(2, "abc", "def", 5);
// }
// conn.Wait(conn.Server.Ping());
// conn.Close(false);
// if (Interlocked.Decrement(ref count) == 0) evt.Set();
// };
// ThreadPool.QueueUserWorkItem(cb, c1);
// ThreadPool.QueueUserWorkItem(cb, c2);
// evt.WaitOne(8000);
// }
// Assert.AreEqual(0, Interlocked.CompareExchange(ref errorCount, 0, 0));
// }
// [Test]
// public void TestOpCountByVersionLocal_UpLevel()
// {
// using (var conn = Config.GetUnsecuredConnection(open: false))
// {
// TestLockOpCountByVersion(conn, 1, false);
// TestLockOpCountByVersion(conn, 1, true);
// //TestManualLockOpCountByVersion(conn, 5, false);
// //TestManualLockOpCountByVersion(conn, 3, true);
// }
// }
// [Test]
// public void TestOpCountByVersionLocal_DownLevel()
// {
// using (var conn = Config.GetUnsecuredConnection(open: false))
// {
// conn.SetServerVersion(new Version(2, 6, 0), ServerType.Master);
// TestLockOpCountByVersion(conn, 5, false);
// TestLockOpCountByVersion(conn, 3, true);
// //TestManualLockOpCountByVersion(conn, 5, false);
// //TestManualLockOpCountByVersion(conn, 3, true);
// }
// }
// [Test]
// public void TestOpCountByVersionRemote()
// {
// using (var conn = Config.GetRemoteConnection(open:false))
// {
// TestLockOpCountByVersion(conn, 1, false);
// TestLockOpCountByVersion(conn, 1, true);
// //TestManualLockOpCountByVersion(conn, 1, false);
// //TestManualLockOpCountByVersion(conn, 1, true);
// }
// }
// public void TestLockOpCountByVersion(RedisConnection conn, int expected, bool existFirst)
// {
// const int DB = 0, LockDuration = 30;
// const string Key = "TestOpCountByVersion";
// conn.Wait(conn.Open());
// conn.Keys.Remove(DB, Key);
// var newVal = "us:" + Config.CreateUniqueName();
// string expectedVal = newVal;
// if (existFirst)
// {
// expectedVal = "other:" + Config.CreateUniqueName();
// conn.Strings.Set(DB, Key, expectedVal, LockDuration);
// }
// int countBefore = conn.GetCounters().MessagesSent;
// var taken = conn.Wait(conn.Strings.TakeLock(DB, Key, newVal, LockDuration));
// int countAfter = conn.GetCounters().MessagesSent;
// var valAfter = conn.Wait(conn.Strings.GetString(DB, Key));
// Assert.AreEqual(!existFirst, taken, "lock taken");
// Assert.AreEqual(expectedVal, valAfter, "taker");
// Assert.AreEqual(expected, (countAfter - countBefore) - 1, "expected ops (including ping)");
// // note we get a ping from GetCounters
// }
// [Test]
// public void TakeLockAndExtend()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// string right = Guid.NewGuid().ToString(),
// wrong = Guid.NewGuid().ToString();
// const int DB = 7;
// const string Key = "lock-key";
// conn.SuspendFlush();
// conn.Keys.Remove(DB, Key);
// var t1 = conn.Strings.TakeLock(DB, Key, right, 20);
// var t1b = conn.Strings.TakeLock(DB, Key, wrong, 10);
// var t2 = conn.Strings.GetString(DB, Key);
// var t3 = conn.Strings.ReleaseLock(DB, Key, wrong);
// var t4 = conn.Strings.GetString(DB, Key);
// var t5 = conn.Strings.ExtendLock(DB, Key, wrong, 60);
// var t6 = conn.Strings.GetString(DB, Key);
// var t7 = conn.Keys.TimeToLive(DB, Key);
// var t8 = conn.Strings.ExtendLock(DB, Key, right, 60);
// var t9 = conn.Strings.GetString(DB, Key);
// var t10 = conn.Keys.TimeToLive(DB, Key);
// var t11 = conn.Strings.ReleaseLock(DB, Key, right);
// var t12 = conn.Strings.GetString(DB, Key);
// var t13 = conn.Strings.TakeLock(DB, Key, wrong, 10);
// conn.ResumeFlush();
// Assert.IsNotNull(right);
// Assert.IsNotNull(wrong);
// Assert.AreNotEqual(right, wrong);
// Assert.IsTrue(conn.Wait(t1), "1");
// Assert.IsFalse(conn.Wait(t1b), "1b");
// Assert.AreEqual(right, conn.Wait(t2), "2");
// Assert.IsFalse(conn.Wait(t3), "3");
// Assert.AreEqual(right, conn.Wait(t4), "4");
// Assert.IsFalse(conn.Wait(t5), "5");
// Assert.AreEqual(right, conn.Wait(t6), "6");
// var ttl = conn.Wait(t7);
// Assert.IsTrue(ttl > 0 && ttl <= 20, "7");
// Assert.IsTrue(conn.Wait(t8), "8");
// Assert.AreEqual(right, conn.Wait(t9), "9");
// ttl = conn.Wait(t10);
// Assert.IsTrue(ttl > 50 && ttl <= 60, "10");
// Assert.IsTrue(conn.Wait(t11), "11");
// Assert.IsNull(conn.Wait(t12), "12");
// Assert.IsTrue(conn.Wait(t13), "13");
// }
// }
// //public void TestManualLockOpCountByVersion(RedisConnection conn, int expected, bool existFirst)
// //{
// // const int DB = 0, LockDuration = 30;
// // const string Key = "TestManualLockOpCountByVersion";
// // conn.Wait(conn.Open());
// // conn.Keys.Remove(DB, Key);
// // var newVal = "us:" + Config.CreateUniqueName();
// // string expectedVal = newVal;
// // if (existFirst)
// // {
// // expectedVal = "other:" + Config.CreateUniqueName();
// // conn.Strings.Set(DB, Key, expectedVal, LockDuration);
// // }
// // int countBefore = conn.GetCounters().MessagesSent;
// // var tran = conn.CreateTransaction();
// // tran.AddCondition(Condition.KeyNotExists(DB, Key));
// // tran.Strings.Set(DB, Key, newVal, LockDuration);
// // var taken = conn.Wait(tran.Execute());
// // int countAfter = conn.GetCounters().MessagesSent;
// // var valAfter = conn.Wait(conn.Strings.GetString(DB, Key));
// // Assert.AreEqual(!existFirst, taken, "lock taken (manual)");
// // Assert.AreEqual(expectedVal, valAfter, "taker (manual)");
// // Assert.AreEqual(expected, (countAfter - countBefore) - 1, "expected ops (including ping) (manual)");
// // // note we get a ping from GetCounters
// //}
// [Test]
// public void TestBasicLockNotTaken()
// {
// using(var conn = Config.GetUnsecuredConnection())
// {
// int errorCount = 0;
// conn.Error += delegate { Interlocked.Increment(ref errorCount); };
// Task<bool> taken = null;
// Task<string> newValue = null;
// Task<long> ttl = null;
// const int LOOP = 50;
// for (int i = 0; i < LOOP; i++)
// {
// conn.Keys.Remove(0, "lock-not-exists");
// taken = conn.Strings.TakeLock(0, "lock-not-exists", "new-value", 10);
// newValue = conn.Strings.GetString(0, "lock-not-exists");
// ttl = conn.Keys.TimeToLive(0, "lock-not-exists");
// }
// Assert.IsTrue(conn.Wait(taken), "taken");
// Assert.AreEqual("new-value", conn.Wait(newValue));
// var ttlValue = conn.Wait(ttl);
// Assert.IsTrue(ttlValue >= 8 && ttlValue <= 10, "ttl");
// Assert.AreEqual(0, errorCount);
// }
// }
// [Test]
// public void TestBasicLockTaken()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(0, "lock-exists");
// conn.Strings.Set(0, "lock-exists", "old-value", expirySeconds: 20);
// var taken = conn.Strings.TakeLock(0, "lock-exists", "new-value", 10);
// var newValue = conn.Strings.GetString(0, "lock-exists");
// var ttl = conn.Keys.TimeToLive(0, "lock-exists");
// Assert.IsFalse(conn.Wait(taken), "taken");
// Assert.AreEqual("old-value", conn.Wait(newValue));
// var ttlValue = conn.Wait(ttl);
// Assert.IsTrue(ttlValue >= 18 && ttlValue <= 20, "ttl");
// }
// }
// }
//}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{97B45B3A-34DB-43C3-A979-37F217390142}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MigratedBookSleeveTestSuite</RootNamespace>
<AssemblyName>MigratedBookSleeveTestSuite</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework">
<HintPath>..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Batches.cs" />
<Compile Include="Config.cs" />
<Compile Include="Connection.cs" />
<Compile Include="Constraints.cs" />
<Compile Include="Hashes.cs" />
<Compile Include="Issues\Issue10.cs" />
<Compile Include="Issues\Massive Delete.cs" />
<Compile Include="Issues\SO10504853.cs" />
<Compile Include="Issues\SO10825542.cs" />
<Compile Include="Issues\SO11766033.cs" />
<Compile Include="Keys.cs" />
<Compile Include="Lists.cs" />
<Compile Include="Locking.cs" />
<Compile Include="Performance.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="PubSub.cs" />
<Compile Include="redis-sharp.cs" />
<Compile Include="Scripting.cs" />
<Compile Include="Server.cs" />
<Compile Include="Sets.cs" />
<Compile Include="SortedSets.cs" />
<Compile Include="Strings.cs" />
<Compile Include="Transactions.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\StackExchange.Redis\StackExchange.Redis.csproj">
<Project>{7cec07f2-8c03-4c42-b048-738b215824c1}</Project>
<Name>StackExchange.Redis</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
//using System;
//using System.Diagnostics;
//using System.Text;
//using System.Threading.Tasks;
//using NUnit.Framework;
//namespace Tests
//{
// [TestFixture]
// public class Performance
// {
// [Test]
// public void VerifyPerformanceImprovement()
// {
// int asyncTimer, sync, op = 0, asyncFaF, syncFaF;
// using (var conn = Config.GetUnsecuredConnection())
// {
// // do these outside the timings, just to ensure the core methods are JITted etc
// for (int db = 0; db < 5; db++ )
// conn.Keys.Remove(db, "perftest");
// var timer = Stopwatch.StartNew();
// for (int i = 0; i < 100; i++)
// {
// // want to test multiplex scenario; test each db, but to make it fair we'll
// // do in batches of 10 on each
// for (int db = 0; db < 5; db++)
// for (int j = 0; j < 10; j++)
// conn.Strings.Increment(db, "perftest");
// }
// asyncFaF = (int)timer.ElapsedMilliseconds;
// Task<string>[] final = new Task<string>[5];
// for (int db = 0; db < 5; db++)
// final[db] = conn.Strings.GetString(db, "perftest");
// conn.WaitAll(final);
// timer.Stop();
// asyncTimer = (int)timer.ElapsedMilliseconds;
// Console.WriteLine("async to completion (local): {0}ms", timer.ElapsedMilliseconds);
// for (int db = 0; db < 5; db++)
// Assert.AreEqual("1000", final[db].Result, "async, db:" + db);
// }
// using (var conn = new Redis(Config.LocalHost, 6379))
// {
// // do these outside the timings, just to ensure the core methods are JITted etc
// for (int db = 0; db < 5; db++) {
// conn.Db = db;
// conn.Remove("perftest");
// }
// var timer = Stopwatch.StartNew();
// for (int i = 0; i < 100; i++)
// {
// // want to test multiplex scenario; test each db, but to make it fair we'll
// // do in batches of 10 on each
// for (int db = 0; db < 5; db++) {
// conn.Db = db;
// op++;
// for (int j = 0; j < 10; j++) {
// conn.Increment("perftest");
// op++;
// }
// }
// }
// syncFaF = (int)timer.ElapsedMilliseconds;
// string[] final = new string[5];
// for (int db = 0; db < 5; db++) {
// conn.Db = db;
// final[db] = Encoding.ASCII.GetString(conn.Get("perftest"));
// }
// timer.Stop();
// sync = (int)timer.ElapsedMilliseconds;
// Console.WriteLine("sync to completion (local): {0}ms", timer.ElapsedMilliseconds);
// for (int db = 0; db < 5; db++)
// Assert.AreEqual("1000", final[db], "async, db:" + db);
// }
// int effectiveAsync = ((10 * asyncTimer) + 3) / 10;
// int effectiveSync = ((10 * sync) + (op * 3)) / 10;
// Console.WriteLine("async to completion with assumed 0.3ms LAN latency: " + effectiveAsync);
// Console.WriteLine("sync to completion with assumed 0.3ms LAN latency: " + effectiveSync);
// Console.WriteLine("fire-and-forget: {0}ms sync vs {1}ms async ", syncFaF, asyncFaF);
// Assert.Less(effectiveAsync, effectiveSync, "Everything");
// Assert.Less(asyncFaF, syncFaF, "Fire and Forget");
// }
// }
//}
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using NUnit.Framework;
//using System.Reflection;
//using System.Threading.Tasks;
//namespace Tests
//{
// class Program
// {
// static void Main()
// {
// try
// {
// Main2();
// }
// catch (Exception ex)
// {
// Console.WriteLine();
// Console.WriteLine("CRAZY ERRORS: " + ex);
// }
// finally
// {
// Console.WriteLine("Press any key to exit");
// Console.ReadKey();
// }
// }
// static void Main2() {
// // why is this here? because some dumbass forgot to install a decent test-runner before going to the airport
// var epicFail = new List<string>();
// var testTypes = from type in typeof(Program).Assembly.GetTypes()
// where Attribute.IsDefined(type, typeof(TestFixtureAttribute))
// && !Attribute.IsDefined(type, typeof(IgnoreAttribute))
// let methods = type.GetMethods()
// select new
// {
// Type = type,
// Methods = methods,
// ActiveMethods = methods.Where(x => Attribute.IsDefined(x, typeof(ActiveTestAttribute))).ToArray(),
// Setup = methods.SingleOrDefault(x => Attribute.IsDefined(x, typeof(TestFixtureSetUpAttribute))),
// TearDown = methods.SingleOrDefault(x => Attribute.IsDefined(x, typeof(TestFixtureTearDownAttribute)))
// };
// int pass = 0, fail = 0;
// bool activeOnly = testTypes.SelectMany(x => x.ActiveMethods).Any();
// TaskScheduler.UnobservedTaskException += (sender, args) =>
// {
// args.SetObserved();
// //if (args.Exception is AggregateException)
// //{
// // foreach (var ex in ((AggregateException)args.Exception).InnerExceptions)
// // {
// // Console.WriteLine(ex.Message);
// // }
// //}
// //else
// //{
// // Console.WriteLine(args.Exception.Message);
// //}
// };
// foreach (var type in testTypes)
// {
// var tests = (from method in (activeOnly ? type.ActiveMethods : type.Methods)
// where Attribute.IsDefined(method, typeof(TestAttribute))
// && !Attribute.IsDefined(method, typeof(IgnoreAttribute))
// select method).ToArray();
// if (tests.Length == 0) continue;
// Console.WriteLine(type.Type.FullName);
// object obj;
// try
// {
// obj = Activator.CreateInstance(type.Type);
// if (obj == null) throw new InvalidOperationException("the world has gone mad");
// }
// catch (Exception ex)
// {
// Console.WriteLine(ex.Message);
// continue;
// }
// using (obj as IDisposable)
// {
// if (type.Setup != null)
// {
// try { type.Setup.Invoke(obj, null); }
// catch (Exception ex)
// {
// Console.WriteLine("Test fixture startup failed: " + ex.Message);
// fail++;
// epicFail.Add(type.Setup.DeclaringType.FullName + "." + type.Setup.Name);
// continue;
// }
// }
// foreach (var test in tests)
// {
// var expectedFail = Attribute.GetCustomAttribute(test, typeof(ExpectedExceptionAttribute)) as ExpectedExceptionAttribute;
// Console.Write(test.Name + ": ");
// Exception err = null;
// try
// {
// int count = 1;
// if (activeOnly)
// {
// var ata = test.GetCustomAttribute(typeof(ActiveTestAttribute)) as ActiveTestAttribute;
// if (ata != null) count = ata.Count;
// }
// while (count-- > 0)
// {
// test.Invoke(obj, null);
// }
// }
// catch (TargetInvocationException ex)
// {
// err = ex.InnerException;
// }
// catch (Exception ex)
// {
// err = ex;
// }
// if (err is AggregateException && ((AggregateException)err).InnerExceptions.Count == 1)
// {
// err = ((AggregateException)err).InnerExceptions[0];
// }
// if (expectedFail != null)
// {
// if (err == null)
// {
// err = new NUnit.Framework.AssertionException("failed to fail");
// }
// else
// {
// int issues = 0;
// if (expectedFail.ExpectedException != null && !expectedFail.ExpectedException.IsAssignableFrom(err.GetType()))
// {
// issues++;
// }
// if (expectedFail.ExpectedExceptionName != null && err.GetType().FullName != expectedFail.ExpectedExceptionName)
// {
// issues++;
// }
// if (expectedFail.ExpectedMessage != null && err.Message != expectedFail.ExpectedMessage)
// {
// issues++;
// }
// if (issues == 0) err = null;
// else
// {
// err = new InvalidOperationException("Failed in a different way", err);
// }
// }
// }
// if (err == null)
// {
// Console.WriteLine("pass");
// pass++;
// }
// else
// {
// Console.WriteLine(err.Message);
// fail++;
// epicFail.Add(test.DeclaringType.FullName + "." + test.Name);
// }
// }
// if (type.TearDown != null)
// {
// try { type.TearDown.Invoke(obj, null); }
// catch (Exception ex)
// {
// Console.WriteLine("Test fixture teardown failed: " + ex.Message);
// fail++;
// epicFail.Add(type.TearDown.DeclaringType.FullName + "." + type.TearDown.Name);
// }
// }
// }
// }
// Console.WriteLine("Passed: {0}; Failed: {1}", pass, fail);
// foreach (var msg in epicFail) Console.WriteLine(msg);
//#if DEBUG
// Console.WriteLine();
// Console.WriteLine("Callbacks: {0:###,###,##0} sync, {1:###,###,##0} async",
// BookSleeve.RedisConnectionBase.AllSyncCallbacks, BookSleeve.RedisConnectionBase.AllAsyncCallbacks);
//#endif
// }
// }
//}
//[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
//public sealed class ActiveTestAttribute : Attribute {
// private readonly int count;
// public int Count { get { return count; } }
// public ActiveTestAttribute() : this(1) { }
// public ActiveTestAttribute(int count) { this.count = count; }
//}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MigratedBookSleeveTestSuite")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MigratedBookSleeveTestSuite")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("350d3b30-78dd-4b74-a76d-bb593a05e8d1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//using NUnit.Framework;
//using System.Threading;
//using System.Text;
//using System;
//using System.Diagnostics;
//using System.Threading.Tasks;
//using BookSleeve;
//using System.Collections.Generic;
//namespace Tests
//{
// [TestFixture]
// public class PubSub // http://redis.io/commands#pubsub
// {
// [Test]
// public void TestPublishWithNoSubscribers()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// Assert.AreEqual(0, conn.Wait(conn.Publish("channel", "message")));
// }
// }
// [Test]
// public void TestMassivePublishWithWithoutFlush_Local()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// TestMassivePublishWithWithoutFlush(conn, "local");
// }
// }
// [Test]
// public void TestMassivePublishWithWithoutFlush_Remote()
// {
// using (var conn = Config.GetRemoteConnection(waitForOpen: true))
// {
// TestMassivePublishWithWithoutFlush(conn, "remote");
// }
// }
// private void TestMassivePublishWithWithoutFlush(RedisConnection conn, string caption)
// {
// const int loop = 100000;
// GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
// GC.WaitForPendingFinalizers();
// var tasks = new Task[loop];
// var withFlush = Stopwatch.StartNew();
// for (int i = 0; i < loop; i++)
// tasks[i] = conn.Publish("foo", "bar");
// conn.WaitAll(tasks);
// withFlush.Stop();
// GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
// GC.WaitForPendingFinalizers();
// conn.SuspendFlush();
// var withoutFlush = Stopwatch.StartNew();
// for (int i = 0; i < loop; i++)
// tasks[i] = conn.Publish("foo", "bar");
// conn.ResumeFlush();
// conn.WaitAll(tasks);
// withoutFlush.Stop();
// Assert.Less(1, 2, "sanity check");
// Assert.Less(withoutFlush.ElapsedMilliseconds, withFlush.ElapsedMilliseconds, caption);
// Console.WriteLine("{2}: {0}ms (eager-flush) vs {1}ms (suspend-flush)",
// withFlush.ElapsedMilliseconds, withoutFlush.ElapsedMilliseconds, caption);
// }
// [Test]
// public void PubSubOrder()
// {
// using (var pub = Config.GetRemoteConnection(waitForOpen: true))
// using (var sub = pub.GetOpenSubscriberChannel())
// {
// string channel = "PubSubOrder";
// const int count = 500000;
// object syncLock = new object();
// List<int> data = new List<int>(count);
// sub.CompletionMode = ResultCompletionMode.PreserveOrder;
// sub.Subscribe(channel, (key,val) => {
// bool pulse;
// lock (data)
// {
// data.Add(int.Parse(Encoding.UTF8.GetString(val)));
// pulse = data.Count == count;
// if((data.Count % 10) == 99) Console.WriteLine(data.Count);
// }
// if(pulse)
// lock(syncLock)
// Monitor.PulseAll(syncLock);
// }).Wait();
// lock (syncLock)
// {
// for (int i = 0; i < count; i++)
// {
// pub.Publish(channel, i.ToString());
// }
// if (!Monitor.Wait(syncLock, 10000))
// {
// throw new TimeoutException("Items: " + data.Count);
// }
// for (int i = 0; i < count; i++)
// Assert.AreEqual(i, data[i]);
// }
// }
// }
// [Test]
// public void TestPublishWithSubscribers()
// {
// using (var listenA = Config.GetSubscriberConnection())
// using (var listenB = Config.GetSubscriberConnection())
// using (var conn = Config.GetUnsecuredConnection())
// {
// var t1 = listenA.Subscribe("channel", delegate { });
// var t2 = listenB.Subscribe("channel", delegate { });
// listenA.Wait(t1);
// Assert.AreEqual(1, listenA.SubscriptionCount, "A subscriptions");
// listenB.Wait(t2);
// Assert.AreEqual(1, listenB.SubscriptionCount, "B subscriptions");
// var pub = conn.Publish("channel", "message");
// Assert.AreEqual(2, conn.Wait(pub), "delivery count");
// }
// }
// [Test]
// public void TestMultipleSubscribersGetMessage()
// {
// using (var listenA = Config.GetSubscriberConnection())
// using (var listenB = Config.GetSubscriberConnection())
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Wait(conn.Server.Ping());
// int gotA = 0, gotB = 0;
// var tA = listenA.Subscribe("channel", (s, msg) => { if (Encoding.UTF8.GetString(msg) == "message") Interlocked.Increment(ref gotA); });
// var tB = listenB.Subscribe("channel", (s, msg) => { if (Encoding.UTF8.GetString(msg) == "message") Interlocked.Increment(ref gotB); });
// listenA.Wait(tA);
// listenB.Wait(tB);
// Assert.AreEqual(2, conn.Wait(conn.Publish("channel", "message")));
// AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(1, Interlocked.CompareExchange(ref gotA, 0, 0));
// Assert.AreEqual(1, Interlocked.CompareExchange(ref gotB, 0, 0));
// // and unsubscibe...
// tA = listenA.Unsubscribe("channel");
// listenA.Wait(tA);
// Assert.AreEqual(1, conn.Wait(conn.Publish("channel", "message")));
// AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(1, Interlocked.CompareExchange(ref gotA, 0, 0));
// Assert.AreEqual(2, Interlocked.CompareExchange(ref gotB, 0, 0));
// }
// }
// [Test]
// public void Issue38()
// { // https://code.google.com/p/booksleeve/issues/detail?id=38
// using (var pub = Config.GetUnsecuredConnection(waitForOpen: true))
// using (var sub = pub.GetOpenSubscriberChannel())
// {
// int count = 0;
// Action<string, byte[]> handler = (channel, payload) => Interlocked.Increment(ref count);
// var a = sub.Subscribe(new string[] { "foo", "bar" }, handler);
// var b = sub.PatternSubscribe(new string[] { "f*o", "b*r" }, handler);
// sub.WaitAll(a, b);
// var c = pub.Publish("foo", "foo");
// var d = pub.Publish("f@o", "f@o");
// var e = pub.Publish("bar", "bar");
// var f = pub.Publish("b@r", "b@r");
// pub.WaitAll(c, d, e, f);
// long total = c.Result + d.Result + e.Result + f.Result;
// AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(6, total, "sent");
// Assert.AreEqual(6, Interlocked.CompareExchange(ref count, 0, 0), "received");
// }
// }
// internal static void AllowReasonableTimeToPublishAndProcess()
// {
// Thread.Sleep(50);
// }
// [Test]
// public void TestPartialSubscriberGetMessage()
// {
// using (var listenA = Config.GetSubscriberConnection())
// using (var listenB = Config.GetSubscriberConnection())
// using (var conn = Config.GetUnsecuredConnection())
// {
// int gotA = 0, gotB = 0;
// var tA = listenA.Subscribe("channel", (s, msg) => { if (s == "channel" && Encoding.UTF8.GetString(msg) == "message") Interlocked.Increment(ref gotA); });
// var tB = listenB.PatternSubscribe("chann*", (s, msg) => { if (s == "channel" && Encoding.UTF8.GetString(msg) == "message") Interlocked.Increment(ref gotB); });
// listenA.Wait(tA);
// listenB.Wait(tB);
// Assert.AreEqual(2, conn.Wait(conn.Publish("channel", "message")));
// AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(1, Interlocked.CompareExchange(ref gotA, 0, 0));
// Assert.AreEqual(1, Interlocked.CompareExchange(ref gotB, 0, 0));
// // and unsubscibe...
// tB = listenB.PatternUnsubscribe("chann*");
// listenB.Wait(tB);
// Assert.AreEqual(1, conn.Wait(conn.Publish("channel", "message")));
// AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(2, Interlocked.CompareExchange(ref gotA, 0, 0));
// Assert.AreEqual(1, Interlocked.CompareExchange(ref gotB, 0, 0));
// }
// }
// [Test]
// public void TestSubscribeUnsubscribeAndSubscribeAgain()
// {
// using (var pub = Config.GetUnsecuredConnection())
// using (var sub = Config.GetSubscriberConnection())
// {
// int x = 0, y = 0;
// var t1 = sub.Subscribe("abc", delegate { Interlocked.Increment(ref x); });
// var t2 = sub.PatternSubscribe("ab*", delegate { Interlocked.Increment(ref y); });
// sub.WaitAll(t1, t2);
// pub.Publish("abc", "");
// AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(1, Thread.VolatileRead(ref x));
// Assert.AreEqual(1, Thread.VolatileRead(ref y));
// t1 = sub.Unsubscribe("abc");
// t2 = sub.PatternUnsubscribe("ab*");
// sub.WaitAll(t1, t2);
// pub.Publish("abc", "");
// Assert.AreEqual(1, Thread.VolatileRead(ref x));
// Assert.AreEqual(1, Thread.VolatileRead(ref y));
// t1 = sub.Subscribe("abc", delegate { Interlocked.Increment(ref x); });
// t2 = sub.PatternSubscribe("ab*", delegate { Interlocked.Increment(ref y); });
// sub.WaitAll(t1, t2);
// pub.Publish("abc", "");
// AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(2, Thread.VolatileRead(ref x));
// Assert.AreEqual(2, Thread.VolatileRead(ref y));
// }
// }
// }
//}
//using BookSleeve;
//using NUnit.Framework;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//namespace Tests
//{
// [TestFixture]
// public class Scripting
// {
// static RedisConnection GetScriptConn(bool allowAdmin = false)
// {
// var conn = Config.GetUnsecuredConnection(waitForOpen: true, allowAdmin: allowAdmin);
// if (!conn.Features.Scripting)
// {
// Assert.Inconclusive("The server does not support scripting");
// }
// return conn;
// }
// [Test]
// public void ClientScripting()
// {
// using (var conn = GetScriptConn())
// {
// var result = conn.Wait(conn.Scripting.Eval(0, "return redis.call('info','server')", null, null));
// }
// }
// [Test]
// public void BasicScripting()
// {
// using (var conn = GetScriptConn())
// {
// var noCache = conn.Scripting.Eval(0, "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
// new[] { "key1", "key2" }, new[] { "first", "second" }, useCache: false);
// var cache = conn.Scripting.Eval(0, "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
// new[] { "key1", "key2" }, new[] { "first", "second" }, useCache: true);
// var results = (object[])conn.Wait(noCache);
// Assert.AreEqual(4, results.Length);
// Assert.AreEqual("key1", results[0]);
// Assert.AreEqual("key2", results[1]);
// Assert.AreEqual("first", results[2]);
// Assert.AreEqual("second", results[3]);
// results = (object[])conn.Wait(cache);
// Assert.AreEqual(4, results.Length);
// Assert.AreEqual("key1", results[0]);
// Assert.AreEqual("key2", results[1]);
// Assert.AreEqual("first", results[2]);
// Assert.AreEqual("second", results[3]);
// }
// }
// [Test]
// public void KeysScripting()
// {
// using (var conn = GetScriptConn())
// {
// conn.Strings.Set(0, "foo", "bar");
// var result = (string)conn.Wait(conn.Scripting.Eval(0, "return redis.call('get', KEYS[1])", new[] { "foo" }, null));
// Assert.AreEqual("bar", result);
// }
// }
// [Test]
// public void TestRandomThingFromForum()
// {
// const string script = @"local currentVal = tonumber(redis.call('GET', KEYS[1]));
// if (currentVal <= 0 ) then return 1 elseif (currentVal - (tonumber(ARGV[1])) < 0 ) then return 0 end;
// return redis.call('INCRBY', KEYS[1], -tonumber(ARGV[1]));";
// using (var conn = GetScriptConn())
// {
// conn.Strings.Set(0, "A", "0");
// conn.Strings.Set(0, "B", "5");
// conn.Strings.Set(0, "C", "10");
// var a = conn.Scripting.Eval(0, script, new[] { "A" }, new object[] { 6 });
// var b = conn.Scripting.Eval(0, script, new[] { "B" }, new object[] { 6 });
// var c = conn.Scripting.Eval(0, script, new[] { "C" }, new object[] { 6 });
// var vals = conn.Strings.GetString(0, new[] { "A", "B", "C" });
// Assert.AreEqual(1, conn.Wait(a)); // exit code when current val is non-positive
// Assert.AreEqual(0, conn.Wait(b)); // exit code when result would be negative
// Assert.AreEqual(4, conn.Wait(c)); // 10 - 6 = 4
// Assert.AreEqual("0", conn.Wait(vals)[0]);
// Assert.AreEqual("5", conn.Wait(vals)[1]);
// Assert.AreEqual("4", conn.Wait(vals)[2]);
// }
// }
// [Test]
// public void HackyGetPerf()
// {
// using (var conn = GetScriptConn())
// {
// conn.Strings.Set(0, "foo", "bar");
// var key = Config.CreateUniqueName();
// var result = (long)conn.Wait(conn.Scripting.Eval(0, @"
//redis.call('psetex', KEYS[1], 60000, 'timing')
//for i = 1,100000 do
// redis.call('set', 'ignore','abc')
//end
//local timeTaken = 60000 - redis.call('pttl', KEYS[1])
//redis.call('del', KEYS[1])
//return timeTaken
//", new[] { key }, null));
// Console.WriteLine(result);
// Assert.IsTrue(result > 0);
// }
// }
// [Test]
// public void MultiIncrWithoutReplies()
// {
// using (var conn = GetScriptConn())
// {
// const int DB = 0; // any database number
// // prime some initial values
// conn.Keys.Remove(DB, new[] { "a", "b", "c" });
// conn.Strings.Increment(DB, "b");
// conn.Strings.Increment(DB, "c");
// conn.Strings.Increment(DB, "c");
// // run the script, passing "a", "b", "c", "c" to
// // increment a & b by 1, c twice
// var result = conn.Scripting.Eval(DB,
// @"for i,key in ipairs(KEYS) do redis.call('incr', key) end",
// new[] { "a", "b", "c", "c" }, // <== aka "KEYS" in the script
// null); // <== aka "ARGV" in the script
// // check the incremented values
// var a = conn.Strings.GetInt64(DB, "a");
// var b = conn.Strings.GetInt64(DB, "b");
// var c = conn.Strings.GetInt64(DB, "c");
// Assert.IsNull(conn.Wait(result), "result");
// Assert.AreEqual(1, conn.Wait(a), "a");
// Assert.AreEqual(2, conn.Wait(b), "b");
// Assert.AreEqual(4, conn.Wait(c), "c");
// }
// }
// [Test]
// public void MultiIncrByWithoutReplies()
// {
// using (var conn = GetScriptConn())
// {
// const int DB = 0; // any database number
// // prime some initial values
// conn.Keys.Remove(DB, new[] { "a", "b", "c" });
// conn.Strings.Increment(DB, "b");
// conn.Strings.Increment(DB, "c");
// conn.Strings.Increment(DB, "c");
// // run the script, passing "a", "b", "c" and 1,2,3
// // increment a & b by 1, c twice
// var result = conn.Scripting.Eval(DB,
// @"for i,key in ipairs(KEYS) do redis.call('incrby', key, ARGV[i]) end",
// new[] { "a", "b", "c" }, // <== aka "KEYS" in the script
// new object[] {1,1,2}); // <== aka "ARGV" in the script
// // check the incremented values
// var a = conn.Strings.GetInt64(DB, "a");
// var b = conn.Strings.GetInt64(DB, "b");
// var c = conn.Strings.GetInt64(DB, "c");
// Assert.IsNull(conn.Wait(result), "result");
// Assert.AreEqual(1, conn.Wait(a), "a");
// Assert.AreEqual(2, conn.Wait(b), "b");
// Assert.AreEqual(4, conn.Wait(c), "c");
// }
// }
// [Test]
// public void DisableStringInference()
// {
// using (var conn = GetScriptConn())
// {
// conn.Strings.Set(0, "foo", "bar");
// var result = (byte[])conn.Wait(conn.Scripting.Eval(0, "return redis.call('get', KEYS[1])", new[] { "foo" }, null, inferStrings: false));
// Assert.AreEqual("bar", Encoding.UTF8.GetString(result));
// }
// }
// [Test]
// public void FlushDetection()
// { // we don't expect this to handle everything; we just expect it to be predictable
// using (var conn = GetScriptConn(allowAdmin: true))
// {
// conn.Strings.Set(0, "foo", "bar");
// var result = conn.Wait(conn.Scripting.Eval(0, "return redis.call('get', KEYS[1])", new[] { "foo" }, null));
// Assert.AreEqual("bar", result);
// // now cause all kinds of problems
// conn.Server.FlushScriptCache();
// // expect this one to fail
// try {
// conn.Wait(conn.Scripting.Eval(0, "return redis.call('get', KEYS[1])", new[] { "foo" }, null));
// Assert.Fail("Shouldn't have got here");
// }
// catch (RedisException) { }
// catch { Assert.Fail("Expected RedisException"); }
// result = conn.Wait(conn.Scripting.Eval(0, "return redis.call('get', KEYS[1])", new[] { "foo" }, null));
// Assert.AreEqual("bar", result);
// }
// }
// [Test]
// public void PrepareScript()
// {
// string[] scripts = { "return redis.call('get', KEYS[1])", "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" };
// using (var conn = GetScriptConn(allowAdmin: true))
// {
// conn.Server.FlushScriptCache();
// // when vanilla
// conn.Wait(conn.Scripting.Prepare(scripts));
// // when known to exist
// conn.Wait(conn.Scripting.Prepare(scripts));
// }
// using (var conn = GetScriptConn())
// {
// // when vanilla
// conn.Wait(conn.Scripting.Prepare(scripts));
// // when known to exist
// conn.Wait(conn.Scripting.Prepare(scripts));
// // when known to exist
// conn.Wait(conn.Scripting.Prepare(scripts));
// }
// }
// [Test]
// public void NonAsciiScripts()
// {
// using (var conn = GetScriptConn())
// {
// const string evil = "return '僕'";
// var task = conn.Scripting.Prepare(evil);
// conn.Wait(task);
// var result = conn.Wait(conn.Scripting.Eval(0, evil, null, null));
// Assert.AreEqual("僕", result);
// }
// }
// [Test, ExpectedException(typeof(RedisException), ExpectedMessage="oops")]
// public void ScriptThrowsError()
// {
// using (var conn = GetScriptConn())
// {
// var result = conn.Scripting.Eval(0, "return redis.error_reply('oops')", null, null);
// conn.Wait(result);
// }
// }
// [Test]
// public void ScriptThrowsErrorInsideTransaction()
// {
// using (var conn = GetScriptConn())
// {
// const int db = 0;
// const string key = "ScriptThrowsErrorInsideTransaction";
// conn.Keys.Remove(db, key);
// var beforeTran = conn.Strings.GetInt64(db, key);
// Assert.IsNull(conn.Wait(beforeTran));
// using (var tran = conn.CreateTransaction())
// {
// var a = tran.Strings.Increment(db, key);
// var b = tran.Scripting.Eval(db, "return redis.error_reply('oops')", null, null);
// var c = tran.Strings.Increment(db, key);
// var complete = tran.Execute();
// Assert.IsTrue(tran.Wait(complete));
// Assert.IsTrue(a.IsCompleted);
// Assert.IsTrue(c.IsCompleted);
// Assert.AreEqual(1L, a.Result);
// Assert.AreEqual(2L, c.Result);
// Assert.IsTrue(b.IsFaulted);
// Assert.AreEqual(1, b.Exception.InnerExceptions.Count);
// var ex = b.Exception.InnerExceptions.Single();
// Assert.IsInstanceOf<RedisException>(ex);
// Assert.AreEqual("oops", ex.Message);
// }
// var afterTran = conn.Strings.GetInt64(db, key);
// Assert.AreEqual(2L, conn.Wait(afterTran));
// }
// }
// [Test]
// public void ChangeDbInScript()
// {
// using (var conn = GetScriptConn())
// {
// conn.Strings.Set(1, "foo", "db 1");
// conn.Strings.Set(2, "foo", "db 2");
// var evalResult = conn.Scripting.Eval(2, @"redis.call('select', 1)
//return redis.call('get','foo')", null, null);
// var getResult = conn.Strings.GetString(2, "foo");
// Assert.AreEqual("db 1", conn.Wait(evalResult));
// // now, our connection thought it was in db 2, but the script changed to db 1
// Assert.AreEqual("db 2", conn.Wait(getResult));
// }
// }
// }
//}
//using System.Linq;
//using BookSleeve;
//using NUnit.Framework;
//using System.Threading;
//using System;
//using System.Threading.Tasks;
//using System.Collections.Generic;
//using System.Diagnostics;
//namespace Tests
//{
// [TestFixture]
// public class Server // http://redis.io/commands#server
// {
// [Test]
// public void TestGetConfigAll()
// {
// using (var db = Config.GetUnsecuredConnection())
// {
// var pairs = db.Wait(db.Server.GetConfig("*"));
// Assert.Greater(1, 0); // I always get double-check which arg is which
// Assert.Greater(pairs.Count, 0);
// }
// }
// [Test]
// public void BGSaveAndLastSave()
// {
// using(var db = Config.GetUnsecuredConnection(allowAdmin: true))
// {
// var oldWhen = db.Server.GetLastSaveTime();
// db.Wait(db.Server.SaveDatabase(foreground: false));
// bool saved = false;
// for(int i = 0; i < 50; i++)
// {
// var newWhen = db.Server.GetLastSaveTime();
// db.Wait(newWhen);
// if(newWhen.Result > oldWhen.Result)
// {
// saved = true;
// break;
// }
// Console.WriteLine("waiting...");
// Thread.Sleep(200);
// }
// Assert.IsTrue(saved);
// }
// }
// [Test]
// [TestCase(true)]
// [TestCase(false)]
// public void Slowlog(bool remote)
// {
// using(var db = remote ? Config.GetRemoteConnection(allowAdmin: true) : Config.GetUnsecuredConnection(allowAdmin: true))
// {
// var oldWhen = db.Wait(db.Server.Time());
// db.Server.FlushAll();
// db.Server.ResetSlowCommands();
// for (int i = 0; i < 100000; i++)
// {
// db.Strings.Set(1, Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// }
// var settings = db.Wait(db.Server.GetConfig("slowlog-*"));
// var count = int.Parse(settings["slowlog-max-len"]);
// var threshold = int.Parse(settings["slowlog-log-slower-than"]);
// var ping = db.Server.Ping();
// Assert.IsTrue(ping.Wait(10000)); // wait until inserted
// db.Server.SaveDatabase(foreground: true);
// var keys = db.Wait(db.Keys.Find(1, "*"));
// var slow = db.Wait(db.Server.GetSlowCommands());
// var slow2 = db.Wait(db.Server.GetSlowCommands(slow.Length)); // different command syntax
// Assert.AreEqual(slow.Length, slow2.Length);
// foreach(var cmd in slow)
// {
// Console.WriteLine(cmd.UniqueId + ": " + cmd.Duration.Milliseconds + "ms; " +
// string.Join(", ", cmd.Arguments), cmd.GetHelpUrl());
// Assert.IsTrue(cmd.Time > oldWhen && cmd.Time < oldWhen.AddMinutes(1));
// }
// Assert.AreEqual(2, slow.Length);
// Assert.AreEqual(2, slow[0].Arguments.Length);
// Assert.AreEqual("KEYS", slow[0].Arguments[0]);
// Assert.AreEqual("*", slow[0].Arguments[1]);
// Assert.AreEqual("http://redis.io/commands/keys", slow[0].GetHelpUrl());
// Assert.AreEqual(1, slow[1].Arguments.Length);
// Assert.AreEqual("SAVE", slow[1].Arguments[0]);
// Assert.AreEqual("http://redis.io/commands/save", slow[1].GetHelpUrl());
// }
// }
// [Test]
// public void TestTime()
// {
// using (var db = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// Assert.IsNotNull(db.Features); // we waited, after all
// if (db.Features.Time)
// {
// var local = DateTime.UtcNow;
// var server = db.Wait(db.Server.Time());
// Assert.True(Math.Abs((local - server).TotalMilliseconds) < 10);
// }
// }
// }
// [Test]
// public void TestTimeWithExplicitVersion()
// {
// using (var db = Config.GetUnsecuredConnection(open: false))
// {
// db.SetServerVersion(new Version("2.6.9"), ServerType.Master);
// db.SetKeepAlive(10);
// Assert.IsNotNull(db.Features, "Features"); // we waited, after all
// Assert.IsTrue(db.Features.ClientName, "ClientName");
// Assert.IsTrue(db.Features.Time, "Time");
// db.Name = "FooFoo";
// db.Wait(db.Open());
// var local = DateTime.UtcNow;
// var server = db.Wait(db.Server.Time());
// Assert.True(Math.Abs((local - server).TotalMilliseconds) < 10, "Latency");
// }
// }
// [Test, ExpectedException(typeof(TimeoutException), ExpectedMessage = "The operation has timed out; the connection is not open")]
// public void TimeoutMessageNotOpened()
// {
// using (var conn = Config.GetUnsecuredConnection(open: false))
// {
// conn.Wait(conn.Strings.Get(0, "abc"));
// }
// }
// [Test, ExpectedException(typeof(TimeoutException), ExpectedMessage = "The operation has timed out.")]
// public void TimeoutMessageNoDetail()
// {
// using (var conn = Config.GetUnsecuredConnection(open: true))
// {
// conn.IncludeDetailInTimeouts = false;
// conn.Keys.Remove(0, "noexist");
// conn.Lists.BlockingRemoveFirst(0, new[] { "noexist" }, 5);
// conn.Wait(conn.Strings.Get(0, "abc"));
// }
// }
// [Test, ExpectedException(typeof(TimeoutException), ExpectedMessage = "The operation has timed out; possibly blocked by: 0: BLPOP \"noexist\" 5")]
// public void TimeoutMessageWithDetail()
// {
// using (var conn = Config.GetUnsecuredConnection(open: true, waitForOpen: true))
// {
// conn.IncludeDetailInTimeouts = true;
// conn.Keys.Remove(0, "noexist");
// conn.Lists.BlockingRemoveFirst(0, new[] { "noexist" }, 5);
// conn.Wait(conn.Strings.Get(0, "abc"));
// }
// }
// [Test]
// public void ClientList()
// {
// using (var killMe = Config.GetUnsecuredConnection())
// using (var conn = Config.GetUnsecuredConnection(allowAdmin: true))
// {
// killMe.Wait(killMe.Strings.GetString(7, "kill me quick"));
// var clients = conn.Wait(conn.Server.ListClients());
// var target = clients.Single(x => x.Database == 7);
// conn.Wait(conn.Server.KillClient(target.Address));
// Assert.IsTrue(clients.Length > 0);
// try
// {
// killMe.Wait(killMe.Strings.GetString(7, "kill me quick"));
// Assert.Fail("Should have been dead");
// }
// catch (Exception) { }
// }
// }
// [Test]
// public void HappilyMurderedClientDoesntGetError()
// {
// using (var victim = Config.GetUnsecuredConnection(waitForOpen: true))
// using (var murderer = Config.GetUnsecuredConnection(allowAdmin: true))
// {
// const int VictimDB = 4;
// victim.Wait(victim.Strings.GetString(VictimDB, "kill me quick"));
// victim.CompletionMode = ResultCompletionMode.PreserveOrder;
// var clients = murderer.Wait(murderer.Server.ListClients());
// var target = clients.Single(x => x.Database == VictimDB);
// int i = 0;
// victim.Closed += (s, a) =>
// {
// Interlocked.Increment(ref i);
// };
// var errors = new List<Exception>();
// victim.Shutdown += (s, a) =>
// {
// if (a.Exception != null)
// {
// lock (errors)
// {
// errors.Add(a.Exception);
// }
// }
// };
// victim.Error += (s, a) =>
// {
// lock (errors)
// {
// errors.Add(a.Exception);
// }
// };
// victim.Wait(victim.Server.Ping());
// murderer.Wait(murderer.Server.KillClient(target.Address));
// PubSub.AllowReasonableTimeToPublishAndProcess();
// Assert.AreEqual(1, Interlocked.CompareExchange(ref i, 0, 0));
// lock(errors)
// {
// foreach (var err in errors) Console.WriteLine(err.Message);
// Assert.AreEqual(0, errors.Count);
// }
// Assert.AreEqual(ShutdownType.ServerClosed, victim.ShutdownType);
// }
// }
// [Test]
// public void MurderedClientKnowsAboutIt()
// {
// using (var victim = Config.GetUnsecuredConnection(waitForOpen: true))
// using (var murderer = Config.GetUnsecuredConnection(allowAdmin: true))
// {
// const int VictimDB = 3;
// victim.Wait(victim.Strings.GetString(VictimDB, "kill me quick"));
// victim.CompletionMode = ResultCompletionMode.PreserveOrder;
// var clients = murderer.Wait(murderer.Server.ListClients());
// var target = clients.Single(x => x.Database == VictimDB);
// object sync = new object();
// ErrorEventArgs args = null;
// Exception ex = null;
// ManualResetEvent shutdownGate = new ManualResetEvent(false),
// exGate = new ManualResetEvent(false);
// victim.Shutdown += (s,a) =>
// {
// Console.WriteLine("shutdown");
// Interlocked.Exchange(ref args, a);
// shutdownGate.Set();
// };
// lock (sync)
// {
// ThreadPool.QueueUserWorkItem(x =>
// {
// try
// {
// for (int i = 0; i < 50000; i++)
// {
// if (i == 5) lock (sync) { Monitor.PulseAll(sync); }
// victim.Wait(victim.Strings.Set(VictimDB, "foo", "foo"));
// }
// }
// catch(Exception ex2)
// {
// Console.WriteLine("ex");
// Interlocked.Exchange(ref ex, ex2);
// exGate.Set();
// }
// }, null);
// // want the other thread to be running
// Monitor.Wait(sync);
// Console.WriteLine("got pulse; victim is ready");
// }
// Console.WriteLine("killing " + target.Address);
// murderer.Wait(murderer.Server.KillClient(target.Address));
// Console.WriteLine("waiting on gates...");
// Assert.IsTrue(shutdownGate.WaitOne(10000), "shutdown gate");
// Assert.IsTrue(exGate.WaitOne(10000), "exception gate");
// Console.WriteLine("gates passed");
// Assert.AreEqual(ShutdownType.ServerClosed, victim.ShutdownType);
// var args_final = Interlocked.Exchange(ref args, null);
// var ex_final = Interlocked.Exchange(ref ex, null);
// Assert.IsNotNull(ex_final, "ex");
// Assert.IsNotNull(args_final, "args");
// }
// }
// [Test]
// public void CleanCloseKnowsReason()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.Wait(conn.Server.Ping());
// conn.Close(false);
// Assert.AreEqual(ShutdownType.ClientClosed, conn.ShutdownType);
// }
// }
// [Test]
// public void DisposeKnowsReason()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.Wait(conn.Server.Ping());
// conn.Dispose();
// Assert.AreEqual(ShutdownType.ClientDisposed, conn.ShutdownType);
// }
// }
// [Test]
// public void TestLastSentCounter()
// {
// using (var db = Config.GetUnsecuredConnection(open: false))
// {
// db.SetServerVersion(new Version("2.6.0"), ServerType.Master);
// db.SetKeepAlive(0); // turn off keep-alives so we don't get unexpected pings
// db.Wait(db.Open());
// db.Wait(db.Server.Ping());
// var first = db.GetCounters(false);
// Assert.LessOrEqual(0, 1, "0 <= 1");
// Assert.LessOrEqual(first.LastSentMillisecondsAgo, 100, "first");
// Thread.Sleep(2000);
// var second = db.GetCounters(false);
// Assert.GreaterOrEqual(1, 0, "1 >= 0");
// Assert.GreaterOrEqual(second.LastSentMillisecondsAgo, 1900, "second");
// Assert.LessOrEqual(second.LastSentMillisecondsAgo, 2100, "second");
// db.Wait(db.Server.Ping());
// var third = db.GetCounters(false);
// Assert.LessOrEqual(0, 1, "0 <= 1");
// Assert.LessOrEqual(third.LastSentMillisecondsAgo, 100, "third");
// }
// }
// [Test]
// public void TestKeepAlive()
// {
// string oldValue = null;
// try
// {
// using (var db = Config.GetUnsecuredConnection(allowAdmin: true))
// {
// oldValue = db.Wait(db.Server.GetConfig("timeout")).Single().Value;
// db.Server.SetConfig("timeout", "20");
// }
// using (var db = Config.GetUnsecuredConnection(allowAdmin: false, waitForOpen:true))
// {
// var before = db.GetCounters(false);
// Assert.AreEqual(4, before.KeepAliveSeconds, "keep-alive");
// Thread.Sleep(13 * 1000);
// var after = db.GetCounters(false);
// // 3 here is 2 * keep-alive, and one PING in GetCounters()
// int sent = after.MessagesSent - before.MessagesSent;
// Assert.GreaterOrEqual(1, 0);
// Assert.GreaterOrEqual(sent, 3);
// Assert.LessOrEqual(0, 4);
// Assert.LessOrEqual(sent, 4);
// }
// }
// finally
// {
// if (oldValue != null)
// {
// Task t;
// using (var db = Config.GetUnsecuredConnection(allowAdmin: true))
// {
// t = db.Server.SetConfig("timeout", oldValue);
// }
// Assert.IsTrue(t.Wait(5000));
// if (t.Exception != null) throw t.Exception;
// }
// }
// }
// [Test, ActiveTest]
// public void SetValueWhileDisposing()
// {
// const int LOOP = 10;
// for (int i = 0; i < LOOP; i++)
// {
// var guid = Config.CreateUniqueName();
// Task t1, t3;
// Task<string> t2;
// string key = "SetValueWhileDisposing:" + i;
// using (var db = Config.GetUnsecuredConnection(open: true))
// {
// t1 = db.Strings.Set(0, key, guid);
// }
// Assert.IsTrue(t1.Wait(500));
// using (var db = Config.GetUnsecuredConnection())
// {
// t2 = db.Strings.GetString(0, key);
// t3 = db.Keys.Remove(0, key);
// }
// Assert.IsTrue(t2.Wait(500));
// Assert.AreEqual(guid, t2.Result);
// Assert.IsTrue(t3.Wait(500));
// }
// }
// [Test]
// public void TestMasterSlaveSetup()
// {
// using (var unsec = Config.GetUnsecuredConnection(true, true, true))
// using (var sec = Config.GetUnsecuredConnection(true, true, true))
// {
// try
// {
// var makeSlave = sec.Server.MakeSlave(unsec.Host, unsec.Port);
// var info = sec.Wait(sec.Server.GetInfo());
// sec.Wait(makeSlave);
// Assert.AreEqual("slave", info["role"], "slave");
// Assert.AreEqual(unsec.Host, info["master_host"], "host");
// Assert.AreEqual(unsec.Port.ToString(), info["master_port"], "port");
// var makeMaster = sec.Server.MakeMaster();
// info = sec.Wait(sec.Server.GetInfo());
// sec.Wait(makeMaster);
// Assert.AreEqual("master", info["role"], "master");
// }
// finally
// {
// sec.Server.MakeMaster();
// }
// }
// }
// }
//}
//using System;
//using NUnit.Framework;
//using System.Text;
//using System.Linq;
//namespace Tests
//{
// [TestFixture]
// public class Sets // http://redis.io/commands#set
// {
// [Test]
// public void AddSingle()
// {
// using(var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// var r0 = conn.Sets.Add(3, "set", "abc");
// var r1 = conn.Sets.Add(3, "set", "abc");
// var len = conn.Sets.GetLength(3, "set");
// Assert.AreEqual(true, r0.Result);
// Assert.AreEqual(false, r1.Result);
// Assert.AreEqual(1, len.Result);
// }
// }
// [Test]
// public void Scan()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// if (!conn.Features.Scan) Assert.Inconclusive();
// const int db = 3;
// const string key = "set-scan";
// conn.Keys.Remove(db, key);
// conn.Sets.Add(db, key, "abc");
// conn.Sets.Add(db, key, "def");
// conn.Sets.Add(db, key, "ghi");
// var t1 = conn.Sets.Scan(db, key);
// var t3 = conn.Sets.ScanString(db, key);
// var t4 = conn.Sets.ScanString(db, key, "*h*");
// var v1 = t1.ToArray();
// var v3 = t3.ToArray();
// var v4 = t4.ToArray();
// Assert.AreEqual(3, v1.Length);
// Assert.AreEqual(3, v3.Length);
// Assert.AreEqual(1, v4.Length);
// Array.Sort(v1, (x, y) => string.Compare(Encoding.UTF8.GetString(x), Encoding.UTF8.GetString(y)));
// Array.Sort(v3);
// Array.Sort(v4);
// Assert.AreEqual("abc,def,ghi", string.Join(",", v1.Select(x => Encoding.UTF8.GetString(x))));
// Assert.AreEqual("abc,def,ghi", string.Join(",", v3));
// Assert.AreEqual("ghi", string.Join(",", v4));
// }
// }
// [Test]
// public void AddSingleBinary()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// var r0 = conn.Sets.Add(3, "set", Encode("abc"));
// var r1 = conn.Sets.Add(3, "set", Encode("abc"));
// var len = conn.Sets.GetLength(3, "set");
// Assert.AreEqual(true, r0.Result);
// Assert.AreEqual(false, r1.Result);
// Assert.AreEqual(1, len.Result);
// }
// }
// static byte[] Encode(string value) { return Encoding.UTF8.GetBytes(value); }
// static string Decode(byte[] value) { return Encoding.UTF8.GetString(value); }
// [Test]
// public void RemoveSingle()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// conn.Sets.Add(3, "set", "abc");
// conn.Sets.Add(3, "set", "def");
// var r0 = conn.Sets.Remove(3, "set", "abc");
// var r1 = conn.Sets.Remove(3, "set", "abc");
// var len = conn.Sets.GetLength(3, "set");
// Assert.AreEqual(true, r0.Result);
// Assert.AreEqual(false, r1.Result);
// Assert.AreEqual(1, len.Result);
// }
// }
// [Test]
// public void RemoveSingleBinary()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// conn.Sets.Add(3, "set", Encode("abc"));
// conn.Sets.Add(3, "set", Encode("def"));
// var r0 = conn.Sets.Remove(3, "set", Encode("abc"));
// var r1 = conn.Sets.Remove(3, "set", Encode("abc"));
// var len = conn.Sets.GetLength(3, "set");
// Assert.AreEqual(true, r0.Result);
// Assert.AreEqual(false, r1.Result);
// Assert.AreEqual(1, len.Result);
// }
// }
// [Test]
// public void AddMulti()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.Keys.Remove(3, "set");
// var r0 = conn.Sets.Add(3, "set", "abc");
// var r1 = conn.Sets.Add(3, "set", new[] {"abc", "def"});
// var len = conn.Sets.GetLength(3, "set");
// Assert.AreEqual(true, r0.Result);
// Assert.AreEqual(1, r1.Result);
// Assert.AreEqual(2, len.Result);
// }
// }
// [Test]
// public void RemoveMulti()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.Keys.Remove(3, "set");
// conn.Sets.Add(3, "set", "abc");
// conn.Sets.Add(3, "set", "ghi");
// var r0 = conn.Sets.Remove(3, "set", new[] {"abc", "def"});
// var len = conn.Sets.GetLength(3, "set");
// Assert.AreEqual(1, r0.Result);
// Assert.AreEqual(1, len.Result);
// }
// }
// [Test]
// public void AddMultiBinary()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen:true))
// {
// conn.Keys.Remove(3, "set");
// var r0 = conn.Sets.Add(3, "set", Encode("abc"));
// var r1 = conn.Sets.Add(3, "set", new[] { Encode("abc"), Encode("def") });
// var len = conn.Sets.GetLength(3, "set");
// Assert.AreEqual(true, r0.Result);
// Assert.AreEqual(1, r1.Result);
// Assert.AreEqual(2, len.Result);
// }
// }
// [Test]
// public void RemoveMultiBinary()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.Keys.Remove(3, "set");
// conn.Sets.Add(3, "set", Encode("abc"));
// conn.Sets.Add(3, "set", Encode("ghi"));
// var r0 = conn.Sets.Remove(3, "set", new[] { Encode("abc"), Encode("def") });
// var len = conn.Sets.GetLength(3, "set");
// Assert.AreEqual(1, r0.Result);
// Assert.AreEqual(1, len.Result);
// }
// }
// [Test]
// public void Exists()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// var r0 = conn.Sets.Contains(3, "set", "def");
// conn.Sets.Add(3, "set", "abc");
// var r1 = conn.Sets.Contains(3, "set", "def");
// conn.Sets.Add(3, "set", "def");
// var r2 = conn.Sets.Contains(3, "set", "def");
// conn.Sets.Remove(3, "set", "def");
// var r3 = conn.Sets.Contains(3, "set", "def");
// Assert.AreEqual(false, r0.Result);
// Assert.AreEqual(false, r1.Result);
// Assert.AreEqual(true, r2.Result);
// Assert.AreEqual(false, r3.Result);
// }
// }
// [Test]
// public void ExistsBinary()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// var r0 = conn.Sets.Contains(3, "set", Encode("def"));
// conn.Sets.Add(3, "set", "abc");
// var r1 = conn.Sets.Contains(3, "set", Encode("def"));
// conn.Sets.Add(3, "set", "def");
// var r2 = conn.Sets.Contains(3, "set", Encode("def"));
// conn.Sets.Remove(3, "set", "def");
// var r3 = conn.Sets.Contains(3, "set", Encode("def"));
// Assert.AreEqual(false, r0.Result);
// Assert.AreEqual(false, r1.Result);
// Assert.AreEqual(true, r2.Result);
// Assert.AreEqual(false, r3.Result);
// }
// }
// [Test]
// public void GetRandom()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// Assert.IsNull(conn.Sets.GetRandomString(3, "set").Result);
// Assert.IsNull(conn.Sets.GetRandom(3, "set").Result);
// conn.Sets.Add(3, "set", "abc");
// Assert.AreEqual("abc", conn.Sets.GetRandomString(3, "set").Result);
// Assert.AreEqual("abc", Decode(conn.Sets.GetRandom(3, "set").Result));
// conn.Sets.Add(3, "set", Encode("def"));
// var result = conn.Sets.GetRandomString(3, "set").Result;
// Assert.IsTrue(result == "abc" || result == "def");
// result = Decode(conn.Sets.GetRandom(3, "set").Result);
// Assert.IsTrue(result == "abc" || result == "def");
// }
// }
// [Test]
// public void GetRandomMulti()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// if (conn.Features.MultipleRandom)
// {
// conn.Keys.Remove(3, "set");
// Assert.AreEqual(0, conn.Sets.GetRandomString(3, "set", 2).Result.Length);
// Assert.AreEqual(0, conn.Sets.GetRandom(3, "set", 2).Result.Length);
// conn.Sets.Add(3, "set", "abc");
// var a1 = conn.Sets.GetRandomString(3, "set", 2).Result;
// var a2 = conn.Sets.GetRandom(3, "set", 2).Result;
// Assert.AreEqual(1, a1.Length);
// Assert.AreEqual(1, a2.Length);
// Assert.AreEqual("abc", a1[0]);
// Assert.AreEqual("abc", Decode(a2[0]));
// conn.Sets.Add(3, "set", Encode("def"));
// var a3 = conn.Sets.GetRandomString(3, "set", 3).Result;
// var a4 = Array.ConvertAll(conn.Sets.GetRandom(3, "set", 3).Result, Decode);
// Assert.AreEqual(2, a3.Length);
// Assert.AreEqual(2, a4.Length);
// Assert.Contains("abc", a3);
// Assert.Contains("def", a3);
// Assert.Contains("abc", a4);
// Assert.Contains("def", a4);
// var a5 = conn.Sets.GetRandomString(3, "set", -3).Result;
// var a6 = Array.ConvertAll(conn.Sets.GetRandom(3, "set", -3).Result, Decode);
// Assert.AreEqual(3, a5.Length);
// Assert.AreEqual(3, a6.Length);
// Assert.IsTrue(a5.All(x => x == "abc" || x == "def"));
// Assert.IsTrue(a6.All(x => x == "abc" || x == "def"));
// }
// }
// }
// [Test]
// public void RemoveRandom()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// Assert.IsNull(conn.Sets.RemoveRandomString(3, "set").Result);
// Assert.IsNull(conn.Sets.RemoveRandom(3, "set").Result);
// conn.Sets.Add(3, "set", "abc");
// Assert.AreEqual("abc", conn.Sets.RemoveRandomString(3, "set").Result);
// Assert.AreEqual(0, conn.Sets.GetLength(3, "set").Result);
// conn.Sets.Add(3, "set", "abc");
// Assert.AreEqual("abc", Decode(conn.Sets.RemoveRandom(3, "set").Result));
// Assert.AreEqual(0, conn.Sets.GetLength(3, "set").Result);
// conn.Sets.Add(3, "set", "abc");
// conn.Sets.Add(3, "set", Encode("def"));
// var result1 = conn.Sets.RemoveRandomString(3, "set").Result;
// var result2 = Decode(conn.Sets.RemoveRandom(3, "set").Result);
// Assert.AreEqual(0, conn.Sets.GetLength(3, "set").Result);
// Assert.AreNotEqual(result1, result2);
// Assert.IsTrue(result1 == "abc" || result1 == "def");
// Assert.IsTrue(result2 == "abc" || result2 == "def");
// }
// }
// [Test]
// public void GetAll()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "set");
// var b0 = conn.Sets.GetAll(3, "set");
// var s0 = conn.Sets.GetAllString(3, "set");
// conn.Sets.Add(3, "set", "abc");
// conn.Sets.Add(3, "set", "def");
// var b1 = conn.Sets.GetAll(3, "set");
// var s1 = conn.Sets.GetAllString(3, "set");
// Assert.AreEqual(0, conn.Wait(b0).Length);
// Assert.AreEqual(0, conn.Wait(s0).Length);
// // check strings
// var s = conn.Wait(s1);
// Assert.AreEqual(2, s.Length);
// Array.Sort(s);
// Assert.AreEqual("abc", s[0]);
// Assert.AreEqual("def", s[1]);
// // check binary
// s = Array.ConvertAll(conn.Wait(b1), Decode);
// Assert.AreEqual(2, s.Length);
// Array.Sort(s);
// Assert.AreEqual("abc", s[0]);
// Assert.AreEqual("def", s[1]);
// }
// }
// [Test]
// public void Move()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "from");
// conn.Keys.Remove(3, "to");
// conn.Sets.Add(3, "from", "abc");
// conn.Sets.Add(3, "from", "def");
// Assert.AreEqual(2, conn.Sets.GetLength(3, "from").Result);
// Assert.AreEqual(0, conn.Sets.GetLength(3, "to").Result);
// Assert.IsFalse(conn.Sets.Move(3, "from", "to", "nix").Result);
// Assert.IsFalse(conn.Sets.Move(3, "from", "to", Encode("nix")).Result);
// Assert.IsTrue(conn.Sets.Move(3, "from", "to", "abc").Result);
// Assert.IsTrue(conn.Sets.Move(3, "from", "to", Encode("def")).Result);
// Assert.AreEqual(0, conn.Sets.GetLength(3, "from").Result);
// Assert.AreEqual(2, conn.Sets.GetLength(3, "to").Result);
// }
// }
// [Test]
// public void Diff()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "key1");
// conn.Keys.Remove(3, "key2");
// conn.Keys.Remove(3, "key3");
// conn.Keys.Remove(3, "to");
// conn.Sets.Add(3, "key1", "a");
// conn.Sets.Add(3, "key1", "b");
// conn.Sets.Add(3, "key1", "c");
// conn.Sets.Add(3, "key1", "d");
// conn.Sets.Add(3, "key2", "c");
// conn.Sets.Add(3, "key3", "a");
// conn.Sets.Add(3, "key3", "c");
// conn.Sets.Add(3, "key3", "e");
// var diff1 = conn.Sets.Difference(3, new[] {"key1", "key2", "key3"});
// var diff2 = conn.Sets.DifferenceString(3, new[] { "key1", "key2", "key3" });
// var len = conn.Sets.DifferenceAndStore(3, "to", new[] { "key1", "key2", "key3" });
// var diff3 = conn.Sets.GetAllString(3, "to");
// var s = Array.ConvertAll(conn.Wait(diff1), Decode);
// Assert.AreEqual(2, s.Length);
// Array.Sort(s);
// Assert.AreEqual("b", s[0]);
// Assert.AreEqual("d", s[1]);
// s = conn.Wait(diff2);
// Assert.AreEqual(2, s.Length);
// Array.Sort(s);
// Assert.AreEqual("b", s[0]);
// Assert.AreEqual("d", s[1]);
// Assert.AreEqual(2, conn.Wait(len));
// s = conn.Wait(diff3);
// Assert.AreEqual(2, s.Length);
// Array.Sort(s);
// Assert.AreEqual("b", s[0]);
// Assert.AreEqual("d", s[1]);
// }
// }
// [Test]
// public void Intersect()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "key1");
// conn.Keys.Remove(3, "key2");
// conn.Keys.Remove(3, "key3");
// conn.Keys.Remove(3, "to");
// conn.Sets.Add(3, "key1", "a");
// conn.Sets.Add(3, "key1", "b");
// conn.Sets.Add(3, "key1", "c");
// conn.Sets.Add(3, "key1", "d");
// conn.Sets.Add(3, "key2", "c");
// conn.Sets.Add(3, "key3", "a");
// conn.Sets.Add(3, "key3", "c");
// conn.Sets.Add(3, "key3", "e");
// var diff1 = conn.Sets.Intersect(3, new[] { "key1", "key2", "key3" });
// var diff2 = conn.Sets.IntersectString(3, new[] { "key1", "key2", "key3" });
// var len = conn.Sets.IntersectAndStore(3, "to", new[] { "key1", "key2", "key3" });
// var diff3 = conn.Sets.GetAllString(3, "to");
// var s = Array.ConvertAll(conn.Wait(diff1), Decode);
// Assert.AreEqual(1, s.Length);
// Assert.AreEqual("c", s[0]);
// s = conn.Wait(diff2);
// Assert.AreEqual(1, s.Length);
// Assert.AreEqual("c", s[0]);
// Assert.AreEqual(1, conn.Wait(len));
// s = conn.Wait(diff3);
// Assert.AreEqual(1, s.Length);
// Assert.AreEqual("c", s[0]);
// }
// }
// [Test]
// public void Union()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "key1");
// conn.Keys.Remove(3, "key2");
// conn.Keys.Remove(3, "key3");
// conn.Keys.Remove(3, "to");
// conn.Sets.Add(3, "key1", "a");
// conn.Sets.Add(3, "key1", "b");
// conn.Sets.Add(3, "key1", "c");
// conn.Sets.Add(3, "key1", "d");
// conn.Sets.Add(3, "key2", "c");
// conn.Sets.Add(3, "key3", "a");
// conn.Sets.Add(3, "key3", "c");
// conn.Sets.Add(3, "key3", "e");
// var diff1 = conn.Sets.Union(3, new[] { "key1", "key2", "key3" });
// var diff2 = conn.Sets.UnionString(3, new[] { "key1", "key2", "key3" });
// var len = conn.Sets.UnionAndStore(3, "to", new[] { "key1", "key2", "key3" });
// var diff3 = conn.Sets.GetAllString(3, "to");
// var s = Array.ConvertAll(conn.Wait(diff1), Decode);
// Assert.AreEqual(5, s.Length);
// Array.Sort(s);
// Assert.AreEqual("a", s[0]);
// Assert.AreEqual("b", s[1]);
// Assert.AreEqual("c", s[2]);
// Assert.AreEqual("d", s[3]);
// Assert.AreEqual("e", s[4]);
// s = conn.Wait(diff2);
// Assert.AreEqual(5, s.Length);
// Array.Sort(s);
// Assert.AreEqual("a", s[0]);
// Assert.AreEqual("b", s[1]);
// Assert.AreEqual("c", s[2]);
// Assert.AreEqual("d", s[3]);
// Assert.AreEqual("e", s[4]);
// Assert.AreEqual(5, conn.Wait(len));
// s = conn.Wait(diff3);
// Assert.AreEqual(5, s.Length);
// Array.Sort(s);
// Assert.AreEqual("a", s[0]);
// Assert.AreEqual("b", s[1]);
// Assert.AreEqual("c", s[2]);
// Assert.AreEqual("d", s[3]);
// Assert.AreEqual("e", s[4]);
// }
// }
// }
//}
//using System.Linq;
//using NUnit.Framework;
//using System;
//using System.Text;
//using BookSleeve;
//using System.Collections.Generic;
//using System.Threading.Tasks;
//namespace Tests
//{
// [TestFixture]
// public class SortedSets // http://redis.io/commands#sorted_set
// {
// [Test]
// public void SortedTrim()
// {
// using(var conn = Config.GetUnsecuredConnection())
// {
// const int db = 0;
// const string key = "sorted-trim";
// for(int i = 0; i < 200; i++)
// {
// conn.SortedSets.Add(db, key, i.ToString(), i);
// }
// conn.SortedSets.RemoveRange(db, key, 0, -21);
// var count = conn.SortedSets.GetLength(db, key);
// Assert.AreEqual(20, conn.Wait(count));
// }
// }
// [Test]
// public void Scan()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen:true))
// {
// if (!conn.Features.Scan) Assert.Inconclusive();
// const int db = 3;
// const string key = "sorted-set-scan";
// conn.Keys.Remove(db, key);
// conn.SortedSets.Add(db, key, "abc", 1);
// conn.SortedSets.Add(db, key, "def", 2);
// conn.SortedSets.Add(db, key, "ghi", 3);
// var t1 = conn.SortedSets.Scan(db, key);
// var t3 = conn.SortedSets.ScanString(db, key);
// var t4 = conn.SortedSets.ScanString(db, key, "*h*");
// var v1 = t1.ToArray();
// var v3 = t3.ToArray();
// var v4 = t4.ToArray();
// Assert.AreEqual(3, v1.Length);
// Assert.AreEqual(3, v3.Length);
// Assert.AreEqual(1, v4.Length);
// Array.Sort(v1, (x, y) => string.Compare(Encoding.UTF8.GetString(x.Key), Encoding.UTF8.GetString(y.Key)));
// Array.Sort(v3, (x, y) => string.Compare(x.Key, y.Key));
// Array.Sort(v4, (x, y) => string.Compare(x.Key, y.Key));
// Assert.AreEqual("abc=1,def=2,ghi=3", string.Join(",", v1.Select(pair => Encoding.UTF8.GetString(pair.Key) + "=" + pair.Value)));
// Assert.AreEqual("abc=1,def=2,ghi=3", string.Join(",", v3.Select(pair => pair.Key + "=" + pair.Value)));
// Assert.AreEqual("ghi=3", string.Join(",", v4.Select(pair => pair.Key + "=" + pair.Value)));
// }
// }
// [Test]
// public void Range() // http://code.google.com/p/booksleeve/issues/detail?id=12
// {
// using(var conn = Config.GetUnsecuredConnection())
// {
// const double value = 634614442154715;
// conn.SortedSets.Add(3, "zset", "abc", value);
// var range = conn.SortedSets.Range(3, "zset", 0, -1);
// Assert.AreEqual(value, conn.Wait(range).Single().Value);
// }
// }
// [Test]
// public void RangeString() // http://code.google.com/p/booksleeve/issues/detail?id=18
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// const double value = 634614442154715;
// conn.SortedSets.Add(3, "zset", "abc", value);
// var range = conn.SortedSets.RangeString(3, "zset", 0, -1);
// Assert.AreEqual(value, conn.Wait(range).Single().Value);
// }
// }
// [Test]
// public void Score() // http://code.google.com/p/booksleeve/issues/detail?id=23
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(0, "abc");
// conn.SortedSets.Add(0, "abc", "def", 1.0);
// var s1 = conn.SortedSets.Score(0, "abc", "def");
// var s2 = conn.SortedSets.Score(0, "abc", "ghi");
// Assert.AreEqual(1.0, conn.Wait(s1));
// Assert.IsNull(conn.Wait(s2));
// }
// }
// [Test]
// public void Rank() // http://code.google.com/p/booksleeve/issues/detail?id=23
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(0, "abc");
// conn.SortedSets.Add(0, "abc", "def", 1.0);
// conn.SortedSets.Add(0, "abc", "jkl", 2.0);
// var a1 = conn.SortedSets.Rank(0, "abc", "def", ascending: true);
// var a2 = conn.SortedSets.Rank(0, "abc", "ghi", ascending: true);
// var a3 = conn.SortedSets.Rank(0, "abc", "jkl", ascending: true);
// var d1 = conn.SortedSets.Rank(0, "abc", "def", ascending: false);
// var d2 = conn.SortedSets.Rank(0, "abc", "ghi", ascending: false);
// var d3 = conn.SortedSets.Rank(0, "abc", "jkl", ascending: false);
// Assert.AreEqual(0, conn.Wait(a1));
// Assert.IsNull(conn.Wait(a2));
// Assert.AreEqual(1, conn.Wait(a3));
// Assert.AreEqual(1, conn.Wait(d1));
// Assert.IsNull(conn.Wait(d2));
// Assert.AreEqual(0, conn.Wait(d3));
// }
// }
// static string SeedRange(RedisConnection connection, out double min, out double max)
// {
// var rand = new Random(123456);
// const string key = "somerange";
// connection.Keys.Remove(0, key);
// min = max = 0;
// for (int i = 0; i < 50; i++)
// {
// double value = rand.NextDouble();
// if (i == 0)
// {
// min = max = value;
// }
// else
// {
// if (value < min) min = value;
// if (value > max) max= value;
// }
// connection.SortedSets.Add(0, key, "item " + i, value);
// }
// return key;
// }
// [Test]
// public void GetAll()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// double minActual, maxActual;
// string key = SeedRange(conn, out minActual, out maxActual);
// var all = conn.Wait(conn.SortedSets.Range(0, key, 0.0, 1.0));
// Assert.AreEqual(50, all.Length, "all between 0.0 and 1.0");
// var subset = conn.Wait(conn.SortedSets.Range(0, key, 0.0, 1.0, offset: 2, count: 46));
// Assert.AreEqual(46, subset.Length);
// var subVals = new HashSet<double>(subset.Select(x => x.Value));
// Assert.IsFalse(subVals.Contains(all[0].Value));
// Assert.IsFalse(subVals.Contains(all[1].Value));
// Assert.IsFalse(subVals.Contains(all[48].Value));
// Assert.IsFalse(subVals.Contains(all[49].Value));
// for (int i = 2; i < 48; i++)
// {
// Assert.IsTrue(subVals.Contains(all[i].Value));
// }
// }
// }
// [Test]
// public void FindMinMax()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// double minActual, maxActual;
// string key = SeedRange(conn, out minActual, out maxActual);
// var min = conn.SortedSets.Range(0, key, ascending: true, count: 1);
// var max = conn.SortedSets.Range(0, key, ascending: false, count: 1);
// var minScore = conn.Wait(min).Single().Value;
// var maxScore = conn.Wait(max).Single().Value;
// Assert.Less(1, 2); // I *always* get these args the wrong way around
// Assert.Less(Math.Abs(minActual - minScore), 0.0000001, "min");
// Assert.Less(Math.Abs(maxActual - maxScore), 0.0000001, "max");
// }
// }
// [Test]
// public void CheckInfinity()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(0, "infs");
// conn.SortedSets.Add(0, "infs", "neg", double.NegativeInfinity);
// conn.SortedSets.Add(0, "infs", "pos", double.PositiveInfinity);
// conn.SortedSets.Add(0, "infs", "zero", 0.0);
// var pairs = conn.Wait(conn.SortedSets.RangeString(0, "infs", 0, -1));
// Assert.AreEqual(3, pairs.Length);
// Assert.AreEqual("neg", pairs[0].Key);
// Assert.AreEqual("zero", pairs[1].Key);
// Assert.AreEqual("pos", pairs[2].Key);
// Assert.IsTrue(double.IsNegativeInfinity(pairs[0].Value), "-inf");
// Assert.AreEqual(0.0, pairs[1].Value);
// Assert.IsTrue(double.IsPositiveInfinity(pairs[2].Value), "+inf");
// }
// }
// [Test]
// public void UnionAndStore()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "key1");
// conn.Keys.Remove(3, "key2");
// conn.Keys.Remove(3, "to");
// conn.SortedSets.Add(3, "key1", "a", 1);
// conn.SortedSets.Add(3, "key1", "b", 2);
// conn.SortedSets.Add(3, "key1", "c", 3);
// conn.SortedSets.Add(3, "key2", "a", 1);
// conn.SortedSets.Add(3, "key2", "b", 2);
// conn.SortedSets.Add(3, "key2", "c", 3);
// var numberOfElementsT = conn.SortedSets.UnionAndStore(3, "to", new string[] { "key1", "key2" }, BookSleeve.RedisAggregate.Sum);
// var resultSetT = conn.SortedSets.RangeString(3, "to", 0, -1);
// var numberOfElements = conn.Wait(numberOfElementsT);
// Assert.AreEqual(3, numberOfElements);
// var s = conn.Wait(resultSetT);
// Assert.AreEqual("a", s[0].Key);
// Assert.AreEqual("b", s[1].Key);
// Assert.AreEqual("c", s[2].Key);
// Assert.AreEqual(2, s[0].Value);
// Assert.AreEqual(4, s[1].Value);
// Assert.AreEqual(6, s[2].Value);
// }
// }
// [Test]
// public void UnionAndStoreMax()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "key1");
// conn.Keys.Remove(3, "key2");
// conn.Keys.Remove(3, "to");
// conn.SortedSets.Add(3, "key1", "a", 1);
// conn.SortedSets.Add(3, "key1", "b", 2);
// conn.SortedSets.Add(3, "key1", "c", 3);
// conn.SortedSets.Add(3, "key2", "a", 4);
// conn.SortedSets.Add(3, "key2", "b", 5);
// conn.SortedSets.Add(3, "key2", "c", 6);
// var numberOfElementsT = conn.SortedSets.UnionAndStore(3, "to", new string[] { "key1", "key2" }, BookSleeve.RedisAggregate.Max);
// var resultSetT = conn.SortedSets.RangeString(3, "to", 0, -1);
// var numberOfElements = conn.Wait(numberOfElementsT);
// Assert.AreEqual(3, numberOfElements);
// var s = conn.Wait(resultSetT);
// Assert.AreEqual("a", s[0].Key);
// Assert.AreEqual("b", s[1].Key);
// Assert.AreEqual("c", s[2].Key);
// Assert.AreEqual(4, s[0].Value);
// Assert.AreEqual(5, s[1].Value);
// Assert.AreEqual(6, s[2].Value);
// }
// }
// [Test]
// public void UnionAndStoreMin()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(3, "key1");
// conn.Keys.Remove(3, "key2");
// conn.Keys.Remove(3, "to");
// conn.SortedSets.Add(3, "key1", "a", 1);
// conn.SortedSets.Add(3, "key1", "b", 2);
// conn.SortedSets.Add(3, "key1", "c", 3);
// conn.SortedSets.Add(3, "key2", "a", 4);
// conn.SortedSets.Add(3, "key2", "b", 5);
// conn.SortedSets.Add(3, "key2", "c", 6);
// var numberOfElementsT = conn.SortedSets.UnionAndStore(3, "to", new string[] { "key1", "key2" }, BookSleeve.RedisAggregate.Min);
// var resultSetT = conn.SortedSets.RangeString(3, "to", 0, -1);
// var numberOfElements = conn.Wait(numberOfElementsT);
// Assert.AreEqual(3, numberOfElements);
// var s = conn.Wait(resultSetT);
// Assert.AreEqual("a", s[0].Key);
// Assert.AreEqual("b", s[1].Key);
// Assert.AreEqual("c", s[2].Key);
// Assert.AreEqual(1, s[0].Value);
// Assert.AreEqual(2, s[1].Value);
// Assert.AreEqual(3, s[2].Value);
// }
// }
// [Test]
// public void TestZUNIONSTORElimit()
// {
// const int SIZE = 10000;
// using (var conn = Config.GetUnsecuredConnection())
// {
// for (int i = 0; i < SIZE; i++)
// {
// string key = "z_" + i;
// conn.Keys.Remove(0, key);
// for (int j = 0; j < 5; j++)
// conn.SortedSets.Add(0, key, "s" + j.ToString(), j);
// }
// conn.Wait(conn.Server.Ping());
// List<Task> results = new List<Task>(SIZE);
// for (int i = 0; i < SIZE; i+=100)
// {
// string[] keys = Enumerable.Range(0,i+1).Select(x => "z_" + x).ToArray();
// results.Add(conn.SortedSets.UnionAndStore(0, "zu_" + i, keys, RedisAggregate.Max));
// }
// foreach (var task in results)
// conn.WaitAll(task);
// }
// }
// [Test]
// public void SO14991819()
// {
// const int _db = 0;
// const string _thisChannel = "SO14991819";
// string thisChannel = string.Format("urn:{0}", _thisChannel);
// const string message = "hi";
// using (var _connection = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// _connection.Keys.Remove(_db, thisChannel); // start from known state
// TimeSpan span = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0));
// double val = span.TotalSeconds;
// _connection.SortedSets.Add(_db, thisChannel, message, val, false);
// var subset = _connection.Wait(_connection.SortedSets.RangeString(
// _db, thisChannel, span.TotalSeconds - 10000, span.TotalSeconds, offset: 0, count: 50));
// Assert.AreEqual(1, subset.Length);
// Config.AssertNearlyEqual(val, subset[0].Value);
// Assert.AreEqual(message, subset[0].Key);
// }
// }
// }
//}
using System.Collections.Generic;
using NUnit.Framework;
using System.Text;
using System;
using System.Linq;
using StackExchange.Redis;
namespace Tests
{
[TestFixture]
public class Strings // http://redis.io/commands#string
{
[Test]
public void Append()
{
using (var muxer = Config.GetUnsecuredConnection(waitForOpen: true))
{
var conn = muxer.GetDatabase(2);
var server = Config.GetServer(muxer);
conn.KeyDelete("append");
var l0 = server.Features.StringLength ? conn.StringLengthAsync("append") : null;
var s0 = conn.StringGetAsync("append");
conn.StringSetAsync("append", "abc");
var s1 = conn.StringGetAsync("append");
var l1 = server.Features.StringLength ? conn.StringLengthAsync("append") : null;
var result = conn.StringAppendAsync("append", Encode("defgh"));
var s3 = conn.StringGetAsync("append");
var l2 = server.Features.StringLength ? conn.StringLengthAsync("append") : null;
Assert.AreEqual(null, (string)conn.Wait(s0));
Assert.AreEqual("abc", (string)conn.Wait(s1));
Assert.AreEqual(8, conn.Wait(result));
Assert.AreEqual("abcdefgh", (string)conn.Wait(s3));
if (server.Features.StringLength)
{
Assert.AreEqual(0, conn.Wait(l0));
Assert.AreEqual(3, conn.Wait(l1));
Assert.AreEqual(8, conn.Wait(l2));
}
}
}
[Test]
public void Set()
{
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(2);
conn.KeyDeleteAsync("set");
conn.StringSetAsync("set", "abc");
var v1 = conn.StringGetAsync("set");
conn.StringSetAsync("set", Encode("def"));
var v2 = conn.StringGetAsync("set");
Assert.AreEqual("abc", (string)conn.Wait(v1));
Assert.AreEqual("def", (string)Decode(conn.Wait(v2)));
}
}
[Test]
public void SetNotExists()
{
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(2);
conn.KeyDeleteAsync("set");
conn.KeyDeleteAsync("set2");
conn.KeyDeleteAsync("set3");
conn.StringSetAsync("set", "abc");
var x0 = conn.StringSetAsync("set", "def", when: When.NotExists);
var x1 = conn.StringSetAsync("set", Encode("def"), when: When.NotExists);
var x2 = conn.StringSetAsync("set2", "def", when: When.NotExists);
var x3 = conn.StringSetAsync("set3", Encode("def"), when: When.NotExists);
var s0 = conn.StringGetAsync("set");
var s2 = conn.StringGetAsync("set2");
var s3 = conn.StringGetAsync("set3");
Assert.IsFalse(conn.Wait(x0));
Assert.IsFalse(conn.Wait(x1));
Assert.IsTrue(conn.Wait(x2));
Assert.IsTrue(conn.Wait(x3));
Assert.AreEqual("abc", (string)conn.Wait(s0));
Assert.AreEqual("def", (string)conn.Wait(s2));
Assert.AreEqual("def", (string)conn.Wait(s3));
}
}
[Test]
public void Ranges()
{
using (var muxer = Config.GetUnsecuredConnection(waitForOpen: true))
{
if (!Config.GetFeatures(muxer).StringSetRange) Assert.Inconclusive();
var conn = muxer.GetDatabase(2);
conn.KeyDeleteAsync("range");
conn.StringSetAsync("range", "abcdefghi");
conn.StringSetRangeAsync("range", 2, "xy");
conn.StringSetRangeAsync("range", 4, Encode("z"));
var val = conn.StringGetAsync("range");
Assert.AreEqual("abxyzfghi", (string)conn.Wait(val));
}
}
[Test]
public void IncrDecr()
{
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(2);
conn.KeyDeleteAsync("incr");
conn.StringSetAsync("incr", "2");
var v1 = conn.StringIncrementAsync("incr");
var v2 = conn.StringIncrementAsync("incr", 5);
var v3 = conn.StringIncrementAsync("incr", -2);
var v4 = conn.StringDecrementAsync("incr");
var v5 = conn.StringDecrementAsync("incr", 5);
var v6 = conn.StringDecrementAsync("incr", -2);
var s = conn.StringGetAsync("incr");
Assert.AreEqual(3, conn.Wait(v1));
Assert.AreEqual(8, conn.Wait(v2));
Assert.AreEqual(6, conn.Wait(v3));
Assert.AreEqual(5, conn.Wait(v4));
Assert.AreEqual(0, conn.Wait(v5));
Assert.AreEqual(2, conn.Wait(v6));
Assert.AreEqual("2", (string)conn.Wait(s));
}
}
[Test]
public void IncrDecrFloat()
{
using (var muxer = Config.GetUnsecuredConnection(waitForOpen: true))
{
if (!Config.GetFeatures(muxer).IncrementFloat) Assert.Inconclusive();
var conn = muxer.GetDatabase(2);
conn.KeyDelete("incr");
conn.StringSetAsync("incr", "2");
var v1 = conn.StringIncrementAsync("incr", 1.1);
var v2 = conn.StringIncrementAsync("incr", 5.0);
var v3 = conn.StringIncrementAsync("incr", -2.0);
var v4 = conn.StringIncrementAsync("incr", -1.0);
var v5 = conn.StringIncrementAsync("incr", -5.0);
var v6 = conn.StringIncrementAsync("incr", 2.0);
var s = conn.StringGetAsync("incr");
Config.AssertNearlyEqual(3.1, conn.Wait(v1));
Config.AssertNearlyEqual(8.1, conn.Wait(v2));
Config.AssertNearlyEqual(6.1, conn.Wait(v3));
Config.AssertNearlyEqual(5.1, conn.Wait(v4));
Config.AssertNearlyEqual(0.1, conn.Wait(v5));
Config.AssertNearlyEqual(2.1, conn.Wait(v6));
Assert.AreEqual("2.1", (string)conn.Wait(s));
}
}
[Test]
public void GetRange()
{
using (var muxer = Config.GetUnsecuredConnection(waitForOpen: true))
{
var conn = muxer.GetDatabase(2);
conn.KeyDeleteAsync("range");
conn.StringSetAsync("range", "abcdefghi");
var s = conn.StringGetRangeAsync("range", 2, 4);
var b = conn.StringGetRangeAsync("range", 2, 4);
Assert.AreEqual("cde", (string)conn.Wait(s));
Assert.AreEqual("cde", Decode(conn.Wait(b)));
}
}
[Test]
public void BitCount()
{
using (var muxer = Config.GetUnsecuredConnection(waitForOpen: true))
{
if (!Config.GetFeatures(muxer).BitwiseOperations) Assert.Inconclusive();
var conn = muxer.GetDatabase(0);
conn.StringSetAsync("mykey", "foobar");
var r1 = conn.StringBitCountAsync("mykey");
var r2 = conn.StringBitCountAsync("mykey", 0, 0);
var r3 = conn.StringBitCountAsync("mykey", 1, 1);
Assert.AreEqual(26, conn.Wait(r1));
Assert.AreEqual(4, conn.Wait(r2));
Assert.AreEqual(6, conn.Wait(r3));
}
}
[Test]
public void BitOp()
{
using (var muxer = Config.GetUnsecuredConnection(waitForOpen: true))
{
if (!Config.GetFeatures(muxer).BitwiseOperations) Assert.Inconclusive();
var conn = muxer.GetDatabase(0);
conn.StringSetAsync("key1", new byte[] { 3 });
conn.StringSetAsync("key2", new byte[] { 6 });
conn.StringSetAsync("key3", new byte[] { 12 });
var len_and = conn.StringBitOperationAsync(Bitwise.And, "and", new RedisKey[] { "key1", "key2", "key3" });
var len_or = conn.StringBitOperationAsync(Bitwise.Or, "or", new RedisKey[] { "key1", "key2", "key3" });
var len_xor = conn.StringBitOperationAsync(Bitwise.Xor, "xor", new RedisKey[] { "key1", "key2", "key3" });
var len_not = conn.StringBitOperationAsync(Bitwise.Not, "not", "key1");
Assert.AreEqual(1, conn.Wait(len_and));
Assert.AreEqual(1, conn.Wait(len_or));
Assert.AreEqual(1, conn.Wait(len_xor));
Assert.AreEqual(1, conn.Wait(len_not));
var r_and = ((byte[])conn.Wait(conn.StringGetAsync("and"))).Single();
var r_or = ((byte[])conn.Wait(conn.StringGetAsync("or"))).Single();
var r_xor = ((byte[])conn.Wait(conn.StringGetAsync("xor"))).Single();
var r_not = ((byte[])conn.Wait(conn.StringGetAsync("not"))).Single();
Assert.AreEqual((byte)(3 & 6 & 12), r_and);
Assert.AreEqual((byte)(3 | 6 | 12), r_or);
Assert.AreEqual((byte)(3 ^ 6 ^ 12), r_xor);
Assert.AreEqual(unchecked((byte)(~3)), r_not);
}
}
[Test]
public void RangeString()
{
using (var muxer = Config.GetUnsecuredConnection())
{
var conn = muxer.GetDatabase(0);
conn.StringSetAsync("my key", "hello world");
var result = conn.StringGetRangeAsync("my key", 2, 6);
Assert.AreEqual("llo w", (string)conn.Wait(result));
}
}
static byte[] Encode(string value) { return Encoding.UTF8.GetBytes(value); }
static string Decode(byte[] value) { return Encoding.UTF8.GetString(value); }
}
}
//using System.Threading.Tasks;
//using NUnit.Framework;
//using System.Collections.Generic;
//using System;
//using System.Linq;
//using BookSleeve;
//using System.Text;
//using System.Threading;
//namespace Tests
//{
// [TestFixture]
// public class Transactions // http://redis.io/commands#transactions
// {
// [Test]
// public void TestBasicMultiExec()
// {
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(1, "tran");
// conn.Keys.Remove(2, "tran");
// using (var tran = conn.CreateTransaction())
// {
// var s1 = tran.Strings.Set(1, "tran", "abc");
// var s2 = tran.Strings.Set(2, "tran", "def");
// var g1 = tran.Strings.GetString(1, "tran");
// var g2 = tran.Strings.GetString(2, "tran");
// var outsideTran = conn.Strings.GetString(1, "tran");
// var exec = tran.Execute();
// Assert.IsNull(conn.Wait(outsideTran));
// Assert.AreEqual("abc", conn.Wait(g1));
// Assert.AreEqual("def", conn.Wait(g2));
// conn.Wait(s1);
// conn.Wait(s2);
// conn.Wait(exec);
// }
// }
// }
// [Test]
// public void TestRollback()
// {
// using (var conn = Config.GetUnsecuredConnection())
// using (var tran = conn.CreateTransaction())
// {
// var task = tran.Strings.Set(4, "abc", "def");
// tran.Discard();
// Assert.IsTrue(task.IsCanceled, "should be cancelled");
// try
// {
// conn.Wait(task);
// }
// catch (TaskCanceledException)
// { }// ok, else boom!
// }
// }
// [Test]
// public void TestDispose()
// {
// Task task;
// using (var conn = Config.GetUnsecuredConnection())
// {
// using (var tran = conn.CreateTransaction())
// {
// task = tran.Strings.Set(4, "abc", "def");
// }
// Assert.IsTrue(task.IsCanceled, "should be cancelled");
// try
// {
// conn.Wait(task);
// }
// catch (TaskCanceledException)
// { }// ok, else boom!
// }
// }
// [Test]
// public void BlogDemo()
// {
// int db = 8;
// using (var conn = Config.GetUnsecuredConnection())
// {
// conn.Keys.Remove(db, "foo"); // just to reset
// using (var tran = conn.CreateTransaction())
// { // deliberately ignoring INCRBY here
// tran.AddCondition(Condition.KeyNotExists(db, "foo"));
// var t1 = tran.Strings.Increment(db, "foo");
// var t2 = tran.Strings.Increment(db, "foo");
// var val = tran.Strings.GetString(db, "foo");
// var t3 = tran.Execute(); // this *still* returns a Task
// Assert.AreEqual(true, conn.Wait(t3));
// Assert.AreEqual(1, conn.Wait(t1));
// Assert.AreEqual(2, conn.Wait(t2));
// Assert.AreEqual("2", conn.Wait(val));
// }
// }
// }
// [Test]
// public void AbortWorks()
// {
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// {
// conn.CompletionMode = ResultCompletionMode.PreserveOrder;
// conn.Keys.Remove(0, "AbortWorks");
// using (var tran = conn.CreateTransaction())
// {
// var condition = tran.AddCondition(Condition.KeyExists(0, "AbortWorks"));
// var rename = tran.Strings.Increment(0, "key");
// var success = conn.Wait(tran.Execute());
// Assert.IsFalse(success, "success");
// Assert.IsFalse(conn.Wait(condition), "condition");
// Assert.AreEqual(TaskStatus.Canceled, rename.Status, "rename");
// }
// }
// }
// [Test]
// public void SignalRSend()
// {
// const int db = 3;
// const string idKey = "newid";
// const string channel = "SignalRSend";
// using (var conn = Config.GetUnsecuredConnection(waitForOpen: true))
// using (var sub = conn.GetOpenSubscriberChannel())
// {
// conn.CompletionMode = ResultCompletionMode.ConcurrentIfContinuation;
// sub.CompletionMode = ResultCompletionMode.PreserveOrder;
// var received = new List<string>();
// sub.Subscribe(channel, (chan, payload) =>
// {
// lock (received) { received.Add(Encoding.UTF8.GetString(payload)); }
// });
// conn.Keys.Remove(db, idKey);
// int totalAttempts = 0;
// var evt = new ManualResetEvent(false);
// const int threadCount = 2;
// const int perThread = 5;
// int unreadyThreads = threadCount;
// ParameterizedThreadStart work = state =>
// {
// string thread = (string)state;
// if (Interlocked.Decrement(ref unreadyThreads) == 0)
// {
// // all threads ready; unleash the hounds!
// evt.Set();
// }
// else
// {
// evt.WaitOne();
// }
// for (int i = 0; i < perThread; i++)
// {
// int attempts = Send(conn, idKey, db, channel, thread + ":" + i).Result;
// Interlocked.Add(ref totalAttempts, attempts);
// }
// };
// var threads = new Thread[unreadyThreads];
// for (int i = 0; i < threads.Length; i++) threads[i] = new Thread(work);
// for (int i = 0; i < threads.Length; i++) threads[i].Start(i.ToString());
// for (int i = 0; i < threads.Length; i++) threads[i].Join();
// const int expected = perThread * threadCount;
// // it doesn't matter that this number is big; we are testing the pathological worst-case
// // scenario here; multiple threads aggressively causing conflicts
// Console.WriteLine("total messages: {0} (vs {1} theoretical)", totalAttempts, expected);
// // check we got everything we expected, and nothing more; the messages should
// // all be increasing; we should have every thread/loop combination
// Assert.AreEqual(expected, received.Count, "total messages");
// for (int i = 0; i < expected; i++)
// {
// string want = (i + 1) + ":";
// Assert.IsTrue(received[i].StartsWith(want), want);
// }
// for (int i = 0; i < threadCount; i++)
// {
// for (int j = 0; j < perThread; j++)
// {
// string want = ":" + i + ":" + j;
// bool found = received.Any(x => x.EndsWith(want));
// Assert.IsTrue(found, want);
// }
// }
// }
// }
// static async Task<int> Send(RedisConnection conn, string idKey, int db, string channel, string data)
// {
// int attempts = 0;
// bool success;
// do
// {
// var oldId = await conn.Strings.GetInt64(db, idKey).SafeAwaitable().ConfigureAwait(false); // important: let this be nullable;
// // means "doesn't exist"
// var newId = (oldId ?? 0) + 1;
// var payload = Pack(newId, data);
// using (var tran = conn.CreateTransaction())
// {
// var x0 = tran.AddCondition(Condition.KeyEquals(db, idKey, oldId)).SafeAwaitable();
// var x1 = tran.Strings.Increment(db, idKey).SafeAwaitable();
// var x2 = tran.Publish(channel, payload).SafeAwaitable();
// success = await tran.Execute().SafeAwaitable().ConfigureAwait(false);
// if (success)
// {
// // still expect all of these to get answers
// await Task.WhenAll(x0, x1, x2);
// Assert.IsTrue(x0.Result, "condition passed");
// Assert.AreEqual(newId, x1.Result);
// }
// else
// {
// // can't say much about x0; could have got past that
// Assert.IsTrue(await IsCancelled(x1));
// Assert.IsTrue(await IsCancelled(x2));
// }
// attempts++;
// }
// } while (!success);
// return attempts;
// }
// [Test]
// public void Issue43()
// {
// using(var conn = Config.GetRemoteConnection())
// {
// conn.Keys.Remove(0, "anExistingKey1");
// conn.Keys.Remove(0, "anExistingKey2");
// conn.Keys.Remove(0, "anExistingKey3");
// conn.Strings.Set(0, "anExistingKey1", "anExistingKey1");
// conn.Strings.Set(0, "anExistingKey2", "anExistingKey2");
// conn.Strings.Set(0, "anExistingKey3", "anExistingKey3");
// for(int i = 0; i < 10000; i++)
// {
// using(var tx = conn.CreateTransaction())
// {
// var cond1 = tx.AddCondition(Condition.KeyExists(0, "anExistingKey1"));
// var cond2 = tx.AddCondition(Condition.KeyExists(0, "anExistingKey2"));
// var cond3 = tx.AddCondition(Condition.KeyExists(0, "anExistingKey3"));
// tx.Strings.Increment(0, "foo", 1);
// tx.Strings.Increment(0, "foo", 1);
// tx.Strings.Increment(0, "foo", 1);
// var txRes = tx.Execute();
// Assert.IsTrue(tx.Wait(cond1), "cond1" + i); //--> ok
// Assert.IsTrue(tx.Wait(cond2), "cond2" + i); //--> ok
// Assert.IsTrue(tx.Wait(cond3), "cond3" + i); //--> ok
// Assert.IsTrue(tx.Wait(txRes), "txRes" + i); //--> not ok: false
// }
// }
// }
// }
// static async Task<bool> IsCancelled(Task task)
// {
// try
// {
// await task;
// return false;
// }
// catch
// {
// return task.IsCanceled;
// }
// }
// static byte[] Pack(long id, string data)
// {
// return Encoding.UTF8.GetBytes(id + ":" + data);
// }
// }
//}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NUnit" version="2.6.3" targetFramework="net45" />
</packages>
\ No newline at end of file
// preamble: original source: https://github.com/migueldeicaza/redis-sharp/blob/master/redis-sharp.cs
// included here for performance test purposes only; this is a separate and parallel implementation
//
// redis-sharp.cs: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010 Novell, Inc.
//
// Licensed under the same terms of reddis: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
public class Redis : IDisposable
{
Socket socket;
BufferedStream bstream;
public enum KeyType
{
None, String, List, Set
}
public class ResponseException : Exception
{
public ResponseException(string code)
: base("Response error")
{
Code = code;
}
public string Code { get; private set; }
}
public Redis(string host, int port)
{
if (host == null)
throw new ArgumentNullException("host");
Host = host;
Port = port;
SendTimeout = -1;
}
public Redis(string host)
: this(host, 6379)
{
}
public Redis()
: this("localhost", 6379)
{
}
public string Host { get; private set; }
public int Port { get; private set; }
public int RetryTimeout { get; set; }
public int RetryCount { get; set; }
public int SendTimeout { get; set; }
public string Password { get; set; }
int db;
public int Db
{
get
{
return db;
}
set
{
db = value;
SendExpectSuccess("SELECT {0}\r\n", db);
}
}
public string this[string key]
{
get { return GetString(key); }
set { Set(key, value); }
}
public void Set(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
Set(key, Encoding.UTF8.GetBytes(value));
}
public void Set(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
if (!SendDataCommand(value, "SET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect");
ExpectSuccess();
}
public bool SetNX(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
return SetNX(key, Encoding.UTF8.GetBytes(value));
}
public bool SetNX(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
return SendDataExpectInt(value, "SETNX {0} {1}\r\n", key, value.Length) > 0 ? true : false;
}
public void Set(IDictionary<string, string> dict)
{
Set(dict.ToDictionary(k => k.Key, v => Encoding.UTF8.GetBytes(v.Value)));
}
public void Set(IDictionary<string, byte[]> dict)
{
if (dict == null)
throw new ArgumentNullException("dict");
var nl = Encoding.UTF8.GetBytes("\r\n");
var ms = new MemoryStream();
foreach (var key in dict.Keys)
{
var val = dict[key];
var kLength = Encoding.UTF8.GetBytes("$" + key.Length + "\r\n");
var k = Encoding.UTF8.GetBytes(key + "\r\n");
var vLength = Encoding.UTF8.GetBytes("$" + val.Length + "\r\n");
ms.Write(kLength, 0, kLength.Length);
ms.Write(k, 0, k.Length);
ms.Write(vLength, 0, vLength.Length);
ms.Write(val, 0, val.Length);
ms.Write(nl, 0, nl.Length);
}
SendDataCommand(ms.ToArray(), "*" + (dict.Count * 2 + 1) + "\r\n$4\r\nMSET\r\n");
ExpectSuccess();
}
public byte[] Get(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectData(null, "GET " + key + "\r\n");
}
public string GetString(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return Encoding.UTF8.GetString(Get(key));
}
public byte[][] Sort(SortOptions options)
{
return SendDataCommandExpectMultiBulkReply(null, options.ToCommand() + "\r\n");
}
public byte[] GetSet(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
if (!SendDataCommand(value, "GETSET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect");
return ReadData();
}
public string GetSet(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
return Encoding.UTF8.GetString(GetSet(key, Encoding.UTF8.GetBytes(value)));
}
string ReadLine()
{
var sb = new StringBuilder();
int c;
while ((c = bstream.ReadByte()) != -1)
{
if (c == '\r')
continue;
if (c == '\n')
break;
sb.Append((char)c);
}
return sb.ToString();
}
void Connect()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = true;
socket.SendTimeout = SendTimeout;
socket.Connect(Host, Port);
if (!socket.Connected)
{
socket.Close();
socket = null;
return;
}
bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);
if (Password != null)
SendExpectSuccess("AUTH {0}\r\n", Password);
}
byte[] end_data = new byte[] { (byte)'\r', (byte)'\n' };
bool SendDataCommand(byte[] data, string cmd, params object[] args)
{
if (socket == null)
Connect();
if (socket == null)
return false;
var s = args.Length > 0 ? String.Format(cmd, args) : cmd;
byte[] r = Encoding.UTF8.GetBytes(s);
try
{
Log("S: " + String.Format(cmd, args));
socket.Send(r);
if (data != null)
{
socket.Send(data);
socket.Send(end_data);
}
}
catch (SocketException)
{
// timeout;
socket.Close();
socket = null;
return false;
}
return true;
}
bool SendCommand(string cmd, params object[] args)
{
if (socket == null)
Connect();
if (socket == null)
return false;
var s = args != null && args.Length > 0 ? String.Format(cmd, args) : cmd;
byte[] r = Encoding.UTF8.GetBytes(s);
try
{
Log("S: " + String.Format(cmd, args));
socket.Send(r);
}
catch (SocketException)
{
// timeout;
socket.Close();
socket = null;
return false;
}
return true;
}
[Conditional("DEBUG")]
void Log(string fmt, params object[] args)
{
Console.WriteLine("{0}", String.Format(fmt, args).Trim());
}
void ExpectSuccess()
{
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
}
void SendExpectSuccess(string cmd, params object[] args)
{
if (!SendCommand(cmd, args))
throw new Exception("Unable to connect");
ExpectSuccess();
}
int SendDataExpectInt(byte[] data, string cmd, params object[] args)
{
if (!SendDataCommand(data, cmd, args))
throw new Exception("Unable to connect");
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':')
{
int i;
if (int.TryParse(s, out i))
return i;
}
throw new ResponseException("Unknown reply on integer request: " + c + s);
}
int SendExpectInt(string cmd, params object[] args)
{
if (!SendCommand(cmd, args))
throw new Exception("Unable to connect");
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':')
{
int i;
if (int.TryParse(s, out i))
return i;
}
throw new ResponseException("Unknown reply on integer request: " + c + s);
}
string SendExpectString(string cmd, params object[] args)
{
if (!SendCommand(cmd, args))
throw new Exception("Unable to connect");
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '+')
return s;
throw new ResponseException("Unknown reply on integer request: " + c + s);
}
//
// This one does not throw errors
//
string SendGetString(string cmd, params object[] args)
{
if (!SendCommand(cmd, args))
throw new Exception("Unable to connect");
return ReadLine();
}
byte[] SendExpectData(byte[] data, string cmd, params object[] args)
{
if (!SendDataCommand(data, cmd, args))
throw new Exception("Unable to connect");
return ReadData();
}
byte[] ReadData()
{
string r = ReadLine();
Log("R: {0}", r);
if (r.Length == 0)
throw new ResponseException("Zero length respose");
char c = r[0];
if (c == '-')
throw new ResponseException(r.StartsWith("-ERR") ? r.Substring(5) : r.Substring(1));
if (c == '$')
{
if (r == "$-1")
return null;
int n;
if (Int32.TryParse(r.Substring(1), out n))
{
byte[] retbuf = new byte[n];
int bytesRead = 0;
do
{
int read = bstream.Read(retbuf, bytesRead, n - bytesRead);
if (read < 1)
throw new ResponseException("Invalid termination mid stream");
bytesRead += read;
}
while (bytesRead < n);
if (bstream.ReadByte() != '\r' || bstream.ReadByte() != '\n')
throw new ResponseException("Invalid termination");
return retbuf;
}
throw new ResponseException("Invalid length");
}
//returns the number of matches
if (c == '*')
{
int n;
if (Int32.TryParse(r.Substring(1), out n))
return n <= 0 ? new byte[0] : ReadData();
throw new ResponseException("Unexpected length parameter" + r);
}
throw new ResponseException("Unexpected reply: " + r);
}
public bool ContainsKey(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("EXISTS " + key + "\r\n") == 1;
}
public bool Remove(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("DEL " + key + "\r\n", key) == 1;
}
public int Remove(params string[] args)
{
if (args == null)
throw new ArgumentNullException("args");
return SendExpectInt("DEL " + string.Join(" ", args) + "\r\n");
}
public int Increment(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("INCR " + key + "\r\n");
}
public int Increment(string key, int count)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("INCRBY {0} {1}\r\n", key, count);
}
public int Decrement(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("DECR " + key + "\r\n");
}
public int Decrement(string key, int count)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("DECRBY {0} {1}\r\n", key, count);
}
public KeyType TypeOf(string key)
{
if (key == null)
throw new ArgumentNullException("key");
switch (SendExpectString("TYPE {0}\r\n", key))
{
case "none":
return KeyType.None;
case "string":
return KeyType.String;
case "set":
return KeyType.Set;
case "list":
return KeyType.List;
}
throw new ResponseException("Invalid value");
}
public string RandomKey()
{
return SendExpectString("RANDOMKEY\r\n");
}
public bool Rename(string oldKeyname, string newKeyname)
{
if (oldKeyname == null)
throw new ArgumentNullException("oldKeyname");
if (newKeyname == null)
throw new ArgumentNullException("newKeyname");
return SendGetString("RENAME {0} {1}\r\n", oldKeyname, newKeyname)[0] == '+';
}
public bool Expire(string key, int seconds)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("EXPIRE {0} {1}\r\n", key, seconds) == 1;
}
public bool ExpireAt(string key, int time)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("EXPIREAT {0} {1}\r\n", key, time) == 1;
}
public int TimeToLive(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("TTL {0}\r\n", key);
}
public int DbSize
{
get
{
return SendExpectInt("DBSIZE\r\n");
}
}
public string Save()
{
return SendGetString("SAVE\r\n");
}
public void BackgroundSave()
{
SendGetString("BGSAVE\r\n");
}
public void Shutdown()
{
SendGetString("SHUTDOWN\r\n");
}
public void FlushAll()
{
SendGetString("FLUSHALL\r\n");
}
public void FlushDb()
{
SendGetString("FLUSHDB\r\n");
}
const long UnixEpoch = 621355968000000000L;
public DateTime LastSave
{
get
{
int t = SendExpectInt("LASTSAVE\r\n");
return new DateTime(UnixEpoch) + TimeSpan.FromSeconds(t);
}
}
public Dictionary<string, string> GetInfo()
{
byte[] r = SendExpectData(null, "INFO\r\n");
var dict = new Dictionary<string, string>();
foreach (var line in Encoding.UTF8.GetString(r).Split('\n'))
{
int p = line.IndexOf(':');
if (p == -1)
continue;
dict.Add(line.Substring(0, p), line.Substring(p + 1));
}
return dict;
}
public string[] Keys
{
get
{
string commandResponse = Encoding.UTF8.GetString(SendExpectData(null, "KEYS *\r\n"));
if (commandResponse.Length < 1)
return new string[0];
else
return commandResponse.Split(' ');
}
}
public string[] GetKeys(string pattern)
{
if (pattern == null)
throw new ArgumentNullException("key");
var keys = SendExpectData(null, "KEYS {0}\r\n", pattern);
if (keys.Length == 0)
return new string[0];
return Encoding.UTF8.GetString(keys).Split(' ');
}
public byte[][] GetKeys(params string[] keys)
{
if (keys == null)
throw new ArgumentNullException("key1");
if (keys.Length == 0)
throw new ArgumentException("keys");
return SendDataCommandExpectMultiBulkReply(null, "MGET {0}\r\n", string.Join(" ", keys));
}
public byte[][] SendDataCommandExpectMultiBulkReply(byte[] data, string command, params object[] args)
{
if (!SendDataCommand(data, command, args))
throw new Exception("Unable to connect");
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '*')
{
int count;
if (int.TryParse(s, out count))
{
var result = new byte[count][];
for (int i = 0; i < count; i++)
result[i] = ReadData();
return result;
}
}
throw new ResponseException("Unknown reply on multi-request: " + c + s);
}
#region List commands
public byte[][] ListRange(string key, int start, int end)
{
return SendDataCommandExpectMultiBulkReply(null, "LRANGE {0} {1} {2}\r\n", key, start, end);
}
public void RightPush(string key, string value)
{
SendExpectSuccess("RPUSH {0} {1}\r\n{2}\r\n", key, value.Length, value);
}
public int ListLength(string key)
{
return SendExpectInt("LLEN {0}\r\n", key);
}
public byte[] ListIndex(string key, int index)
{
SendCommand("LINDEX {0} {1}\r\n", key, index);
return ReadData();
}
public byte[] LeftPop(string key)
{
SendCommand("LPOP {0}\r\n", key);
return ReadData();
}
#endregion
#region Set commands
public bool AddToSet(string key, byte[] member)
{
return SendDataExpectInt(member, "SADD {0} {1}\r\n", key, member.Length) > 0;
}
public bool AddToSet(string key, string member)
{
return AddToSet(key, Encoding.UTF8.GetBytes(member));
}
public int CardinalityOfSet(string key)
{
return SendDataExpectInt(null, "SCARD {0}\r\n", key);
}
public bool IsMemberOfSet(string key, byte[] member)
{
return SendDataExpectInt(member, "SISMEMBER {0} {1}\r\n", key, member.Length) > 0;
}
public bool IsMemberOfSet(string key, string member)
{
return IsMemberOfSet(key, Encoding.UTF8.GetBytes(member));
}
public byte[][] GetMembersOfSet(string key)
{
return SendDataCommandExpectMultiBulkReply(null, "SMEMBERS {0}\r\n", key);
}
public byte[] GetRandomMemberOfSet(string key)
{
return SendExpectData(null, "SRANDMEMBER {0}\r\n", key);
}
public byte[] PopRandomMemberOfSet(string key)
{
return SendExpectData(null, "SPOP {0}\r\n", key);
}
public bool RemoveFromSet(string key, byte[] member)
{
return SendDataExpectInt(member, "SREM {0} {1}\r\n", key, member.Length) > 0;
}
public bool RemoveFromSet(string key, string member)
{
return RemoveFromSet(key, Encoding.UTF8.GetBytes(member));
}
public byte[][] GetUnionOfSets(params string[] keys)
{
if (keys == null)
throw new ArgumentNullException();
return SendDataCommandExpectMultiBulkReply(null, "SUNION " + string.Join(" ", keys) + "\r\n");
}
void StoreSetCommands(string cmd, string destKey, params string[] keys)
{
if (String.IsNullOrEmpty(cmd))
throw new ArgumentNullException("cmd");
if (String.IsNullOrEmpty(destKey))
throw new ArgumentNullException("destKey");
if (keys == null)
throw new ArgumentNullException("keys");
SendExpectSuccess("{0} {1} {2}\r\n", cmd, destKey, String.Join(" ", keys));
}
public void StoreUnionOfSets(string destKey, params string[] keys)
{
StoreSetCommands("SUNIONSTORE", destKey, keys);
}
public byte[][] GetIntersectionOfSets(params string[] keys)
{
if (keys == null)
throw new ArgumentNullException();
return SendDataCommandExpectMultiBulkReply(null, "SINTER " + string.Join(" ", keys) + "\r\n");
}
public void StoreIntersectionOfSets(string destKey, params string[] keys)
{
StoreSetCommands("SINTERSTORE", destKey, keys);
}
public byte[][] GetDifferenceOfSets(params string[] keys)
{
if (keys == null)
throw new ArgumentNullException();
return SendDataCommandExpectMultiBulkReply(null, "SDIFF " + string.Join(" ", keys) + "\r\n");
}
public void StoreDifferenceOfSets(string destKey, params string[] keys)
{
StoreSetCommands("SDIFFSTORE", destKey, keys);
}
public bool MoveMemberToSet(string srcKey, string destKey, byte[] member)
{
return SendDataExpectInt(member, "SMOVE {0} {1} {2}\r\n", srcKey, destKey, member.Length) > 0;
}
#endregion
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Redis()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
SendCommand("QUIT\r\n");
socket.Close();
socket = null;
}
}
}
public class SortOptions
{
public string Key { get; set; }
public bool Descending { get; set; }
public bool Lexographically { get; set; }
public Int32 LowerLimit { get; set; }
public Int32 UpperLimit { get; set; }
public string By { get; set; }
public string StoreInKey { get; set; }
public string Get { get; set; }
public string ToCommand()
{
var command = "SORT " + this.Key;
if (LowerLimit != 0 || UpperLimit != 0)
command += " LIMIT " + LowerLimit + " " + UpperLimit;
if (Lexographically)
command += " ALPHA";
if (!string.IsNullOrEmpty(By))
command += " BY " + By;
if (!string.IsNullOrEmpty(Get))
command += " GET " + Get;
if (!string.IsNullOrEmpty(StoreInKey))
command += " STORE " + StoreInKey;
return command;
}
}
......@@ -46,6 +46,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Docs", "Docs\Docs.csproj",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BasicTest", "BasicTest\BasicTest.csproj", "{BE213DFB-5334-4441-B975-0DBCFD5F5A73}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MigratedBookSleeveTestSuite", "MigratedBookSleeveTestSuite\MigratedBookSleeveTestSuite.csproj", "{97B45B3A-34DB-43C3-A979-37F217390142}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -94,6 +96,14 @@ Global
{BE213DFB-5334-4441-B975-0DBCFD5F5A73}.Release|Any CPU.Build.0 = Release|Any CPU
{BE213DFB-5334-4441-B975-0DBCFD5F5A73}.Verbose|Any CPU.ActiveCfg = Release|Any CPU
{BE213DFB-5334-4441-B975-0DBCFD5F5A73}.Verbose|Any CPU.Build.0 = Release|Any CPU
{97B45B3A-34DB-43C3-A979-37F217390142}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97B45B3A-34DB-43C3-A979-37F217390142}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97B45B3A-34DB-43C3-A979-37F217390142}.Log Output|Any CPU.ActiveCfg = Release|Any CPU
{97B45B3A-34DB-43C3-A979-37F217390142}.Log Output|Any CPU.Build.0 = Release|Any CPU
{97B45B3A-34DB-43C3-A979-37F217390142}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97B45B3A-34DB-43C3-A979-37F217390142}.Release|Any CPU.Build.0 = Release|Any CPU
{97B45B3A-34DB-43C3-A979-37F217390142}.Verbose|Any CPU.ActiveCfg = Release|Any CPU
{97B45B3A-34DB-43C3-A979-37F217390142}.Verbose|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
<?xml version="1.0" encoding="utf-8"?>
<repositories>
<repository path="..\MigratedBookSleeveTestSuite\packages.config" />
<repository path="..\StackExchange.Redis.Tests\packages.config" />
</repositories>
\ No newline at end of file
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