Permalink
Browse files

Refactored tests to use the new connection string code and a MongoTes…

…tBase class
  • Loading branch information...
1 parent 013c9fd commit a209e2700643eb4d4bd52586d98497d51749d7ed @samus committed Mar 8, 2010
View
3 .gitignore
@@ -21,6 +21,9 @@
*/test-results/*
/test-results/
+/examples/*/bin/*
+/examples/*/test-results/*
+
/_UpgradeReport_Files/*
/redist/*.zip
View
78 MongoDB.GridFS.Tests/GridFileInfoTest.cs
@@ -8,14 +8,21 @@
namespace MongoDB.GridFS
{
[TestFixture]
- public class GridFileInfoTest
+ public class GridFileInfoTest : GridTestBase
{
- Mongo db = new Mongo();
+
+ public override string TestFileSystems {
+ get {
+ return "gfcreate,gfdelete,gfmove,gfopen,gfexists,gfinfo";
+ }
+ }
+
+
[Test]
public void TestCreateNonExisting(){
String filename = "newfile.txt";
- GridFile gf = new GridFile(db["tests"],"gfcreate");
- GridFileInfo gfi = new GridFileInfo(db["tests"],"gfcreate", filename);
+ GridFile gf = new GridFile(DB,"gfcreate");
+ GridFileInfo gfi = new GridFileInfo(DB,"gfcreate", filename);
Assert.AreEqual(filename, gfi.FileName);
GridFileStream gfs = gfi.Create();
@@ -26,12 +33,14 @@ public class GridFileInfoTest
[Test]
public void TestCreateExisting(){
String filename = "existing.txt";
- GridFile gf = new GridFile(db["tests"],"gfcreate");
- GridFileInfo gfi = new GridFileInfo(db["tests"],"gfcreate", filename);
+ GridFile gf = new GridFile(DB,"gfcreate");
+ GridFileInfo gfi = new GridFileInfo(DB,"gfcreate", filename);
GridFileStream gfs = gfi.Create();
+ gfs.Close();
+
bool thrown = false;
try{
- gfi = new GridFileInfo(db["tests"],"create", filename);
+ gfi = new GridFileInfo(DB,"gfcreate", filename);
gfi.Create();
}catch(IOException){
thrown = true;
@@ -43,7 +52,7 @@ public class GridFileInfoTest
public void TestModeCreateNew(){
Object id;
string filename = "createnew.txt";
- GridFileInfo gfi = new GridFileInfo(db["tests"],"gfcreate", filename);
+ GridFileInfo gfi = new GridFileInfo(DB,"gfcreate", filename);
using(GridFileStream gfs = gfi.Create(FileMode.CreateNew)){
id = gfs.GridFileInfo.Id;
TextWriter tw = new StreamWriter(gfs);
@@ -56,8 +65,8 @@ public class GridFileInfoTest
[Test]
public void TestDelete(){
String filename = "gfi-delete.txt";
- GridFile gf = new GridFile(db["tests"],"gfdelete");
- GridFileInfo gfi = new GridFileInfo(db["tests"],"gfdelete", filename);
+ GridFile gf = new GridFile(DB,"gfdelete");
+ GridFileInfo gfi = new GridFileInfo(DB,"gfdelete", filename);
GridFileStream gfs = gfi.Create(); //TODO Expand Test to make sure that chunks for the file got deleted too.
gfi.Delete();
Assert.IsFalse(gf.Exists(filename), "File should have been deleted.");
@@ -67,8 +76,8 @@ public class GridFileInfoTest
public void TestMoveTo(){
String filename = "gfi-move.txt";
String filename2 = "gfi-move.txt2";
- GridFile gf = new GridFile(db["tests"],"gfmove");
- GridFileInfo gfi = new GridFileInfo(db["tests"],"gfmove", filename);
+ GridFile gf = new GridFile(DB,"gfmove");
+ GridFileInfo gfi = new GridFileInfo(DB,"gfmove", filename);
gfi.Create();
gfi.MoveTo(filename2);
Assert.IsFalse(gf.Exists(filename), "File should have been moved.");
@@ -79,7 +88,7 @@ public class GridFileInfoTest
[Test]
public void TestFileExists(){
string filename = "gfi-exists.txt";
- GridFileInfo gfi = new GridFileInfo(db["tests"], "gfexists", filename);
+ GridFileInfo gfi = new GridFileInfo(DB, "gfexists", filename);
Assert.IsFalse(gfi.Exists);
GridFileStream gfs = gfi.Create();
Assert.IsTrue(gfi.Exists);
@@ -88,8 +97,8 @@ public class GridFileInfoTest
[Test]
public void TestOpenNonExistentFails(){
string filename = "gfi-opennothere.txt";
- GridFile gf = new GridFile(db["tests"], "gfopen");
- GridFileInfo gfi = new GridFileInfo(db["tests"], "gfopen", filename);
+ GridFile gf = new GridFile(DB, "gfopen");
+ GridFileInfo gfi = new GridFileInfo(DB, "gfopen", filename);
bool thrown = false;
try{
GridFileStream gfs = gfi.OpenRead();
@@ -103,7 +112,7 @@ public class GridFileInfoTest
[Test]
public void TestOpenReadOnly(){
string filename = "gfi-open.txt";
- GridFile gf = new GridFile(db["tests"], "gfopen");
+ GridFile gf = new GridFile(DB, "gfopen");
GridFileStream gfs = gf.Create(filename);
gfs.Close();
@@ -126,7 +135,7 @@ public class GridFileInfoTest
string fs = "gfinfo";
Object id;
- GridFileInfo gfi = new GridFileInfo(db["tests"],fs, filename);
+ GridFileInfo gfi = new GridFileInfo(DB,fs, filename);
using(GridFileStream gfs = gfi.Create(FileMode.CreateNew)){
id = gfs.GridFileInfo.Id;
gfi.ContentType = "text/sam";
@@ -136,46 +145,13 @@ public class GridFileInfoTest
tw.Close();
}
gfi.Aliases = new String[]{"file1"};
- GridFileInfo gfi2 = new GridFileInfo(db["tests"],fs, filename);
+ GridFileInfo gfi2 = new GridFileInfo(DB,fs, filename);
Assert.IsTrue(gfi2.Exists, "Couldn't find " + filename);
Assert.AreEqual("text/sam", gfi2.ContentType);
Assert.AreNotEqual(gfi2.Aliases, gfi.Aliases);
gfi.UpdateInfo();
gfi2.Refresh();
Assert.AreEqual(gfi2.Aliases, gfi.Aliases);
- }
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- CleanDB(); //Run here instead of at the end so that the db can be examined after a run.
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- db.Disconnect();
- }
-
- protected void CleanDB(){
- //Any collections that we might want to delete before the tests run should be done here.
- DropGridFileSystem("gfcreate");
- DropGridFileSystem("gfdelete");
- DropGridFileSystem("gfmove");
- DropGridFileSystem("gfopen");
- DropGridFileSystem("gfexists");
- DropGridFileSystem("gfinfo");
- }
-
- protected void DropGridFileSystem(string filesystem){
- try{
- db["tests"].MetaData.DropCollection(filesystem + ".files");
- db["tests"].MetaData.DropCollection(filesystem + ".chunks");
- }catch(MongoCommandException){}//if it fails it is because the collection isn't there to start with.
-
- }
-
- protected long CountChunks(string filesystem, Object fileid){
- return db["tests"][filesystem + ".chunks"].Count(new Document().Append("files_id", fileid));
}
}
}
View
63 MongoDB.GridFS.Tests/GridFileStreamTest.cs
@@ -8,12 +8,22 @@
namespace MongoDB.GridFS
{
[TestFixture]
- public class GridFileStreamTest
+ public class GridFileStreamTest : GridTestBase
{
- Mongo db = new Mongo();
GridFile fs;
String filesystem = "gfstream";
+ public override string TestFileSystems {
+ get {
+ return filesystem;
+ }
+ }
+
+ public override void OnInit (){
+ fs = new GridFile(DB, filesystem);
+ }
+
+
[Test]
public void TestWrite(){
@@ -25,7 +35,7 @@ public class GridFileStreamTest
}
gfs.Close();
- Assert.AreEqual(1, CountChunks(id));
+ Assert.AreEqual(1, CountChunks(filesystem,id));
Document chunk = GrabChunk(id, 0);
Binary bin = (Binary)chunk["data"];
Assert.AreEqual(127, bin.Bytes[127]);
@@ -42,7 +52,7 @@ public class GridFileStreamTest
}
gfs.Close();
- Assert.AreEqual(1, CountChunks(id));
+ Assert.AreEqual(1, CountChunks(filesystem,id));
}
[Test]
@@ -56,7 +66,7 @@ public class GridFileStreamTest
gfs.Write(buff,0,buff.Length);
Assert.AreEqual(buff.Length, gfs.Position);
gfs.Close();
- Assert.AreEqual(chunks, CountChunks(id));
+ Assert.AreEqual(chunks, CountChunks(filesystem,id));
}
[Test]
@@ -99,7 +109,7 @@ public class GridFileStreamTest
int size = chunks * chunksize;
Object id = CreateDummyFile(filename, size, chunksize, offset);
- Assert.AreEqual(2, CountChunks(id));
+ Assert.AreEqual(2, CountChunks(filesystem,id));
GridFileStream gfs = fs.OpenRead(filename);
byte[] buff = new Byte[4];
@@ -134,7 +144,7 @@ public class GridFileStreamTest
}
gfs.Close();
- Assert.AreEqual(1, CountChunks(id));
+ Assert.AreEqual(1, CountChunks(filesystem,id));
Document chunk = GrabChunk(id, 0);
Binary b = (Binary)chunk["data"];
Assert.AreEqual(2, b.Bytes[chunksize-1]);
@@ -179,7 +189,7 @@ public class GridFileStreamTest
}
Assert.AreEqual(buffsize, gfs.Position, "Position is incorrect");
gfs.Close();
- Assert.AreEqual(chunks - 1, CountChunks(id));
+ Assert.AreEqual(chunks - 1, CountChunks(filesystem,id));
Document chunk = GrabChunk(id, 0);
Binary b = (Binary)chunk["data"];
Assert.AreEqual(2, b.Bytes[buffsize-1]);
@@ -238,10 +248,10 @@ public class GridFileStreamTest
gfs.SetLength(length);
gfs.WriteByte(2);
gfs.Close();
- GridFileInfo gfi = new GridFileInfo(db["tests"],filesystem,filename);
+ GridFileInfo gfi = new GridFileInfo(DB,filesystem,filename);
Assert.AreEqual(length + 1, gfi.Length);
- Assert.AreEqual(6, CountChunks(id));
+ Assert.AreEqual(6, CountChunks(filesystem,id));
}
@@ -308,41 +318,12 @@ public class GridFileStreamTest
#endregion
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- fs = new GridFile(db["tests"], filesystem);
- CleanDB(); //Run here instead of at the end so that the db can be examined after a run.
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- db.Disconnect();
- }
-
- protected void CleanDB(){
- //Any collections that we might want to delete before the tests run should be done here.
- DropGridFileSystem(filesystem);
- }
-
- protected void DropGridFileSystem(string filesystem){
- try{
- db["tests"].MetaData.DropCollection(filesystem + ".files");
- db["tests"].MetaData.DropCollection(filesystem + ".chunks");
- }catch(MongoCommandException){}//if it fails it is because the collection isn't there to start with.
-
- }
-
- protected long CountChunks(Object fileid){
- return db["tests"][filesystem + ".chunks"].Count(new Document().Append("files_id", fileid));
- }
-
protected Document GrabChunk(Object fileid, int chunk){
- return db["tests"][filesystem + ".chunks"].FindOne(new Document().Append("files_id", fileid).Append("n", chunk));
+ return DB[filesystem + ".chunks"].FindOne(new Document().Append("files_id", fileid).Append("n", chunk));
}
protected Object CreateDummyFile(string filename, int size, int chunksize, int initialOffset){
- GridFileInfo gfi = new GridFileInfo(db["tests"], "gfstream", filename);
+ GridFileInfo gfi = new GridFileInfo(DB, "gfstream", filename);
gfi.ChunkSize = chunksize;
GridFileStream gfs = gfi.Create();
Object id = gfs.GridFileInfo.Id;
View
48 MongoDB.GridFS.Tests/GridFileTest.cs
@@ -8,24 +8,29 @@
namespace MongoDB.GridFS
{
[TestFixture]
- public class GridFileTest{
- Mongo db = new Mongo();
+ public class GridFileTest : GridTestBase
+ {
+ public override string TestFileSystems {
+ get {
+ return "gfcopy,gfcreate,fs";
+ }
+ }
[Test]
public void TestFileDoesNotExist(){
- GridFile fs = new GridFile(db["tests"]);
+ GridFile fs = new GridFile(DB);
Assert.IsFalse(fs.Exists("non-existent filename"));
}
[Test]
public void TestFileDoes(){
- GridFile fs = new GridFile(db["tests"]);
+ GridFile fs = new GridFile(DB);
fs.Create("exists.txt");
Assert.IsTrue(fs.Exists("exists.txt"));
}
[Test]
public void TestCopy(){
- GridFile fs = new GridFile(db["tests"], "gfcopy");
+ GridFile fs = new GridFile(DB, "gfcopy");
GridFileStream gfs = fs.Create("original.txt");
gfs.WriteByte(1);
gfs.Seek(1024 * 256 * 2, SeekOrigin.Begin);
@@ -41,45 +46,14 @@ public class GridFileTest{
public void TestModeCreateNew(){
Object id;
string filename = "createnew.txt";
- GridFile gf = new GridFile(db["tests"],"gfcreate");
+ GridFile gf = new GridFile(DB,"gfcreate");
using(GridFileStream gfs = gf.Create(filename, FileMode.CreateNew)){
id = gfs.GridFileInfo.Id;
TextWriter tw = new StreamWriter(gfs);
tw.WriteLine("test");
tw.Close();
}
Assert.AreEqual(1, CountChunks("gfcreate", id));
- }
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- CleanDB(); //Run here instead of at the end so that the db can be examined after a run.
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- db.Disconnect();
- }
-
- protected void CleanDB(){
- //Any collections that we might want to delete before the tests run should be done here.
- DropGridFileSystem("gfcopy");
- DropGridFileSystem("gfcreate");
- DropGridFileSystem("fs");
- }
-
- protected void DropGridFileSystem(string filesystem){
- try{
- db["tests"].MetaData.DropCollection(filesystem + ".files");
- db["tests"].MetaData.DropCollection(filesystem + ".chunks");
- }catch(MongoCommandException){}//if it fails it is because the collection isn't there to start with.
-
- }
-
- protected long CountChunks(string filesystem, Object fileid){
- return db["tests"][filesystem + ".chunks"].Count(new Document().Append("files_id", fileid));
}
-
}
}
View
39 MongoDB.GridFS.Tests/GridTestBase.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Configuration;
+using System.Text;
+
+using NUnit.Framework;
+
+using MongoDB.Driver;
+
+namespace MongoDB.GridFS
+{
+ public abstract class GridTestBase : MongoTestBase
+ {
+ /// <summary>
+ /// Comma separated list of collections to clean at startup.
+ /// </summary>
+ public abstract string TestFileSystems{get;}
+
+ /// <summary>
+ /// Turns the TestFileSystems string into a comma delimited set of collections
+ /// </summary>
+ public override string TestCollections {
+ get {
+ StringBuilder sb = new StringBuilder();
+ foreach(string fs in this.TestFileSystems.Split(',')){
+ sb.Append(fs + ".files,");
+ sb.Append(fs + ".chunks,");
+ }
+ sb.Remove(sb.Length - 1,1); //remove last ,
+ Console.WriteLine(sb.ToString());
+ return sb.ToString();
+ }
+ }
+
+ public long CountChunks(string filesystem, Object fileid){
+ return DB[filesystem + ".chunks"].Count(new Document().Append("files_id", fileid));
+ }
+
+ }
+}
View
10 MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.csproj
@@ -41,6 +41,7 @@
<Compile Include="GridFileInfoTest.cs" />
<Compile Include="GridFileStreamTest.cs" />
<Compile Include="GridFileTest.cs" />
+ <Compile Include="GridTestBase.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MongoDBDriver\MongoDB.Driver.csproj">
@@ -51,6 +52,15 @@
<Project>{B42DBBF9-0A1F-4749-9787-013BF8D8F435}</Project>
<Name>MongoDB.GridFS</Name>
</ProjectReference>
+ <ProjectReference Include="..\MongoDB.Net-Tests\MongoDB.Driver.Tests.csproj">
+ <Project>{C8BC95AB-25C6-4133-BC9F-8B6BB782CA02}</Project>
+ <Name>MongoDB.Driver.Tests</Name>
+ </ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+ <ItemGroup>
+ <None Include="MongoDB.GridFS.Tests.dll.config">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ </ItemGroup>
</Project>
View
6 MongoDB.GridFS.Tests/MongoDB.GridFS.Tests.dll.config
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+ <appSettings>
+ <add key="tests" value="Server=localhost:27017"/>
+ </appSettings>
+</configuration>
View
5 MongoDB.Net-Tests/MongoDB.Driver.Tests.csproj
@@ -55,6 +55,7 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\redist\nunit.framework.dll</HintPath>
</Reference>
+ <Reference Include="System.Configuration" />
</ItemGroup>
<ItemGroup>
<Compile Include="Bson\TestBsonBinary.cs" />
@@ -78,7 +79,6 @@
<None Include="test-data\tests.charreads.txt" />
<None Include="test-data\tests.reads.txt" />
<None Include="test-data\tests.smallreads.txt" />
- <Compile Include="TestMongoExceptions.cs" />
<Compile Include="TestOid.cs" />
<Compile Include="TestOidGenerator.cs" />
<Compile Include="Bson\TestBsonWriter.cs" />
@@ -91,6 +91,9 @@
<Compile Include="TestCollectionMetaData.cs" />
<Compile Include="TestBinary.cs" />
<Compile Include="Util\TestJsonUtils.cs" />
+ <None Include="MongoDB.Driver.Tests.dll.config">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MongoDBDriver\MongoDB.Driver.csproj">
View
6 MongoDB.Net-Tests/MongoDB.Driver.Tests.dll.config
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+ <appSettings>
+ <add key="tests" value="Server=localhost:27017"/>
+ </appSettings>
+</configuration>
View
26 MongoDB.Net-Tests/MongoTestBase.cs
@@ -1,4 +1,6 @@
using System;
+using System.Configuration;
+
using NUnit.Framework;
namespace MongoDB.Driver
@@ -19,20 +21,38 @@ public abstract class MongoTestBase
public abstract string TestCollections{get;}
+ /// <summary>
+ /// Override to add custom initialization code.
+ /// </summary>
+ public virtual void OnInit(){}
+
+ /// <summary>
+ /// Override to add custom code to invoke during the test end.
+ /// </summary>
+ public virtual void OnDispose(){}
+
+
+ /// <summary>
+ /// Sets up the test environment. You can either override this OnInit to add custom initialization.
+ /// </summary>
[TestFixtureSetUp]
public virtual void Init(){
- this.Mongo = new Mongo();
+ string connstr = ConfigurationManager.AppSettings["tests"];
+ if(String.IsNullOrEmpty(connstr)) throw new ArgumentNullException("Connection string not found.");
+ this.Mongo = new Mongo(connstr);
this.Mongo.Connect();
- cleanDB();
+ CleanDB();
+ OnInit();
}
[TestFixtureTearDown]
public virtual void Dispose(){
+ OnDispose();
this.Mongo.Disconnect();
}
- protected void cleanDB(){
+ protected void CleanDB(){
foreach(string col in this.TestCollections.Split(',')){
DB["$cmd"].FindOne(new Document(){{"drop", col.Trim()}});
Console.WriteLine("Dropping " + col);
View
215 MongoDB.Net-Tests/TestCollection.cs
@@ -5,90 +5,109 @@
namespace MongoDB.Driver
{
[TestFixture]
- public class TestCollection
+ public class TestCollection : MongoTestBase
{
- Mongo db = new Mongo();
private string pound = "\u00a3";
+ public override string TestCollections {
+ get {
+ return "inserts,updates,counts,counts_spec,finds,charreads";
+ }
+ }
+
+ public override void OnInit (){
+ IMongoCollection finds = DB["finds"];
+ for(int j = 1; j < 100; j++){
+ finds.Insert(new Document(){{"x", 4},{"h", "hi"},{"j", j}});
+ }
+ for(int j = 100; j < 105; j++){
+ finds.Insert(new Document(){{"x", 4},{"n", 1},{"j", j}});
+ }
+ IMongoCollection charreads = DB["charreads"];
+ charreads.Insert(new Document(){{"test", "1234" + pound + "56"}});
+
+ }
+
+
[Test]
public void TestFindOne(){
Document query = new Document();
query["j"] = 10;
- Document result = db["tests"]["reads"].FindOne(query);
+ Document result = DB["finds"].FindOne(query);
Assert.IsNotNull(result);
Assert.AreEqual(4, result["x"]);
Assert.AreEqual(10, result["j"]);
-
+
}
-
+
[Test]
public void TestFindOneNotThere(){
Document query = new Document();
query["not_there"] = 10;
- Document result = db["tests"]["reads"].FindOne(query);
+ Document result = DB["finds"].FindOne(query);
Assert.IsNull(result);
}
-
+
[Test]
public void TestFindNulls(){
Document query = new Document().Append("n",DBNull.Value);
- long numnulls = db["tests"]["smallreads"].Count(query);
- Assert.AreEqual(4,numnulls);
+ long numnulls = DB["finds"].Count(query);
+ Assert.AreEqual(99,numnulls);
}
-
+
[Test]
public void TestFindAttributeLimit(){
Document query = new Document();
query["j"] = 10;
Document fields = new Document();
fields["x"] = 1;
-
- ICursor c = db["tests"]["reads"].Find(query,-1,0,fields);
- foreach(Document result in c.Documents){
+
+ ICursor c = DB["finds"].Find(query,-1,0,fields);
+ foreach(Document result in c.Documents){
Assert.IsNotNull(result);
Assert.AreEqual(4, result["x"]);
- Assert.IsNull(result["j"]);
+ Assert.IsNull(result["j"]);
}
}
-
+
[Test]
public void TestFindGTRange(){
Document query = new Document();
query["j"] = new Document().Append("$gt",20);
-
- ICursor c = db["tests"]["reads"].Find(query);
- foreach(Document result in c.Documents){
+
+ ICursor c = DB["finds"].Find(query);
+ foreach(Document result in c.Documents){
Assert.IsNotNull(result);
Object j = result["j"];
Assert.IsTrue(Convert.ToDouble(j) > 20);
- }
+ }
}
-
+
[Test]
public void TestManualWhere(){
Document query = new Document().Append("$where", new Code("this.j % 2 == 0"));
- ICursor c = db["tests"]["reads"].Find(query);
- foreach(Document result in c.Documents){
+ ICursor c = DB["finds"].Find(query);
+ foreach(Document result in c.Documents){
Assert.IsNotNull(result);
Object j = result["j"];
- Assert.IsTrue((double)j % 2 == 0);
- }
+ Assert.IsTrue(Convert.ToInt32(j) % 2 == 0);
+ }
}
[Test]
public void TestFindWhereEquivalency(){
- IMongoCollection col = db["tests"]["reads"];
+ IMongoCollection col = DB["finds"];
Document lt = new Document().Append("j", new Document().Append("$lt", 5));
string where = "this.j < 5";
Document explicitWhere = new Document().Append("$where", new Code(where));
CodeWScope func = new CodeWScope("function() { return this.j < 5; }", new Document());
Document funcDoc = new Document().Append("$where", func);
-
+
Assert.AreEqual(4, CountDocs(col.Find(lt)), "Basic find didn't return 4 docs");
Assert.AreEqual(4, CountDocs(col.Find(where)), "String where didn't return 4 docs");
Assert.AreEqual(4, CountDocs(col.Find(explicitWhere)), "Explicit where didn't return 4 docs");
Assert.AreEqual(4, CountDocs(col.Find(funcDoc)), "Function where didn't return 4 docs");
}
-
+
private int CountDocs(ICursor cur){
int cnt = 0;
foreach(Document doc in cur.Documents){
@@ -98,65 +117,65 @@ public class TestCollection
}
[Test]
public void TestWhere(){
- ICursor c = db["tests"]["reads"].Find("this.j % 2 == 0");
- foreach(Document result in c.Documents){
+ ICursor c = DB["finds"].Find("this.j % 2 == 0");
+ foreach(Document result in c.Documents){
Assert.IsNotNull(result);
Object j = result["j"];
- Assert.IsTrue((double)j % 2 == 0);
- }
- }
+ Assert.IsTrue(Convert.ToInt32(j) % 2 == 0);
+ }
+ }
[Test]
public void TestFindOneObjectContainingUKPound(){
Document query = new Document();
- Document result = db["tests"]["charreads"].FindOne(query);
+ Document result = DB["charreads"].FindOne(query);
Assert.IsNotNull(result);
Assert.IsTrue(result.Contains("test"));
Assert.AreEqual("1234£56",result["test"]);
}
-
+
[Test]
public void TestSimpleInsert(){
- IMongoCollection inserts = db["tests"]["inserts"];
+ IMongoCollection inserts = DB["inserts"];
Document indoc = new Document();
indoc["song"] = "Palmdale";
indoc["artist"] = "Afroman";
indoc["year"] = 1999;
inserts.Insert(indoc);
-
+
Document result = inserts.FindOne(new Document().Append("song","Palmdale"));
Assert.IsNotNull(result);
Assert.AreEqual(1999,result["year"]);
}
-
+
[Test]
public void TestReallySimpleInsert(){
- IMongoCollection inserts = db["tests"]["inserts"];
+ IMongoCollection inserts = DB["inserts"];
Document indoc = new Document();
indoc["y"] = 1;
indoc["x"] = 2;
inserts.Insert(indoc);
-
+
Document result = inserts.FindOne(new Document().Append("x",2));
Assert.IsNotNull(result);
Assert.AreEqual(1,result["y"]);
}
-
+
[Test]
public void TestPoundSymbolInsert(){
- IMongoCollection inserts = db["tests"]["inserts"];
+ IMongoCollection inserts = DB["inserts"];
Document indoc = new Document().Append("x","1234" + pound + "56").Append("y",1);;
inserts.Insert(indoc);
Document result = inserts.FindOne(new Document().Append("x","1234" + pound + "56"));
Assert.IsNotNull(result);
- Assert.AreEqual(1,result["y"]);
+ Assert.AreEqual(1,result["y"]);
}
-
+
[Test]
public void TestArrayInsert(){
- IMongoCollection inserts = db["tests"]["inserts"];
+ IMongoCollection inserts = DB["inserts"];
Document indoc1 = new Document();
indoc1["song"] = "The Axe";
indoc1["artist"] = "Tinsley Ellis";
@@ -166,22 +185,22 @@ public class TestCollection
indoc2["song"] = "The Axe2";
indoc2["artist"] = "Tinsley Ellis2";
indoc2["year"] = 2008;
-
+
inserts.Insert(new Document[]{indoc1,indoc2});
-
+
Document result = inserts.FindOne(new Document().Append("song","The Axe"));
Assert.IsNotNull(result);
Assert.AreEqual(2006,result["year"]);
-
+
result = inserts.FindOne(new Document().Append("song","The Axe2"));
Assert.IsNotNull(result);
- Assert.AreEqual(2008,result["year"]);
- }
-
+ Assert.AreEqual(2008,result["year"]);
+ }
+
[Test]
public void TestInsertOfArray(){
OidGenerator ogen = new OidGenerator();
- IMongoCollection inserts = db["tests"]["inserts"];
+ IMongoCollection inserts = DB["inserts"];
Document album = new Document();
album["_id"] = ogen.Generate();
album["artist"] = "Popa Chubby";
@@ -194,79 +213,79 @@ public class TestCollection
new Document().Append("title", "Grown Man Crying Blues").Append("length", "8:09").Append("_id", ogen.Generate()),
};
inserts.Insert(album);
-
+
Document result = inserts.FindOne(new Document().Append("songs.title","Deliveries After Dark"));
Assert.IsNotNull(result);
-
+
Assert.AreEqual(album.ToString(), result.ToString());
}
-
+
[Test]
public void TestDelete(){
- IMongoCollection deletes = db["tests"]["deletes"];
+ IMongoCollection deletes = DB["deletes"];
Document doc = new Document();
doc["y"] = 1;
doc["x"] = 2;
deletes.Insert(doc);
-
+
Document selector = new Document().Append("x",2);
-
+
Document result = deletes.FindOne(selector);
Assert.IsNotNull(result);
Assert.AreEqual(1,result["y"]);
-
+
deletes.Delete(selector);
result = deletes.FindOne(selector);
Assert.IsNull(result,"Shouldn't have been able to find a document that was deleted");
-
- }
-
+
+ }
+
[Test]
public void TestUpdateUpsertNotExisting(){
- IMongoCollection updates = db["tests"]["updates"];
+ IMongoCollection updates = DB["updates"];
Document doc = new Document();
doc["First"] = "Sam";
doc["Last"] = "CorderNE";
-
+
updates.Update(doc);
Document selector = new Document().Append("Last", "CorderNE");
Document result = updates.FindOne(selector);
Assert.IsNotNull(result);
Assert.AreEqual("Sam", result["First"]);
}
-
+
[Test]
public void TestUpdateUpsertExisting(){
- IMongoCollection updates = db["tests"]["updates"];
+ IMongoCollection updates = DB["updates"];
Document doc = new Document();
doc["First"] = "Mtt";
doc["Last"] = "Brewer";
-
+
updates.Insert(doc);
-
+
Document selector = new Document().Append("Last", "Brewer");
doc = updates.FindOne(selector);
Assert.IsNotNull(doc);
Assert.AreEqual("Mtt", doc["First"]);
Assert.IsNotNull(doc["_id"]);
-
+
doc["First"] = "Matt";
updates.Update(doc);
-
+
Document result = updates.FindOne(selector);
Assert.IsNotNull(result);
Assert.AreEqual("Matt", result["First"]);
-
- }
-
+
+ }
+
[Test]
public void TestUpdateMany(){
- IMongoCollection updates = db["tests"]["updates"];
-
+ IMongoCollection updates = DB["updates"];
+
updates.Insert(new Document().Append("Last", "Cordr").Append("First","Sam"));
updates.Insert(new Document().Append("Last", "Cordr").Append("First","Sam2"));
updates.Insert(new Document().Append("Last", "Cordr").Append("First","Sam3"));
-
+
Document selector = new Document().Append("Last", "Cordr");
ICursor results = updates.Find(selector);
bool found = false;
@@ -276,74 +295,52 @@ public class TestCollection
}
Assert.IsTrue(found,"Should have found docs inserted for TestUpdateMany");
Assert.AreEqual(3, updates.Count(selector), "Didn't find all Documents inserted for TestUpdateMany with Selector");
-
+
//Document updateData = new Document().Append("$set", new Document().Append("Last", "Corder2"));
Document updateData = new Document().Append("Last", "Corder2");
updates.UpdateAll(updateData, selector);
-
+
selector["Last"] = "Corder2";
Assert.AreEqual(3, updates.Count(selector), "Not all Cordr documents were updated");
-
+
results = updates.Find(selector);
found = false;
foreach(Document doc in results.Documents){
Assert.AreEqual("Corder2", doc["Last"]);
Assert.IsNotNull(doc["First"],"First name should not disappear");
found = true;
}
- Assert.IsTrue(found,"Should have found docs updated for TestMany");
+ Assert.IsTrue(found,"Should have found docs updated for TestMany");
}
-
+
[Test]
public void TestCount(){
- IMongoCollection counts = db["tests"]["counts"];
+ IMongoCollection counts = DB["counts"];
int top = 100;
for(int i = 0; i < top; i++){
counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", i));
}
long cnt = counts.Count();
Assert.AreEqual(top,cnt, "Count not the same as number of inserted records");
}
-
+
[Test]
public void TestCountWithSpec(){
- IMongoCollection counts = db["tests"]["counts_spec"];
+ IMongoCollection counts = DB["counts_spec"];
counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", 1));
counts.Insert(new Document().Append("Last", "Cordr").Append("First","Sam").Append("cnt", 2));
counts.Insert(new Document().Append("Last", "Corder").Append("First","Sam").Append("cnt", 3));
-
+
Assert.AreEqual(2, counts.Count(new Document().Append("Last", "Cordr")));
Assert.AreEqual(1, counts.Count(new Document().Append("Last", "Corder")));
Assert.AreEqual(0, counts.Count(new Document().Append("Last", "Brown")));
-
+
}
-
+
[Test]
public void TestCountInvalidCollection(){
- IMongoCollection counts = db["tests"]["counts_wtf"];
+ IMongoCollection counts = DB["counts_wtf"];
Assert.AreEqual(0, counts.Count());
}
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- cleanDB();
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- //cleanDB();
- db.Disconnect();
- }
-
- protected void cleanDB(){
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","inserts"));
-
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","updates"));
-
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","counts"));
-
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","counts_spec"));
- }
}
}
View
46 MongoDB.Net-Tests/TestCollectionMetaData.cs
@@ -7,23 +7,25 @@
namespace MongoDB.Driver
{
[TestFixture]
- public class TestCollectionMetaData
+ public class TestCollectionMetaData : MongoTestBase
{
Mongo db = new Mongo();
-
+ public override string TestCollections {
+ get {
+ return "indextests";
+ }
+ }
+
[Test]
public void TestGetOptions(){
- CollectionMetaData cmd = db["tests"]["reads"].MetaData;
+ CollectionMetaData cmd = DB["reads"].MetaData;
Document options = cmd.Options;
- Assert.IsNotNull(options);
-
- System.Console.WriteLine(options.ToString());
-
+ Assert.IsNotNull(options);
}
[Test]
public void TestGetIndexes(){
- CollectionMetaData cmd = db["tests"]["indextests"].MetaData;
+ CollectionMetaData cmd = DB["indextests"].MetaData;
Dictionary<string, Document> indexes = cmd.Indexes;
Assert.IsNotNull(indexes);
@@ -35,52 +37,40 @@ public class TestCollectionMetaData
[Test]
public void TestCreateIndex(){
- CollectionMetaData cmd = db["tests"]["indextests"].MetaData;
+ CollectionMetaData cmd = DB["indextests"].MetaData;
cmd.CreateIndex("lastnames", new Document().Append("lname", IndexOrder.Ascending), false);
Dictionary<string, Document> indexes = cmd.Indexes;
Assert.IsNotNull(indexes["lastnames"]);
}
[Test]
public void TestCreateIndexNoNames(){
- CollectionMetaData cmd = db["tests"]["indextests"].MetaData;
+ CollectionMetaData cmd = DB["indextests"].MetaData;
cmd.CreateIndex(new Document().Append("lname", IndexOrder.Ascending).Append("fname",IndexOrder.Ascending), true);
Dictionary<string, Document> indexes = cmd.Indexes;
Assert.IsNotNull(indexes["_lname_fname_unique_"]);
}
[Test]
public void TestDropIndex(){
- CollectionMetaData cmd = db["tests"]["indextests"].MetaData;
+ CollectionMetaData cmd = DB["indextests"].MetaData;
cmd.CreateIndex("firstnames", new Document().Append("fname", IndexOrder.Ascending), false);
Dictionary<string, Document> indexes = cmd.Indexes;
Assert.IsNotNull(indexes["firstnames"]);
cmd.DropIndex("firstnames");
Assert.IsFalse(cmd.Indexes.ContainsKey("firstnames"));
}
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- initDB();
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- db.Disconnect();
- }
-
- protected void initDB(){
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","indextests"));
- IMongoCollection its = db["tests"]["indextests"];
+
+ public override void OnInit (){
+ IMongoCollection its = DB["indextests"];
Document doc = new Document();
its.Insert(createDoc("S","A","Anderson","OH"));
its.Insert(createDoc("T","B","Delhi","OH"));
its.Insert(createDoc("F","B","Cincinnati","OH"));
its.Insert(createDoc("U","D","Newtown","OH"));
- its.Insert(createDoc("J","E","Newport","KY"));
-
+ its.Insert(createDoc("J","E","Newport","KY"));
}
+
protected Document createDoc(string fname, string lname, string city, string state){
Document doc = new Document();
View
53 MongoDB.Net-Tests/TestConcurrency.cs
@@ -8,20 +8,33 @@ namespace MongoDB.Driver
{
[TestFixture()]
- public class TestConcurrency
+ public class TestConcurrency :MongoTestBase
{
/*
* Having all of these tests enabled will slow the test suite down a lot. In the future it may be better
* to have them ifdef'ed so that the long running tests can be executed by just setting a compile flag.
*/
Mongo db = new Mongo();
+ public override string TestCollections {
+ get {
+ return "threadinserts,threadreadinserts,threadsmallreads";
+ }
+ }
+ public override void OnInit (){
+ Collection col = (Collection)DB["threadsmallreads"];
+ for(int j = 0; j < 4; j++){
+ col.Insert(new Document(){{"x", 4},{"j", j}});
+ }
+ }
+
+
//[Test]
public void TestMultiThreadedWrites (){
Mongo db = new Mongo();
db.Connect();
- IMongoCollection col = db["tests"]["threadinserts"];
+ IMongoCollection col = DB["threadinserts"];
List<string> identifiers = new List<string>{"A", "B", "C", "D"};
List<Thread> threads = new List<Thread>();
@@ -48,12 +61,13 @@ public class TestConcurrency
Mongo db = new Mongo();
db.Connect();
- List<string> colnames = new List<string>{"smallreads", "smallreads", "smallreads", "smallreads"};
+ List<string> colnames = new List<string>{"threadsmallreads", "threadsmallreads",
+ "threadsmallreads", "threadsmallreads"};
List<Thread> threads = new List<Thread>();
List<Reader> readers = new List<Reader>();
int iterations = 50;
foreach(string colname in colnames){
- Reader r = new Reader{Iterations = iterations, Collection = db["tests"][colname]};
+ Reader r = new Reader{Iterations = iterations, Collection = DB[colname]};
readers.Add(r);
ThreadStart ts = new ThreadStart(r.DoReads);
Thread thread = new Thread(ts);
@@ -63,7 +77,7 @@ public class TestConcurrency
try{
//Connection still alive?
- db["tests"]["smallreads"].Count();
+ DB["smallreads"].Count();
}catch(Exception e){
Assert.Fail(e.Message);
}
@@ -77,10 +91,11 @@ public class TestConcurrency
Mongo db = new Mongo();
db.Connect();
- IMongoCollection col = db["tests"]["threadreadinserts"];
+ IMongoCollection col = DB["threadreadinserts"];
List<string> identifiers = new List<string>{"A", "B", "C", "D"};
- List<string> colnames = new List<string>{"smallreads", "smallreads", "smallreads", "smallreads"};
+ List<string> colnames = new List<string>{"threadsmallreads", "threadsmallreads",
+ "threadsmallreads", "threadsmallreads"};
List<Thread> threads = new List<Thread>();
List<Reader> readers = new List<Reader>();
int writeiterations = 100;
@@ -92,7 +107,7 @@ public class TestConcurrency
threads.Add(thread);
}
foreach(string colname in colnames){
- Reader r = new Reader{Iterations = readiterations, Collection = db["tests"][colname]};
+ Reader r = new Reader{Iterations = readiterations, Collection = DB[colname]};
readers.Add(r);
ThreadStart ts = new ThreadStart(r.DoReads);
Thread thread = new Thread(ts);
@@ -109,19 +124,7 @@ public class TestConcurrency
Assert.AreEqual(readiterations, r.Count, "A reader did not read everytime.");
}
}
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- cleanDB();
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- //cleanDB();
- db.Disconnect();
- }
-
+
protected void RunAndWait(List<Thread> threads){
foreach(Thread t in threads){
t.Start();
@@ -137,13 +140,7 @@ public class TestConcurrency
}
}
}
- }
-
- protected void cleanDB(){
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","threadinserts"));
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","threadreadinserts"));
- }
-
+ }
}
public class Inserter{
View
58 MongoDB.Net-Tests/TestCursor.cs
@@ -8,14 +8,33 @@
namespace MongoDB.Driver
{
[TestFixture]
- public class TestCursor
+ public class TestCursor : MongoTestBase
{
- Mongo db = new Mongo();
+ public override string TestCollections {
+ get {
+ return "sorts,hintindex,smallreads,reads";
+ }
+ }
+ public override void OnInit (){
+ //smallreads
+ IMongoCollection smallreads = DB["smallreads"];
+ for(int j = 1; j < 5; j++){
+ smallreads.Insert(new Document(){{"x", 4},{"j", j}});
+ }
+ smallreads.Insert(new Document(){{"x", 4}, {"j", 5}, {"n", 1}});
+
+ IMongoCollection reads = DB["reads"];
+ for(int j = 1; j < 10000; j++){
+ reads.Insert(new Document(){{"x", 4},{"h", "hi"},{"j", j}});
+ }
+ }
+
+
[Test]
public void TestCanReadSmall()
{
- ICursor c = db["tests"]["smallreads"].FindAll();
+ ICursor c = DB["smallreads"].FindAll();
Assert.IsNotNull(c,"Cursor shouldn't be null");
int reads = 0;
@@ -28,7 +47,7 @@ public void TestCanReadSmall()
[Test]
public void TestCanReadMore(){
- ICursor c = db["tests"]["reads"].FindAll();
+ ICursor c = DB["reads"].FindAll();
Assert.IsNotNull(c,"Cursor shouldn't be null");
int reads = 0;
@@ -51,7 +70,7 @@ public void TestCanReadSmall()
[Test]
public void TestCanReadAndKillCursor()
{
- ICursor c = db["tests"]["reads"].FindAll();
+ ICursor c = DB["reads"].FindAll();
Assert.IsNotNull(c,"Cursor shouldn't be null");
foreach(Document doc in c.Documents){
@@ -63,7 +82,7 @@ public void TestCanReadAndKillCursor()
[Test]
public void TestCanLimit(){
- ICursor c = db["tests"]["reads"].FindAll().Limit(5);
+ ICursor c = DB["reads"].FindAll().Limit(5);
Assert.IsNotNull(c,"Cursor shouldn't be null");
int reads = 0;
@@ -76,7 +95,7 @@ public void TestCanReadAndKillCursor()
[Test]
public void TestSort(){
- IMongoCollection sorts = db["tests"]["sorts"];
+ IMongoCollection sorts = DB["sorts"];
int[] randoms = new int[]{4,6,8,9,1,3,2,5,7,0};
foreach(int x in randoms){
sorts.Insert(new Document().Append("x", randoms[x]));
@@ -98,15 +117,15 @@ public void TestCanReadAndKillCursor()
[Test]
public void TestExplain(){
- Document exp = db["tests"]["reads"].FindAll().Limit(5).Skip(5).Sort("x").Explain();
+ Document exp = DB["reads"].FindAll().Limit(5).Skip(5).Sort("x").Explain();
Assert.IsTrue(exp.Contains("cursor"));
Assert.IsTrue(exp.Contains("n"));
Assert.IsTrue(exp.Contains("nscanned"));
}
[Test]
public void TestHint(){
- IMongoCollection reads = db["tests"]["reads"];
+ IMongoCollection reads = DB["reads"];
Document hint = new Document().Append("x",IndexOrder.Ascending);
Document exp = reads.FindAll().Hint(hint).Explain();
@@ -119,26 +138,5 @@ public void TestCanReadAndKillCursor()
Assert.IsTrue(exp.Contains("n"));
Assert.IsTrue(exp.Contains("nscanned"));
}
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- cleanDB();
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- db.Disconnect();
- }
-
- protected void cleanDB(){
- try{
- db["tests"].MetaData.DropCollection("sorts");
- }catch(Exception){}
- try{
- db["tests"]["reads"].MetaData.DropIndex("hintindex");
- }catch(Exception){}
-
- }
}
}
View
83 MongoDB.Net-Tests/TestDatabase.cs
@@ -5,44 +5,54 @@
namespace MongoDB.Driver
{
[TestFixture]
- public class TestDatabase
+ public class TestDatabase : MongoTestBase
{
- Mongo mongo = new Mongo();
- Database db;
+ public override string TestCollections {
+ get {
+ return "refs,noerror,errcol,preverror";
+ }
+ }
+
+ public override void OnInit ()
+ {
+ base.OnInit();
+ }
[Test]
public void TestFollowReference(){
- Database tests = mongo["tests"];
+ IMongoCollection refs = DB["refs"];
Oid id = new Oid("4a7067c30a57000000008ecb");
- DBRef rf = new DBRef("reads", id);
+ string msg = "this has an oid key";
+ Document doc = new Document(){{"_id", id},{"msg", msg}};
+ refs.Insert(doc);
+
+ DBRef rf = new DBRef("refs", id);
- Document target = tests.FollowReference(rf);
+ Document target = DB.FollowReference(rf);
Assert.IsNotNull(target, "FollowReference returned null");
- Assert.IsTrue(target.Contains("j"));
- Assert.AreEqual((double)9980, (double)target["j"]);
+ Assert.IsTrue(target.Contains("msg"));
+ Assert.AreEqual(msg, target["msg"]);
}
[Test]
public void TestFollowNonReference(){
- Database tests = mongo["tests"];
Oid id = new Oid("BAD067c30a57000000008ecb");
- DBRef rf = new DBRef("reads", id);
+ DBRef rf = new DBRef("refs", id);
- Document target = tests.FollowReference(rf);
+ Document target = DB.FollowReference(rf);
Assert.IsNull(target, "FollowReference returned wasn't null");
}
[Test]
public void TestReferenceNonOid(){
- Database tests = mongo["tests"];
- IMongoCollection refs = tests["refs"];
+ IMongoCollection refs = DB["refs"];
Document doc = new Document().Append("_id",123).Append("msg", "this has a non oid key");
refs.Insert(doc);
DBRef rf = new DBRef("refs",123);
- Document recv = tests.FollowReference(rf);
+ Document recv = DB.FollowReference(rf);
Assert.IsNotNull(recv);
Assert.IsTrue(recv.Contains("msg"));
@@ -51,23 +61,23 @@ public class TestDatabase
[Test]
public void TestGetCollectionNames(){
- List<String> names = mongo["tests"].GetCollectionNames();
+ List<String> names = DB.GetCollectionNames();
Assert.IsNotNull(names,"No collection names returned");
Assert.IsTrue(names.Count > 0);
Assert.IsTrue(names.Contains("tests.inserts"));
}
[Test]
public void TestEvalNoScope(){
- Document result = db.Eval("function(){return 3;}");
+ Document result = DB.Eval("function(){return 3;}");
Assert.AreEqual(3, result["retval"]);
}
[Test]
public void TestEvalWithScope(){
int val = 3;
Document scope = new Document().Append("x",val);
- Document result = db.Eval("function(){return x;}", scope);
+ Document result = DB.Eval("function(){return x;}", scope);
Assert.AreEqual(val, result["retval"]);
}
@@ -77,70 +87,51 @@ public class TestDatabase
int y = 4;
string func = "adder = function(a, b){return a + b;}; return adder(x,y)";
Document scope = new Document().Append("x",x).Append("y", y);
- Document result = db.Eval(func, scope);
+ Document result = DB.Eval(func, scope);
Console.Out.WriteLine(result.ToString());
Assert.AreEqual(x + y, result["retval"]);
}
[Test]
public void TestGetLastErrorNoError(){
- db["noerror"].Insert(new Document(){{"a",1},{"b",2}});
- Document error = db.GetLastError();
+ DB["noerror"].Insert(new Document(){{"a",1},{"b",2}});
+ Document error = DB.GetLastError();
Assert.AreEqual(DBNull.Value, error["err"]);
}
[Test]
public void TestGetLastError(){
- IMongoCollection errcol = db["errcol"];
+ IMongoCollection errcol = DB["errcol"];
errcol.MetaData.CreateIndex(new Document(){{"x", IndexOrder.Ascending}}, true);
Document dup = new Document(){{"x",1},{"y",2}};
errcol.Insert(dup);
- Document error = db.GetLastError();
+ Document error = DB.GetLastError();
Assert.AreEqual(DBNull.Value, error["err"]);
errcol.Insert(dup);
- error = db.GetLastError();
+ error = DB.GetLastError();
Assert.IsFalse(DBNull.Value == error["err"]);
}
[Test]
public void TestGetPrevError(){
- IMongoCollection col = db["preverror"];
+ IMongoCollection col = DB["preverror"];
col.MetaData.CreateIndex(new Document(){{"x", IndexOrder.Ascending}},true);
List<Document> docs = new List<Document>();
for(int x = 0; x < 10; x++){
docs.Add(new Document(){{"x",x},{"y",2}});
}
docs.Add(new Document(){{"x",1},{"y",4}}); //the dupe
- db.ResetError();
- Assert.AreEqual(DBNull.Value, db.GetLastError()["err"]);
+ DB.ResetError();
+ Assert.AreEqual(DBNull.Value, DB.GetLastError()["err"]);
col.Insert(docs);
- Document error = db.GetLastError();
+ Document error = DB.GetLastError();
Assert.IsFalse(DBNull.Value == error["err"]);
- Console.WriteLine(error);
- }
- [TestFixtureSetUp]
- public void Init(){
- mongo.Connect();
- db = mongo["tests"];
- cleanDB();
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- mongo.Disconnect();
- }
-
- protected void cleanDB(){
- mongo["tests"]["$cmd"].FindOne(new Document().Append("drop","refs"));
- mongo["tests"]["$cmd"].FindOne(new Document().Append("drop","noerror"));
- mongo["tests"]["$cmd"].FindOne(new Document().Append("drop","errcol"));
- mongo["tests"]["$cmd"].FindOne(new Document().Append("drop","preverror"));
}
}
}
View
46 MongoDB.Net-Tests/TestDatabaseJS.cs
@@ -7,15 +7,28 @@ namespace MongoDB.Driver{
[TestFixture()]
- public class TestDatabaseJS
+ public class TestDatabaseJS : MongoTestBase
{
- Mongo db = new Mongo();
- Database tests;
DatabaseJS js;
+ public override string TestCollections {
+ get {
+ return "jsreads";
+ }
+ }
+
+ public override void OnInit (){
+ DB["system.js"].Delete(new Document());
+ js = DB.JS;
+
+ IMongoCollection jsreads = DB["jsreads"];
+ for(int j = 1; j < 10; j++){
+ jsreads.Insert(new Document(){{"j", j}});
+ }
+ }
[Test()]
public void TestCanGetDatabaseJSObject(){
- Assert.IsNotNull(tests.JS);
+ Assert.IsNotNull(DB.JS);
}
[Test()]
@@ -158,7 +171,7 @@ public class TestDatabaseJS
public void TestExec(){
js.Add("lt4", new Code("function(doc){return doc.j < 4;}"));
int cnt = 0;
- foreach(Document doc in tests["reads"].Find("lt4(this)").Documents){
+ foreach(Document doc in DB["reads"].Find("lt4(this)").Documents){
cnt++;
}
Assert.AreEqual(3,cnt);
@@ -170,34 +183,15 @@ public class TestDatabaseJS
int cnt = 0;
Document scope = new Document().Append("limit", 5);
Document query = new Document().Append("$where", new CodeWScope("lt(this)",scope));
- foreach(Document doc in tests["reads"].Find(query).Documents){
+ foreach(Document doc in DB["jsreads"].Find(query).Documents){
cnt++;
}
Assert.AreEqual(4,cnt);
}
-
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- initDB();
- tests = db["tests"];
- js = tests.JS;
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- db.Disconnect();
- }
-
- protected void initDB(){
- //drop any previously created collections.
- db["tests"]["system.js"].Delete(new Document());
- }
protected void AddFunction(string name){
Code func = new Code("function(x,y){return x + y;}");
- tests["system.js"].Insert(new Document().Append("_id", name).Append("value", func));
+ DB["system.js"].Insert(new Document().Append("_id", name).Append("value", func));
}
}
}
View
59 MongoDB.Net-Tests/TestDatabaseMetaData.cs
@@ -6,92 +6,75 @@
namespace MongoDB.Driver
{
[TestFixture]
- public class TestDatabaseMetaData
+ public class TestDatabaseMetaData : MongoTestBase
{
- Mongo db = new Mongo();
+ public override string TestCollections {
+ get {
+ return "creatednoopts,createdcapped,createdinvalid";
+ }
+ }
+
+ public override void OnInit () {
+ //Add any new collections ones to work on.
+ DB["$cmd"].FindOne(new Document().Append("create","todrop"));
+ }
[Test]
public void TestCreateCollectionNoOptions(){
- Database tests = db["tests"];
- tests.MetaData.CreateCollection("creatednoopts");
+ DB.MetaData.CreateCollection("creatednoopts");
- List<String> names = tests.GetCollectionNames();
+ List<String> names = DB.GetCollectionNames();
Assert.IsTrue(names.Contains("tests.creatednoopts"));
}
[Test]
public void TestCreateCollectionWithOptions(){
- Database tests = db["tests"];
Document options = new Document().Append("capped",true).Append("size",10000);
- tests.MetaData.CreateCollection("createdcapped",options);
+ DB.MetaData.CreateCollection("createdcapped",options);
- List<String> names = tests.GetCollectionNames();
+ List<String> names = DB.GetCollectionNames();
Assert.IsTrue(names.Contains("tests.createdcapped"));
}
[Test]
public void TestCreateCollectionWithInvalidOptions(){
- Database tests = db["tests"];
Document options = new Document().Append("invalidoption",true);
- tests.MetaData.CreateCollection("createdinvalid",options);
+ DB.MetaData.CreateCollection("createdinvalid",options);
- List<String> names = tests.GetCollectionNames();
+ List<String> names = DB.GetCollectionNames();
Assert.IsTrue(names.Contains("tests.createdinvalid"));
}
[Test]
public void TestDropCollection(){
- Database tests = db["tests"];
- bool dropped = tests.MetaData.DropCollection("todrop");
+ bool dropped = DB.MetaData.DropCollection("todrop");
Assert.IsTrue(dropped,"Dropped was false");
- List<String> names = tests.GetCollectionNames();
+ List<String> names = DB.GetCollectionNames();
Assert.IsFalse(names.Contains("tests.todrop"));
}
[Test]
public void TestDropInvalidCollection(){
- Database tests = db["tests"];
bool thrown = false;
try{
- tests.MetaData.DropCollection("todrop_notexists");
+ DB.MetaData.DropCollection("todrop_notexists");
}catch(MongoCommandException){
thrown = true;
}
Assert.IsTrue(thrown,"Command exception should have been thrown");
- List<String> names = tests.GetCollectionNames();
+ List<String> names = DB.GetCollectionNames();
Assert.IsFalse(names.Contains("tests.todrop_notexists"));
}
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- initDB();
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- db.Disconnect();
- }
- protected void initDB(){
- //drop any previously created collections.
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","creatednoopts"));
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","createdcapped"));
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","createdinvalid"));
-
- //Add any new ones to work on.
- db["tests"]["$cmd"].FindOne(new Document().Append("create","todrop"));
-
-
- }
}
}
View
48 MongoDB.Net-Tests/TestMapReduce.cs
@@ -5,11 +5,9 @@
namespace MongoDB.Driver
{
[TestFixture()]
- public class TestMapReduce
+ public class TestMapReduce : MongoTestBase
{
- Mongo db = new Mongo();
- Database tests;
- Collection mrcol;
+ IMongoCollection mrcol;
string mapfunction = "function(){\n" +
" this.tags.forEach(\n" +
" function(z){\n" +
@@ -23,6 +21,21 @@ public class TestMapReduce
" return { count : total };\n" +
"};";
+ public override string TestCollections {
+ get {
+ return "mr";
+ }
+ }
+
+ public override void OnInit (){
+ mrcol = DB["mr"];
+ mrcol.Insert(new Document().Append("_id", 1).Append("tags", new String[]{"dog", "cat"}));
+ mrcol.Insert(new Document().Append("_id", 2).Append("tags", new String[]{"dog"}));
+ mrcol.Insert(new Document().Append("_id", 3).Append("tags", new String[]{"mouse", "cat", "dog"}));
+ mrcol.Insert(new Document().Append("_id", 4).Append("tags", new String[]{}));
+
+ }
+
[Test()]
public void TestGetMapReduceObject(){
@@ -39,34 +52,7 @@ public class TestMapReduce
mr.Execute();
Assert.IsNotNull(mr.Result);
}
-
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- tests = db["tests"];
- mrcol = (Collection)tests["mr"];
-
- CleanDB();
- SetupCollection();
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- //cleanDB();
- db.Disconnect();
- }
-
- protected void CleanDB(){
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","mr"));
- }
- protected void SetupCollection(){
- mrcol.Insert(new Document().Append("_id", 1).Append("tags", new String[]{"dog", "cat"}));
- mrcol.Insert(new Document().Append("_id", 2).Append("tags", new String[]{"dog"}));
- mrcol.Insert(new Document().Append("_id", 3).Append("tags", new String[]{"mouse", "cat", "dog"}));
- mrcol.Insert(new Document().Append("_id", 4).Append("tags", new String[]{}));
- }
}
}
View
54 MongoDB.Net-Tests/TestMapReduceBuilder.cs
@@ -6,14 +6,10 @@
namespace MongoDB.Driver
{
-
-
[TestFixture()]
- public class TestMapReduceBuilder
+ public class TestMapReduceBuilder : MongoTestBase
{
- Mongo db = new Mongo();
- Database tests;
- Collection mrcol;
+ IMongoCollection mrcol;
string mapfunction = "function(){\n" +
" this.tags.forEach(\n" +
" function(z){\n" +
@@ -27,6 +23,19 @@ public class TestMapReduceBuilder
" return { count : total };\n" +
"};";
+ public override string TestCollections {
+ get {
+ return "mr";
+ }
+ }
+
+ public override void OnInit (){
+ mrcol = DB["mr"];
+ mrcol.Insert(new Document().Append("_id", 1).Append("tags", new String[]{"dog", "cat"}));
+ mrcol.Insert(new Document().Append("_id", 2).Append("tags", new String[]{"dog"}));
+ mrcol.Insert(new Document().Append("_id", 3).Append("tags", new String[]{"mouse", "cat", "dog"}));
+ mrcol.Insert(new Document().Append("_id", 4).Append("tags", new String[]{}));
+ }
[Test()]
public void TestCreateMapReduceWithStringFunctions(){
@@ -81,37 +90,10 @@ public class TestMapReduceBuilder
MapReduce mr = mrb.Execute();
Assert.IsNotNull(mr.Result);
Assert.IsTrue(mr.Result.Ok);
- tempcollname = tests.Name + "." + mr.Result.CollectionName;
- Assert.IsTrue(tests.GetCollectionNames().Contains(tempcollname));
+ tempcollname = DB.Name + "." + mr.Result.CollectionName;
+ Assert.IsTrue(DB.GetCollectionNames().Contains(tempcollname));
}
- Assert.IsFalse(tests.GetCollectionNames().Contains(tempcollname));
- }
-
- [TestFixtureSetUp]
- public void Init(){
- db.Connect();
- tests = db["tests"];
- mrcol = (Collection)tests["mr"];
-
- CleanDB();
- SetupCollection();
- }
-
- [TestFixtureTearDown]
- public void Dispose(){
- //cleanDB();
- db.Disconnect();
- }
-
- protected void CleanDB(){
- db["tests"]["$cmd"].FindOne(new Document().Append("drop","mr"));
- }
-
- protected void SetupCollection(){
- mrcol.Insert(new Document().Append("_id", 1).Append("tags", new String[]{"dog", "cat"}));
- mrcol.Insert(new Document().Append("_id", 2).Append("tags", new String[]{"dog"}));
- mrcol.Insert(new Document().Append("_id", 3).Append("tags", new String[]{"mouse", "cat", "dog"}));
- mrcol.Insert(new Document().Append("_id", 4).Append("tags", new String[]{}));
+ Assert.IsFalse(DB.GetCollectionNames().Contains(tempcollname));
}
}
}
View
12 MongoDB.Net-Tests/TestMongo.cs
@@ -1,34 +1,32 @@
-
using System;
+using System.Configuration;
using NUnit.Framework;
using MongoDB.Driver;
namespace MongoDB.Driver
{
-
-
[TestFixture()]
public class TestMongo
{
-
+ string connectionString = ConfigurationManager.AppSettings["tests"];
[Test()]
public void TestDefaults()
{
- Mongo m = new Mongo();
+ Mongo m = new Mongo(); //Connection string not needed since connect not called and it would screw up the test.
Assert.AreEqual(string.Empty, m.ConnectionString);
}
[Test()]
public void TestExplicitConnection(){
- Mongo m = new Mongo();
+ Mongo m = new Mongo(connectionString);
Assert.IsTrue(m.Connect());
}
[Test()]
public void TestThatConnectMustBeCalled(){
- Mongo m = new Mongo();
+ Mongo m = new Mongo(connectionString);
bool thrown = false;
try{
Database db = m["admin"];
View
17 MongoDB.Net-Tests/TestMongoExceptions.cs
@@ -1,17 +0,0 @@
-using NUnit.Framework;
-
-namespace MongoDB.Driver
-{
- [TestFixture]
- public class TestMongoCommException
- {
- [Test]
- public void TestThrow(){
- try{
-
- }catch(MongoCommException){
- //Assert.AreEqual("localhost", mce.ConnectionString);
- }
- }
- }
-}
View
2 MongoDB.Net-Tests/Util/TestJsonUtils.cs
@@ -169,7 +169,7 @@ public class TestJsonUtils
" return x + y;\n" +
"}\n");
var doc = new Document(){{"c", c}};
- Assert.AreEqual(@"{ ""c"": { $code : ""function add(x, y){\n return x + y;\n}\n"" } }",
+ Assert.AreEqual(@"{ ""c"": { ""$code"": ""function add(x, y){\n return x + y;\n}\n"" } }",
JsonFormatter.Serialize(doc));
}
View
6 MongoDBDriver.sln
@@ -91,6 +91,12 @@ Global
$4.inheritsSet = Mono
$4.inheritsScope = text/x-csharp
$4.scope = text/x-csharp
+ $0.TextStylePolicy = $5
+ $5.FileWidth = 120
+ $5.RemoveTrailingWhitespace = True
+ $5.inheritsSet = VisualStudio
+ $5.inheritsScope = text/plain
+ $5.scope = application/xml
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
View
2 MongoDBDriver/Code.cs
@@ -11,7 +11,7 @@ public class Code
}
public override string ToString() {
- return string.Format(@"{{ $code : ""{0}"" }}", JsonFormatter.Escape(Value));
+ return string.Format(@"{{ ""$code"": ""{0}"" }}", JsonFormatter.Escape(Value));
}
}
}
View
2 MongoDBDriver/MongoDB.Driver.csproj
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>