aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Tests/Common
diff options
context:
space:
mode:
authorUbitUmarov2015-09-01 11:43:07 +0100
committerUbitUmarov2015-09-01 11:43:07 +0100
commitfb78b182520fc9bb0f971afd0322029c70278ea6 (patch)
treeb4e30d383938fdeef8c92d1d1c2f44bb61d329bd /OpenSim/Tests/Common
parentlixo (diff)
parentMantis #7713: fixed bug introduced by 1st MOSES patch. (diff)
downloadopensim-SC-fb78b182520fc9bb0f971afd0322029c70278ea6.zip
opensim-SC-fb78b182520fc9bb0f971afd0322029c70278ea6.tar.gz
opensim-SC-fb78b182520fc9bb0f971afd0322029c70278ea6.tar.bz2
opensim-SC-fb78b182520fc9bb0f971afd0322029c70278ea6.tar.xz
Merge remote-tracking branch 'os/master'
Diffstat (limited to 'OpenSim/Tests/Common')
-rw-r--r--OpenSim/Tests/Common/ANumericalToleranceConstraint.cs56
-rw-r--r--OpenSim/Tests/Common/DatabaseTestAttribute.cs44
-rw-r--r--OpenSim/Tests/Common/DoubleToleranceConstraint.cs77
-rw-r--r--OpenSim/Tests/Common/Helpers/AssetHelpers.cs168
-rw-r--r--OpenSim/Tests/Common/Helpers/BaseRequestHandlerHelpers.cs75
-rw-r--r--OpenSim/Tests/Common/Helpers/ClientStackHelpers.cs95
-rw-r--r--OpenSim/Tests/Common/Helpers/EntityTransferHelpers.cs123
-rw-r--r--OpenSim/Tests/Common/Helpers/SceneHelpers.cs724
-rw-r--r--OpenSim/Tests/Common/Helpers/TaskInventoryHelpers.cs210
-rw-r--r--OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs160
-rw-r--r--OpenSim/Tests/Common/Helpers/UserInventoryHelpers.cs370
-rw-r--r--OpenSim/Tests/Common/LongRunningAttribute.cs49
-rw-r--r--OpenSim/Tests/Common/Mock/BaseAssetRepository.cs62
-rw-r--r--OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs69
-rw-r--r--OpenSim/Tests/Common/Mock/MockGroupsServicesConnector.cs436
-rw-r--r--OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs371
-rw-r--r--OpenSim/Tests/Common/Mock/MockScriptEngine.cs272
-rw-r--r--OpenSim/Tests/Common/Mock/TestClient.cs1323
-rw-r--r--OpenSim/Tests/Common/Mock/TestEventQueueGetModule.cs182
-rw-r--r--OpenSim/Tests/Common/Mock/TestHttpClientContext.cs110
-rw-r--r--OpenSim/Tests/Common/Mock/TestHttpRequest.cs174
-rw-r--r--OpenSim/Tests/Common/Mock/TestHttpResponse.cs171
-rw-r--r--OpenSim/Tests/Common/Mock/TestInventoryDataPlugin.cs219
-rw-r--r--OpenSim/Tests/Common/Mock/TestLLUDPServer.cs171
-rw-r--r--OpenSim/Tests/Common/Mock/TestLandChannel.cs115
-rw-r--r--OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs179
-rw-r--r--OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs133
-rw-r--r--OpenSim/Tests/Common/Mock/TestScene.cs77
-rw-r--r--OpenSim/Tests/Common/Mock/TestXInventoryDataPlugin.cs152
-rw-r--r--OpenSim/Tests/Common/OpenSimTestCase.cs55
-rw-r--r--OpenSim/Tests/Common/QuaternionToleranceConstraint.cs82
-rw-r--r--OpenSim/Tests/Common/TestHelpers.cs164
-rw-r--r--OpenSim/Tests/Common/TestLogging.cs46
-rw-r--r--OpenSim/Tests/Common/VectorToleranceConstraint.cs81
34 files changed, 6795 insertions, 0 deletions
diff --git a/OpenSim/Tests/Common/ANumericalToleranceConstraint.cs b/OpenSim/Tests/Common/ANumericalToleranceConstraint.cs
new file mode 100644
index 0000000..15c8802
--- /dev/null
+++ b/OpenSim/Tests/Common/ANumericalToleranceConstraint.cs
@@ -0,0 +1,56 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using NUnit.Framework.Constraints;
30
31namespace OpenSim.Tests.Common
32{
33 public abstract class ANumericalToleranceConstraint : Constraint
34 {
35 protected double _tolerance;
36
37 public ANumericalToleranceConstraint(double tolerance)
38 {
39 if (tolerance < 0)
40 {
41 throw new ArgumentException("Tolerance cannot be negative.");
42 }
43 _tolerance = tolerance;
44 }
45
46 protected bool IsWithinDoubleConstraint(double doubleValue, double baseValue)
47 {
48 if (doubleValue >= baseValue - _tolerance && doubleValue <= baseValue + _tolerance)
49 {
50 return true;
51 }
52
53 return false;
54 }
55 }
56}
diff --git a/OpenSim/Tests/Common/DatabaseTestAttribute.cs b/OpenSim/Tests/Common/DatabaseTestAttribute.cs
new file mode 100644
index 0000000..d027d59
--- /dev/null
+++ b/OpenSim/Tests/Common/DatabaseTestAttribute.cs
@@ -0,0 +1,44 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Text;
31using NUnit.Framework;
32
33namespace OpenSim.Tests.Common
34{
35 [AttributeUsage(AttributeTargets.All,
36 AllowMultiple=false,
37 Inherited=true)]
38 public class DatabaseTestAttribute : LongRunningAttribute
39 {
40 public DatabaseTestAttribute() : base("Database")
41 {
42 }
43 }
44} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/DoubleToleranceConstraint.cs b/OpenSim/Tests/Common/DoubleToleranceConstraint.cs
new file mode 100644
index 0000000..b2f2057
--- /dev/null
+++ b/OpenSim/Tests/Common/DoubleToleranceConstraint.cs
@@ -0,0 +1,77 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using NUnit.Framework;
30using NUnit.Framework.Constraints;
31
32namespace OpenSim.Tests.Common
33{
34 public class DoubleToleranceConstraint : ANumericalToleranceConstraint
35 {
36 private double _baseValue;
37 private double _valueToBeTested;
38
39 public DoubleToleranceConstraint(double baseValue, double tolerance) : base(tolerance)
40 {
41 _baseValue = baseValue;
42 }
43
44 ///<summary>
45 ///Test whether the constraint is satisfied by a given value
46 ///</summary>
47 ///<param name="valueToBeTested">The value to be tested</param>
48 ///<returns>
49 ///True for success, false for failure
50 ///</returns>
51 public override bool Matches(object valueToBeTested)
52 {
53 if (valueToBeTested == null)
54 {
55 throw new ArgumentException("Constraint cannot be used upon null values.");
56 }
57 if (valueToBeTested.GetType() != typeof(double))
58 {
59 throw new ArgumentException("Constraint cannot be used upon non double-values.");
60 }
61
62 _valueToBeTested = (double)valueToBeTested;
63
64 return IsWithinDoubleConstraint(_valueToBeTested, _baseValue);
65 }
66
67 public override void WriteDescriptionTo(MessageWriter writer)
68 {
69 writer.WriteExpectedValue(string.Format("A value {0} within tolerance of plus or minus {1}",_baseValue,_tolerance));
70 }
71
72 public override void WriteActualValueTo(MessageWriter writer)
73 {
74 writer.WriteActualValue(_valueToBeTested);
75 }
76 }
77}
diff --git a/OpenSim/Tests/Common/Helpers/AssetHelpers.cs b/OpenSim/Tests/Common/Helpers/AssetHelpers.cs
new file mode 100644
index 0000000..7af8bed
--- /dev/null
+++ b/OpenSim/Tests/Common/Helpers/AssetHelpers.cs
@@ -0,0 +1,168 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Text;
29using OpenMetaverse;
30using OpenMetaverse.Assets;
31using OpenSim.Framework;
32using OpenSim.Region.Framework.Scenes;
33using OpenSim.Region.Framework.Scenes.Serialization;
34using OpenSim.Services.Interfaces;
35
36namespace OpenSim.Tests.Common
37{
38 public class AssetHelpers
39 {
40 /// <summary>
41 /// Create a notecard asset with a random uuids and dummy text.
42 /// </summary>
43 /// <returns></returns>
44 public static AssetBase CreateNotecardAsset()
45 {
46 return CreateNotecardAsset(UUID.Random());
47 }
48
49 /// <summary>
50 /// Create a notecard asset with dummy text and a random owner.
51 /// </summary>
52 /// <param name="assetId">/param>
53 /// <returns></returns>
54 public static AssetBase CreateNotecardAsset(UUID assetId)
55 {
56 return CreateNotecardAsset(assetId, "hello");
57 }
58
59 /// <summary>
60 /// Create a notecard asset with a random owner.
61 /// </summary>
62 /// <param name="assetId">/param>
63 /// <param name="text"></param>
64 /// <returns></returns>
65 public static AssetBase CreateNotecardAsset(UUID assetId, string text)
66 {
67 return CreateAsset(assetId, AssetType.Notecard, text, UUID.Random());
68 }
69
70// /// <summary>
71// /// Create and store a notecard asset with a random uuid and dummy text.
72// /// </summary>
73// /// <param name="creatorId">/param>
74// /// <returns></returns>
75// public static AssetBase CreateNotecardAsset(Scene scene, UUID creatorId)
76// {
77// AssetBase asset = CreateAsset(UUID.Random(), AssetType.Notecard, "hello", creatorId);
78// scene.AssetService.Store(asset);
79// return asset;
80// }
81
82 /// <summary>
83 /// Create an asset from the given object.
84 /// </summary>
85 /// <param name="assetUuidTail">
86 /// The hexadecimal last part of the UUID for the asset created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
87 /// will be used.
88 /// </param>
89 /// <param name="sog"></param>
90 /// <returns></returns>
91 public static AssetBase CreateAsset(int assetUuidTail, SceneObjectGroup sog)
92 {
93 return CreateAsset(new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", assetUuidTail)), sog);
94 }
95
96 /// <summary>
97 /// Create an asset from the given object.
98 /// </summary>
99 /// <param name="assetUuid"></param>
100 /// <param name="sog"></param>
101 /// <returns></returns>
102 public static AssetBase CreateAsset(UUID assetUuid, SceneObjectGroup sog)
103 {
104 return CreateAsset(
105 assetUuid,
106 AssetType.Object,
107 Encoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(sog)),
108 sog.OwnerID);
109 }
110
111 /// <summary>
112 /// Create an asset from the given scene object.
113 /// </summary>
114 /// <param name="assetUuidTail">
115 /// The hexadecimal last part of the UUID for the asset created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
116 /// will be used.
117 /// </param>
118 /// <param name="coa"></param>
119 /// <returns></returns>
120 public static AssetBase CreateAsset(int assetUuidTail, CoalescedSceneObjects coa)
121 {
122 return CreateAsset(new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", assetUuidTail)), coa);
123 }
124
125 /// <summary>
126 /// Create an asset from the given scene object.
127 /// </summary>
128 /// <param name="assetUuid"></param>
129 /// <param name="coa"></param>
130 /// <returns></returns>
131 public static AssetBase CreateAsset(UUID assetUuid, CoalescedSceneObjects coa)
132 {
133 return CreateAsset(
134 assetUuid,
135 AssetType.Object,
136 Encoding.ASCII.GetBytes(CoalescedSceneObjectsSerializer.ToXml(coa)),
137 coa.CreatorId);
138 }
139
140 /// <summary>
141 /// Create an asset from the given data.
142 /// </summary>
143 public static AssetBase CreateAsset(UUID assetUuid, AssetType assetType, string text, UUID creatorID)
144 {
145 AssetNotecard anc = new AssetNotecard();
146 anc.BodyText = text;
147 anc.Encode();
148
149 return CreateAsset(assetUuid, assetType, anc.AssetData, creatorID);
150 }
151
152 /// <summary>
153 /// Create an asset from the given data.
154 /// </summary>
155 public static AssetBase CreateAsset(UUID assetUuid, AssetType assetType, byte[] data, UUID creatorID)
156 {
157 AssetBase asset = new AssetBase(assetUuid, assetUuid.ToString(), (sbyte)assetType, creatorID.ToString());
158 asset.Data = data;
159 return asset;
160 }
161
162 public static string ReadAssetAsString(IAssetService assetService, UUID uuid)
163 {
164 byte[] assetData = assetService.GetData(uuid.ToString());
165 return Encoding.ASCII.GetString(assetData);
166 }
167 }
168}
diff --git a/OpenSim/Tests/Common/Helpers/BaseRequestHandlerHelpers.cs b/OpenSim/Tests/Common/Helpers/BaseRequestHandlerHelpers.cs
new file mode 100644
index 0000000..82ecf9a
--- /dev/null
+++ b/OpenSim/Tests/Common/Helpers/BaseRequestHandlerHelpers.cs
@@ -0,0 +1,75 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Text;
31using NUnit.Framework;
32using OpenSim.Framework;
33using OpenSim.Framework.Servers;
34using OpenSim.Framework.Servers.HttpServer;
35
36namespace OpenSim.Tests.Common
37{
38 public class BaseRequestHandlerHelpers
39 {
40 private static string[] m_emptyStringArray = new string[] { };
41
42 public static void BaseTestGetParams(BaseRequestHandler handler, string assetsPath)
43 {
44 Assert.AreEqual(String.Empty, handler.GetParam(null), "Failed on null path.");
45 Assert.AreEqual(String.Empty, handler.GetParam(""), "Failed on empty path.");
46 Assert.AreEqual(String.Empty, handler.GetParam("s"), "Failed on short url.");
47 Assert.AreEqual(String.Empty, handler.GetParam("corruptUrl"), "Failed on corruptUrl.");
48
49 Assert.AreEqual(String.Empty, handler.GetParam(assetsPath));
50 Assert.AreEqual("/", handler.GetParam(assetsPath + "/"));
51 Assert.AreEqual("/a", handler.GetParam(assetsPath + "/a"));
52 Assert.AreEqual("/b/", handler.GetParam(assetsPath + "/b/"));
53 Assert.AreEqual("/c/d", handler.GetParam(assetsPath + "/c/d"));
54 Assert.AreEqual("/e/f/", handler.GetParam(assetsPath + "/e/f/"));
55 }
56
57 public static void BaseTestSplitParams(BaseRequestHandler handler, string assetsPath)
58 {
59 Assert.AreEqual(m_emptyStringArray, handler.SplitParams(null), "Failed on null.");
60 Assert.AreEqual(m_emptyStringArray, handler.SplitParams(""), "Failed on empty path.");
61 Assert.AreEqual(m_emptyStringArray, handler.SplitParams("corruptUrl"), "Failed on corrupt url.");
62
63 Assert.AreEqual(m_emptyStringArray, handler.SplitParams(assetsPath), "Failed on empty params.");
64 Assert.AreEqual(m_emptyStringArray, handler.SplitParams(assetsPath + "/"), "Failed on single slash.");
65
66 Assert.AreEqual(new string[] { "a" }, handler.SplitParams(assetsPath + "/a"), "Failed on first segment.");
67 Assert.AreEqual(new string[] { "b" }, handler.SplitParams(assetsPath + "/b/"), "Failed on second slash.");
68 Assert.AreEqual(new string[] { "c", "d" }, handler.SplitParams(assetsPath + "/c/d"), "Failed on second segment.");
69 Assert.AreEqual(new string[] { "e", "f" }, handler.SplitParams(assetsPath + "/e/f/"), "Failed on trailing slash.");
70 }
71
72 public static byte[] EmptyByteArray = new byte[] {};
73
74 }
75}
diff --git a/OpenSim/Tests/Common/Helpers/ClientStackHelpers.cs b/OpenSim/Tests/Common/Helpers/ClientStackHelpers.cs
new file mode 100644
index 0000000..33cd8a2
--- /dev/null
+++ b/OpenSim/Tests/Common/Helpers/ClientStackHelpers.cs
@@ -0,0 +1,95 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Net;
30using Nini.Config;
31using OpenMetaverse;
32using OpenMetaverse.Packets;
33using OpenSim.Framework;
34using OpenSim.Region.ClientStack.LindenUDP;
35using OpenSim.Region.Framework.Scenes;
36
37namespace OpenSim.Tests.Common
38{
39 /// <summary>
40 /// This class adds full UDP client classes and associated scene presence to scene.
41 /// </summary>
42 /// <remarks>
43 /// This is used for testing client stack code. For testing other code, use SceneHelper methods instead since
44 /// they operate without the burden of setting up UDP structures which should be unnecessary for testing scene
45 /// code.
46 /// </remarks>
47 public static class ClientStackHelpers
48 {
49 public static ScenePresence AddChildClient(
50 Scene scene, LLUDPServer udpServer, UUID agentId, UUID sessionId, uint circuitCode)
51 {
52 IPEndPoint testEp = new IPEndPoint(IPAddress.Loopback, 999);
53
54 UseCircuitCodePacket uccp = new UseCircuitCodePacket();
55
56 UseCircuitCodePacket.CircuitCodeBlock uccpCcBlock
57 = new UseCircuitCodePacket.CircuitCodeBlock();
58 uccpCcBlock.Code = circuitCode;
59 uccpCcBlock.ID = agentId;
60 uccpCcBlock.SessionID = sessionId;
61 uccp.CircuitCode = uccpCcBlock;
62
63 byte[] uccpBytes = uccp.ToBytes();
64 UDPPacketBuffer upb = new UDPPacketBuffer(testEp, uccpBytes.Length);
65 upb.DataLength = uccpBytes.Length; // God knows why this isn't set by the constructor.
66 Buffer.BlockCopy(uccpBytes, 0, upb.Data, 0, uccpBytes.Length);
67
68 AgentCircuitData acd = new AgentCircuitData();
69 acd.AgentID = agentId;
70 acd.SessionID = sessionId;
71
72 scene.AuthenticateHandler.AddNewCircuit(circuitCode, acd);
73
74 udpServer.PacketReceived(upb);
75
76 return scene.GetScenePresence(agentId);
77 }
78
79 public static TestLLUDPServer AddUdpServer(Scene scene)
80 {
81 return AddUdpServer(scene, new IniConfigSource());
82 }
83
84 public static TestLLUDPServer AddUdpServer(Scene scene, IniConfigSource configSource)
85 {
86 uint port = 0;
87 AgentCircuitManager acm = scene.AuthenticateHandler;
88
89 TestLLUDPServer udpServer = new TestLLUDPServer(IPAddress.Any, ref port, 0, false, configSource, acm);
90 udpServer.AddScene(scene);
91
92 return udpServer;
93 }
94 }
95} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Helpers/EntityTransferHelpers.cs b/OpenSim/Tests/Common/Helpers/EntityTransferHelpers.cs
new file mode 100644
index 0000000..cf7583e
--- /dev/null
+++ b/OpenSim/Tests/Common/Helpers/EntityTransferHelpers.cs
@@ -0,0 +1,123 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.IO;
31using System.Net;
32using System.Reflection;
33using System.Text;
34using System.Threading;
35using log4net;
36using Nini.Config;
37using NUnit.Framework;
38using OpenMetaverse;
39using OpenSim.Framework;
40using OpenSim.Framework.Communications;
41using OpenSim.Framework.Servers;
42using OpenSim.Region.Framework.Interfaces;
43using OpenSim.Region.Framework.Scenes;
44using OpenSim.Region.CoreModules.Framework;
45using OpenSim.Tests.Common;
46
47namespace OpenSim.Tests.Common
48{
49 public static class EntityTransferHelpers
50 {
51 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
52
53 /// <summary>
54 /// Set up correct handling of the InformClientOfNeighbour call from the source region that triggers the
55 /// viewer to setup a connection with the destination region.
56 /// </summary>
57 /// <param name='tc'></param>
58 /// <param name='neighbourTcs'>
59 /// A list that will be populated with any TestClients set up in response to
60 /// being informed about a destination region.
61 /// </param>
62 public static void SetupInformClientOfNeighbourTriggersNeighbourClientCreate(
63 TestClient tc, List<TestClient> neighbourTcs)
64 {
65 // XXX: Confusingly, this is also used for non-neighbour notification (as in teleports that do not use the
66 // event queue).
67
68 tc.OnTestClientInformClientOfNeighbour += (neighbourHandle, neighbourExternalEndPoint) =>
69 {
70 uint x, y;
71 Util.RegionHandleToRegionLoc(neighbourHandle, out x, out y);
72
73 m_log.DebugFormat(
74 "[TEST CLIENT]: Processing inform client of neighbour located at {0},{1} at {2}",
75 x, y, neighbourExternalEndPoint);
76
77 AgentCircuitData newAgent = tc.RequestClientInfo();
78
79 Scene neighbourScene;
80 SceneManager.Instance.TryGetScene(x, y, out neighbourScene);
81
82 TestClient neighbourTc = new TestClient(newAgent, neighbourScene);
83 neighbourTcs.Add(neighbourTc);
84 neighbourScene.AddNewAgent(neighbourTc, PresenceType.User);
85 };
86 }
87
88 /// <summary>
89 /// Set up correct handling of the InformClientOfNeighbour call from the source region that triggers the
90 /// viewer to setup a connection with the destination region.
91 /// </summary>
92 /// <param name='tc'></param>
93 /// <param name='neighbourTcs'>
94 /// A list that will be populated with any TestClients set up in response to
95 /// being informed about a destination region.
96 /// </param>
97 public static void SetupSendRegionTeleportTriggersDestinationClientCreateAndCompleteMovement(
98 TestClient client, List<TestClient> destinationClients)
99 {
100 client.OnTestClientSendRegionTeleport
101 += (regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL) =>
102 {
103 uint x, y;
104 Util.RegionHandleToRegionLoc(regionHandle, out x, out y);
105
106 m_log.DebugFormat(
107 "[TEST CLIENT]: Processing send region teleport for destination at {0},{1} at {2}",
108 x, y, regionExternalEndPoint);
109
110 AgentCircuitData newAgent = client.RequestClientInfo();
111
112 Scene destinationScene;
113 SceneManager.Instance.TryGetScene(x, y, out destinationScene);
114
115 TestClient destinationClient = new TestClient(newAgent, destinationScene);
116 destinationClients.Add(destinationClient);
117 destinationScene.AddNewAgent(destinationClient, PresenceType.User);
118
119 ThreadPool.UnsafeQueueUserWorkItem(o => destinationClient.CompleteMovement(), null);
120 };
121 }
122 }
123} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Helpers/SceneHelpers.cs b/OpenSim/Tests/Common/Helpers/SceneHelpers.cs
new file mode 100644
index 0000000..1fb1c5c
--- /dev/null
+++ b/OpenSim/Tests/Common/Helpers/SceneHelpers.cs
@@ -0,0 +1,724 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Net;
30using System.Collections.Generic;
31using Nini.Config;
32using OpenMetaverse;
33using OpenSim.Data.Null;
34using OpenSim.Framework;
35using OpenSim.Framework.Communications;
36using OpenSim.Framework.Console;
37using OpenSim.Framework.Servers;
38using OpenSim.Framework.Servers.HttpServer;
39using OpenSim.Region.Physics.Manager;
40using OpenSim.Region.Framework;
41using OpenSim.Region.Framework.Interfaces;
42using OpenSim.Region.Framework.Scenes;
43using OpenSim.Region.CoreModules.Avatar.Gods;
44using OpenSim.Region.CoreModules.Asset;
45using OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset;
46using OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication;
47using OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory;
48using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid;
49using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts;
50using OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence;
51using OpenSim.Services.Interfaces;
52using GridRegion = OpenSim.Services.Interfaces.GridRegion;
53
54namespace OpenSim.Tests.Common
55{
56 /// <summary>
57 /// Helpers for setting up scenes.
58 /// </summary>
59 public class SceneHelpers
60 {
61 /// <summary>
62 /// We need a scene manager so that test clients can retrieve a scene when performing teleport tests.
63 /// </summary>
64 public SceneManager SceneManager { get; private set; }
65
66 public ISimulationDataService SimDataService { get; private set; }
67
68 private AgentCircuitManager m_acm = new AgentCircuitManager();
69 private IEstateDataService m_estateDataService = null;
70
71 private LocalAssetServicesConnector m_assetService;
72 private LocalAuthenticationServicesConnector m_authenticationService;
73 private LocalInventoryServicesConnector m_inventoryService;
74 private LocalGridServicesConnector m_gridService;
75 private LocalUserAccountServicesConnector m_userAccountService;
76 private LocalPresenceServicesConnector m_presenceService;
77
78 private CoreAssetCache m_cache;
79
80 public SceneHelpers() : this(null) {}
81
82 public SceneHelpers(CoreAssetCache cache)
83 {
84 SceneManager = new SceneManager();
85
86 m_assetService = StartAssetService(cache);
87 m_authenticationService = StartAuthenticationService();
88 m_inventoryService = StartInventoryService();
89 m_gridService = StartGridService();
90 m_userAccountService = StartUserAccountService();
91 m_presenceService = StartPresenceService();
92
93 m_inventoryService.PostInitialise();
94 m_assetService.PostInitialise();
95 m_userAccountService.PostInitialise();
96 m_presenceService.PostInitialise();
97
98 m_cache = cache;
99
100 SimDataService
101 = OpenSim.Server.Base.ServerUtils.LoadPlugin<ISimulationDataService>("OpenSim.Tests.Common.dll", null);
102 }
103
104 /// <summary>
105 /// Set up a test scene
106 /// </summary>
107 /// <remarks>
108 /// Automatically starts services, as would the normal runtime.
109 /// </remarks>
110 /// <returns></returns>
111 public TestScene SetupScene()
112 {
113 return SetupScene("Unit test region", UUID.Random(), 1000, 1000);
114 }
115
116 public TestScene SetupScene(string name, UUID id, uint x, uint y)
117 {
118 return SetupScene(name, id, x, y, new IniConfigSource());
119 }
120
121 public TestScene SetupScene(string name, UUID id, uint x, uint y, IConfigSource configSource)
122 {
123 return SetupScene(name, id, x, y, Constants.RegionSize, Constants.RegionSize, configSource);
124 }
125
126 /// <summary>
127 /// Set up a scene.
128 /// </summary>
129 /// <param name="name">Name of the region</param>
130 /// <param name="id">ID of the region</param>
131 /// <param name="x">X co-ordinate of the region</param>
132 /// <param name="y">Y co-ordinate of the region</param>
133 /// <param name="sizeX">X size of scene</param>
134 /// <param name="sizeY">Y size of scene</param>
135 /// <param name="configSource"></param>
136 /// <returns></returns>
137 public TestScene SetupScene(
138 string name, UUID id, uint x, uint y, uint sizeX, uint sizeY, IConfigSource configSource)
139 {
140 Console.WriteLine("Setting up test scene {0}", name);
141
142 // We must set up a console otherwise setup of some modules may fail
143 MainConsole.Instance = new MockConsole();
144
145 RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1");
146 regInfo.RegionName = name;
147 regInfo.RegionID = id;
148 regInfo.RegionSizeX = sizeX;
149 regInfo.RegionSizeY = sizeY;
150
151 SceneCommunicationService scs = new SceneCommunicationService();
152
153 PhysicsPluginManager physicsPluginManager = new PhysicsPluginManager();
154 physicsPluginManager.LoadPluginsFromAssembly("Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll");
155 Vector3 regionExtent = new Vector3( regInfo.RegionSizeX, regInfo.RegionSizeY, regInfo.RegionSizeZ);
156 PhysicsScene physicsScene
157 = physicsPluginManager.GetPhysicsScene(
158 "basicphysics", "ZeroMesher", new IniConfigSource(), "test", regionExtent);
159
160 TestScene testScene = new TestScene(
161 regInfo, m_acm, physicsScene, scs, SimDataService, m_estateDataService, configSource, null);
162
163 INonSharedRegionModule godsModule = new GodsModule();
164 godsModule.Initialise(new IniConfigSource());
165 godsModule.AddRegion(testScene);
166
167 // Add scene to services
168 m_assetService.AddRegion(testScene);
169
170 if (m_cache != null)
171 {
172 m_cache.AddRegion(testScene);
173 m_cache.RegionLoaded(testScene);
174 testScene.AddRegionModule(m_cache.Name, m_cache);
175 }
176
177 m_assetService.RegionLoaded(testScene);
178 testScene.AddRegionModule(m_assetService.Name, m_assetService);
179
180 m_authenticationService.AddRegion(testScene);
181 m_authenticationService.RegionLoaded(testScene);
182 testScene.AddRegionModule(m_authenticationService.Name, m_authenticationService);
183
184 m_inventoryService.AddRegion(testScene);
185 m_inventoryService.RegionLoaded(testScene);
186 testScene.AddRegionModule(m_inventoryService.Name, m_inventoryService);
187
188 m_gridService.AddRegion(testScene);
189 m_gridService.RegionLoaded(testScene);
190 testScene.AddRegionModule(m_gridService.Name, m_gridService);
191
192 m_userAccountService.AddRegion(testScene);
193 m_userAccountService.RegionLoaded(testScene);
194 testScene.AddRegionModule(m_userAccountService.Name, m_userAccountService);
195
196 m_presenceService.AddRegion(testScene);
197 m_presenceService.RegionLoaded(testScene);
198 testScene.AddRegionModule(m_presenceService.Name, m_presenceService);
199
200 testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random();
201 testScene.SetModuleInterfaces();
202
203 testScene.LandChannel = new TestLandChannel(testScene);
204 testScene.LoadWorldMap();
205
206 testScene.RegionInfo.EstateSettings = new EstateSettings();
207 testScene.LoginsEnabled = true;
208 testScene.RegisterRegionWithGrid();
209
210 SceneManager.Add(testScene);
211
212 return testScene;
213 }
214
215 private static LocalAssetServicesConnector StartAssetService(CoreAssetCache cache)
216 {
217 IConfigSource config = new IniConfigSource();
218 config.AddConfig("Modules");
219 config.Configs["Modules"].Set("AssetServices", "LocalAssetServicesConnector");
220 config.AddConfig("AssetService");
221 config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Services.AssetService.dll:AssetService");
222 config.Configs["AssetService"].Set("StorageProvider", "OpenSim.Tests.Common.dll");
223
224 LocalAssetServicesConnector assetService = new LocalAssetServicesConnector();
225 assetService.Initialise(config);
226
227 if (cache != null)
228 {
229 IConfigSource cacheConfig = new IniConfigSource();
230 cacheConfig.AddConfig("Modules");
231 cacheConfig.Configs["Modules"].Set("AssetCaching", "CoreAssetCache");
232 cacheConfig.AddConfig("AssetCache");
233
234 cache.Initialise(cacheConfig);
235 }
236
237 return assetService;
238 }
239
240 private static LocalAuthenticationServicesConnector StartAuthenticationService()
241 {
242 IConfigSource config = new IniConfigSource();
243 config.AddConfig("Modules");
244 config.AddConfig("AuthenticationService");
245 config.Configs["Modules"].Set("AuthenticationServices", "LocalAuthenticationServicesConnector");
246 config.Configs["AuthenticationService"].Set(
247 "LocalServiceModule", "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService");
248 config.Configs["AuthenticationService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
249
250 LocalAuthenticationServicesConnector service = new LocalAuthenticationServicesConnector();
251 service.Initialise(config);
252
253 return service;
254 }
255
256 private static LocalInventoryServicesConnector StartInventoryService()
257 {
258 IConfigSource config = new IniConfigSource();
259 config.AddConfig("Modules");
260 config.AddConfig("InventoryService");
261 config.Configs["Modules"].Set("InventoryServices", "LocalInventoryServicesConnector");
262 config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Services.InventoryService.dll:XInventoryService");
263 config.Configs["InventoryService"].Set("StorageProvider", "OpenSim.Tests.Common.dll");
264
265 LocalInventoryServicesConnector inventoryService = new LocalInventoryServicesConnector();
266 inventoryService.Initialise(config);
267
268 return inventoryService;
269 }
270
271 private static LocalGridServicesConnector StartGridService()
272 {
273 IConfigSource config = new IniConfigSource();
274 config.AddConfig("Modules");
275 config.AddConfig("GridService");
276 config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector");
277 config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData");
278 config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService");
279 config.Configs["GridService"].Set("ConnectionString", "!static");
280
281 LocalGridServicesConnector gridService = new LocalGridServicesConnector();
282 gridService.Initialise(config);
283
284 return gridService;
285 }
286
287 /// <summary>
288 /// Start a user account service
289 /// </summary>
290 /// <param name="testScene"></param>
291 /// <returns></returns>
292 private static LocalUserAccountServicesConnector StartUserAccountService()
293 {
294 IConfigSource config = new IniConfigSource();
295 config.AddConfig("Modules");
296 config.AddConfig("UserAccountService");
297 config.Configs["Modules"].Set("UserAccountServices", "LocalUserAccountServicesConnector");
298 config.Configs["UserAccountService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
299 config.Configs["UserAccountService"].Set(
300 "LocalServiceModule", "OpenSim.Services.UserAccountService.dll:UserAccountService");
301
302 LocalUserAccountServicesConnector userAccountService = new LocalUserAccountServicesConnector();
303 userAccountService.Initialise(config);
304
305 return userAccountService;
306 }
307
308 /// <summary>
309 /// Start a presence service
310 /// </summary>
311 /// <param name="testScene"></param>
312 private static LocalPresenceServicesConnector StartPresenceService()
313 {
314 // Unfortunately, some services share data via statics, so we need to null every time to stop interference
315 // between tests.
316 // This is a massive non-obvious pita.
317 NullPresenceData.Instance = null;
318
319 IConfigSource config = new IniConfigSource();
320 config.AddConfig("Modules");
321 config.AddConfig("PresenceService");
322 config.Configs["Modules"].Set("PresenceServices", "LocalPresenceServicesConnector");
323 config.Configs["PresenceService"].Set("StorageProvider", "OpenSim.Data.Null.dll");
324 config.Configs["PresenceService"].Set(
325 "LocalServiceModule", "OpenSim.Services.PresenceService.dll:PresenceService");
326
327 LocalPresenceServicesConnector presenceService = new LocalPresenceServicesConnector();
328 presenceService.Initialise(config);
329
330 return presenceService;
331 }
332
333 /// <summary>
334 /// Setup modules for a scene using their default settings.
335 /// </summary>
336 /// <param name="scene"></param>
337 /// <param name="modules"></param>
338 public static void SetupSceneModules(Scene scene, params object[] modules)
339 {
340 SetupSceneModules(scene, new IniConfigSource(), modules);
341 }
342
343 /// <summary>
344 /// Setup modules for a scene.
345 /// </summary>
346 /// <remarks>
347 /// If called directly, then all the modules must be shared modules.
348 /// </remarks>
349 /// <param name="scenes"></param>
350 /// <param name="config"></param>
351 /// <param name="modules"></param>
352 public static void SetupSceneModules(Scene scene, IConfigSource config, params object[] modules)
353 {
354 SetupSceneModules(new Scene[] { scene }, config, modules);
355 }
356
357 /// <summary>
358 /// Setup modules for a scene using their default settings.
359 /// </summary>
360 /// <param name="scenes"></param>
361 /// <param name="modules"></param>
362 public static void SetupSceneModules(Scene[] scenes, params object[] modules)
363 {
364 SetupSceneModules(scenes, new IniConfigSource(), modules);
365 }
366
367 /// <summary>
368 /// Setup modules for scenes.
369 /// </summary>
370 /// <remarks>
371 /// If called directly, then all the modules must be shared modules.
372 ///
373 /// We are emulating here the normal calls made to setup region modules
374 /// (Initialise(), PostInitialise(), AddRegion, RegionLoaded()).
375 /// TODO: Need to reuse normal runtime module code.
376 /// </remarks>
377 /// <param name="scenes"></param>
378 /// <param name="config"></param>
379 /// <param name="modules"></param>
380 public static void SetupSceneModules(Scene[] scenes, IConfigSource config, params object[] modules)
381 {
382 List<IRegionModuleBase> newModules = new List<IRegionModuleBase>();
383 foreach (object module in modules)
384 {
385 IRegionModuleBase m = (IRegionModuleBase)module;
386// Console.WriteLine("MODULE {0}", m.Name);
387 m.Initialise(config);
388 newModules.Add(m);
389 }
390
391 foreach (IRegionModuleBase module in newModules)
392 {
393 if (module is ISharedRegionModule) ((ISharedRegionModule)module).PostInitialise();
394 }
395
396 foreach (IRegionModuleBase module in newModules)
397 {
398 foreach (Scene scene in scenes)
399 {
400 module.AddRegion(scene);
401 scene.AddRegionModule(module.Name, module);
402 }
403 }
404
405 // RegionLoaded is fired after all modules have been appropriately added to all scenes
406 foreach (IRegionModuleBase module in newModules)
407 foreach (Scene scene in scenes)
408 module.RegionLoaded(scene);
409
410 foreach (Scene scene in scenes) { scene.SetModuleInterfaces(); }
411 }
412
413 /// <summary>
414 /// Generate some standard agent connection data.
415 /// </summary>
416 /// <param name="agentId"></param>
417 /// <returns></returns>
418 public static AgentCircuitData GenerateAgentData(UUID agentId)
419 {
420 AgentCircuitData acd = GenerateCommonAgentData();
421
422 acd.AgentID = agentId;
423 acd.firstname = "testfirstname";
424 acd.lastname = "testlastname";
425 acd.ServiceURLs = new Dictionary<string, object>();
426
427 return acd;
428 }
429
430 /// <summary>
431 /// Generate some standard agent connection data.
432 /// </summary>
433 /// <param name="agentId"></param>
434 /// <returns></returns>
435 public static AgentCircuitData GenerateAgentData(UserAccount ua)
436 {
437 AgentCircuitData acd = GenerateCommonAgentData();
438
439 acd.AgentID = ua.PrincipalID;
440 acd.firstname = ua.FirstName;
441 acd.lastname = ua.LastName;
442 acd.ServiceURLs = ua.ServiceURLs;
443
444 return acd;
445 }
446
447 private static AgentCircuitData GenerateCommonAgentData()
448 {
449 AgentCircuitData acd = new AgentCircuitData();
450
451 // XXX: Sessions must be unique, otherwise one presence can overwrite another in NullPresenceData.
452 acd.SessionID = UUID.Random();
453 acd.SecureSessionID = UUID.Random();
454
455 acd.circuitcode = 123;
456 acd.BaseFolder = UUID.Zero;
457 acd.InventoryFolder = UUID.Zero;
458 acd.startpos = Vector3.Zero;
459 acd.CapsPath = "http://wibble.com";
460 acd.Appearance = new AvatarAppearance();
461
462 return acd;
463 }
464
465 /// <summary>
466 /// Add a root agent where the details of the agent connection (apart from the id) are unimportant for the test
467 /// </summary>
468 /// <remarks>
469 /// XXX: Use the version of this method that takes the UserAccount structure wherever possible - this will
470 /// make the agent circuit data (e.g. first, lastname) consistent with the user account data.
471 /// </remarks>
472 /// <param name="scene"></param>
473 /// <param name="agentId"></param>
474 /// <returns></returns>
475 public static ScenePresence AddScenePresence(Scene scene, UUID agentId)
476 {
477 return AddScenePresence(scene, GenerateAgentData(agentId));
478 }
479
480 /// <summary>
481 /// Add a root agent.
482 /// </summary>
483 /// <param name="scene"></param>
484 /// <param name="ua"></param>
485 /// <returns></returns>
486 public static ScenePresence AddScenePresence(Scene scene, UserAccount ua)
487 {
488 return AddScenePresence(scene, GenerateAgentData(ua));
489 }
490
491 /// <summary>
492 /// Add a root agent.
493 /// </summary>
494 /// <remarks>
495 /// This function
496 ///
497 /// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the
498 /// userserver if grid) would give initial login data back to the client and separately tell the scene that the
499 /// agent was coming.
500 ///
501 /// 2) Connects the agent with the scene
502 ///
503 /// This function performs actions equivalent with notifying the scene that an agent is
504 /// coming and then actually connecting the agent to the scene. The one step missed out is the very first
505 /// </remarks>
506 /// <param name="scene"></param>
507 /// <param name="agentData"></param>
508 /// <returns></returns>
509 public static ScenePresence AddScenePresence(Scene scene, AgentCircuitData agentData)
510 {
511 return AddScenePresence(scene, new TestClient(agentData, scene), agentData);
512 }
513
514 /// <summary>
515 /// Add a root agent.
516 /// </summary>
517 /// <remarks>
518 /// This function
519 ///
520 /// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the
521 /// userserver if grid) would give initial login data back to the client and separately tell the scene that the
522 /// agent was coming.
523 ///
524 /// 2) Connects the agent with the scene
525 ///
526 /// This function performs actions equivalent with notifying the scene that an agent is
527 /// coming and then actually connecting the agent to the scene. The one step missed out is the very first
528 /// </remarks>
529 /// <param name="scene"></param>
530 /// <param name="agentData"></param>
531 /// <returns></returns>
532 public static ScenePresence AddScenePresence(
533 Scene scene, IClientAPI client, AgentCircuitData agentData)
534 {
535 // We emulate the proper login sequence here by doing things in four stages
536
537 // Stage 0: login
538 // We need to punch through to the underlying service because scene will not, correctly, let us call it
539 // through it's reference to the LPSC
540 LocalPresenceServicesConnector lpsc = (LocalPresenceServicesConnector)scene.PresenceService;
541 lpsc.m_PresenceService.LoginAgent(agentData.AgentID.ToString(), agentData.SessionID, agentData.SecureSessionID);
542
543 // Stages 1 & 2
544 ScenePresence sp = IntroduceClientToScene(scene, client, agentData, TeleportFlags.ViaLogin);
545
546 // Stage 3: Complete the entrance into the region. This converts the child agent into a root agent.
547 sp.CompleteMovement(sp.ControllingClient, true);
548
549 return sp;
550 }
551
552 /// <summary>
553 /// Introduce an agent into the scene by adding a new client.
554 /// </summary>
555 /// <returns>The scene presence added</returns>
556 /// <param name='scene'></param>
557 /// <param name='testClient'></param>
558 /// <param name='agentData'></param>
559 /// <param name='tf'></param>
560 private static ScenePresence IntroduceClientToScene(
561 Scene scene, IClientAPI client, AgentCircuitData agentData, TeleportFlags tf)
562 {
563 string reason;
564
565 // Stage 1: tell the scene to expect a new user connection
566 if (!scene.NewUserConnection(agentData, (uint)tf, null, out reason))
567 Console.WriteLine("NewUserConnection failed: " + reason);
568
569 // Stage 2: add the new client as a child agent to the scene
570 scene.AddNewAgent(client, PresenceType.User);
571
572 return scene.GetScenePresence(client.AgentId);
573 }
574
575 public static ScenePresence AddChildScenePresence(Scene scene, UUID agentId)
576 {
577 return AddChildScenePresence(scene, GenerateAgentData(agentId));
578 }
579
580 public static ScenePresence AddChildScenePresence(Scene scene, AgentCircuitData acd)
581 {
582 acd.child = true;
583
584 // XXX: ViaLogin may not be correct for child agents
585 TestClient client = new TestClient(acd, scene);
586 return IntroduceClientToScene(scene, client, acd, TeleportFlags.ViaLogin);
587 }
588
589 /// <summary>
590 /// Add a test object
591 /// </summary>
592 /// <param name="scene"></param>
593 /// <returns></returns>
594 public static SceneObjectGroup AddSceneObject(Scene scene)
595 {
596 return AddSceneObject(scene, "Test Object", UUID.Zero);
597 }
598
599 /// <summary>
600 /// Add a test object
601 /// </summary>
602 /// <param name="scene"></param>
603 /// <param name="name"></param>
604 /// <param name="ownerId"></param>
605 /// <returns></returns>
606 public static SceneObjectGroup AddSceneObject(Scene scene, string name, UUID ownerId)
607 {
608 SceneObjectGroup so = new SceneObjectGroup(CreateSceneObjectPart(name, UUID.Random(), ownerId));
609
610 //part.UpdatePrimFlags(false, false, true);
611 //part.ObjectFlags |= (uint)PrimFlags.Phantom;
612
613 scene.AddNewSceneObject(so, true);
614
615 return so;
616 }
617
618 /// <summary>
619 /// Add a test object
620 /// </summary>
621 /// <param name="scene"></param>
622 /// <param name="parts">
623 /// The number of parts that should be in the scene object
624 /// </param>
625 /// <param name="ownerId"></param>
626 /// <param name="partNamePrefix">
627 /// The prefix to be given to part names. This will be suffixed with "Part<part no>"
628 /// (e.g. mynamePart1 for the root part)
629 /// </param>
630 /// <param name="uuidTail">
631 /// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
632 /// will be given to the root part, and incremented for each part thereafter.
633 /// </param>
634 /// <returns></returns>
635 public static SceneObjectGroup AddSceneObject(Scene scene, int parts, UUID ownerId, string partNamePrefix, int uuidTail)
636 {
637 SceneObjectGroup so = CreateSceneObject(parts, ownerId, partNamePrefix, uuidTail);
638
639 scene.AddNewSceneObject(so, false);
640
641 return so;
642 }
643
644 /// <summary>
645 /// Create a scene object part.
646 /// </summary>
647 /// <param name="name"></param>
648 /// <param name="id"></param>
649 /// <param name="ownerId"></param>
650 /// <returns></returns>
651 public static SceneObjectPart CreateSceneObjectPart(string name, UUID id, UUID ownerId)
652 {
653 return new SceneObjectPart(
654 ownerId, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero)
655 { Name = name, UUID = id, Scale = new Vector3(1, 1, 1) };
656 }
657
658 /// <summary>
659 /// Create a scene object but do not add it to the scene.
660 /// </summary>
661 /// <remarks>
662 /// UUID always starts at 00000000-0000-0000-0000-000000000001. For some purposes, (e.g. serializing direct
663 /// to another object's inventory) we do not need a scene unique ID. So it would be better to add the
664 /// UUID when we actually add an object to a scene rather than on creation.
665 /// </remarks>
666 /// <param name="parts">The number of parts that should be in the scene object</param>
667 /// <param name="ownerId"></param>
668 /// <returns></returns>
669 public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId)
670 {
671 return CreateSceneObject(parts, ownerId, 0x1);
672 }
673
674 /// <summary>
675 /// Create a scene object but do not add it to the scene.
676 /// </summary>
677 /// <param name="parts">The number of parts that should be in the scene object</param>
678 /// <param name="ownerId"></param>
679 /// <param name="uuidTail">
680 /// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
681 /// will be given to the root part, and incremented for each part thereafter.
682 /// </param>
683 /// <returns></returns>
684 public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, int uuidTail)
685 {
686 return CreateSceneObject(parts, ownerId, "", uuidTail);
687 }
688
689 /// <summary>
690 /// Create a scene object but do not add it to the scene.
691 /// </summary>
692 /// <param name="parts">
693 /// The number of parts that should be in the scene object
694 /// </param>
695 /// <param name="ownerId"></param>
696 /// <param name="partNamePrefix">
697 /// The prefix to be given to part names. This will be suffixed with "Part<part no>"
698 /// (e.g. mynamePart1 for the root part)
699 /// </param>
700 /// <param name="uuidTail">
701 /// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}"
702 /// will be given to the root part, and incremented for each part thereafter.
703 /// </param>
704 /// <returns></returns>
705 public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, string partNamePrefix, int uuidTail)
706 {
707 string rawSogId = string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail);
708
709 SceneObjectGroup sog
710 = new SceneObjectGroup(
711 CreateSceneObjectPart(string.Format("{0}Part1", partNamePrefix), new UUID(rawSogId), ownerId));
712
713 if (parts > 1)
714 for (int i = 2; i <= parts; i++)
715 sog.AddPart(
716 CreateSceneObjectPart(
717 string.Format("{0}Part{1}", partNamePrefix, i),
718 new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail + i - 1)),
719 ownerId));
720
721 return sog;
722 }
723 }
724}
diff --git a/OpenSim/Tests/Common/Helpers/TaskInventoryHelpers.cs b/OpenSim/Tests/Common/Helpers/TaskInventoryHelpers.cs
new file mode 100644
index 0000000..3a3b33a
--- /dev/null
+++ b/OpenSim/Tests/Common/Helpers/TaskInventoryHelpers.cs
@@ -0,0 +1,210 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using OpenMetaverse;
30using OpenMetaverse.Assets;
31using OpenSim.Framework;
32using OpenSim.Region.Framework.Scenes;
33using OpenSim.Services.Interfaces;
34
35namespace OpenSim.Tests.Common
36{
37 /// <summary>
38 /// Utility functions for carrying out task inventory tests.
39 /// </summary>
40 ///
41 public static class TaskInventoryHelpers
42 {
43 /// <summary>
44 /// Add a notecard item to the given part.
45 /// </summary>
46 /// <param name="assetService"></param>
47 /// <param name="part"></param>
48 /// <param name="itemName"></param>
49 /// <param name="itemIDFrag">UUID or UUID stem</param>
50 /// <param name="assetIDFrag">UUID or UUID stem</param>
51 /// <param name="text">The tex to put in the notecard.</param>
52 /// <returns>The item that was added</returns>
53 public static TaskInventoryItem AddNotecard(
54 IAssetService assetService, SceneObjectPart part, string itemName, string itemIDStem, string assetIDStem, string text)
55 {
56 return AddNotecard(
57 assetService, part, itemName, TestHelpers.ParseStem(itemIDStem), TestHelpers.ParseStem(assetIDStem), text);
58 }
59
60 /// <summary>
61 /// Add a notecard item to the given part.
62 /// </summary>
63 /// <param name="assetService"></param>
64 /// <param name="part"></param>
65 /// <param name="itemName"></param>
66 /// <param name="itemID"></param>
67 /// <param name="assetID"></param>
68 /// <param name="text">The tex to put in the notecard.</param>
69 /// <returns>The item that was added</returns>
70 public static TaskInventoryItem AddNotecard(
71 IAssetService assetService, SceneObjectPart part, string itemName, UUID itemID, UUID assetID, string text)
72 {
73 AssetNotecard nc = new AssetNotecard();
74 nc.BodyText = text;
75 nc.Encode();
76
77 AssetBase ncAsset
78 = AssetHelpers.CreateAsset(assetID, AssetType.Notecard, nc.AssetData, UUID.Zero);
79 assetService.Store(ncAsset);
80
81 TaskInventoryItem ncItem
82 = new TaskInventoryItem
83 { Name = itemName, AssetID = assetID, ItemID = itemID,
84 Type = (int)AssetType.Notecard, InvType = (int)InventoryType.Notecard };
85 part.Inventory.AddInventoryItem(ncItem, true);
86
87 return ncItem;
88 }
89
90 /// <summary>
91 /// Add a simple script to the given part.
92 /// </summary>
93 /// <remarks>
94 /// TODO: Accept input for item and asset IDs to avoid mysterious script failures that try to use any of these
95 /// functions more than once in a test.
96 /// </remarks>
97 /// <param name="assetService"></param>
98 /// <param name="part"></param>
99 /// <returns>The item that was added</returns>
100 public static TaskInventoryItem AddScript(IAssetService assetService, SceneObjectPart part)
101 {
102 return AddScript(assetService, part, "scriptItem", "default { state_entry() { llSay(0, \"Hello World\"); } }");
103 }
104
105 /// <summary>
106 /// Add a simple script to the given part.
107 /// </summary>
108 /// <remarks>
109 /// TODO: Accept input for item and asset IDs so that we have completely replicatable regression tests rather
110 /// than a random component.
111 /// </remarks>
112 /// <param name="assetService"></param>
113 /// <param name="part"></param>
114 /// <param name="scriptName">Name of the script to add</param>
115 /// <param name="scriptSource">LSL script source</param>
116 /// <returns>The item that was added</returns>
117 public static TaskInventoryItem AddScript(
118 IAssetService assetService, SceneObjectPart part, string scriptName, string scriptSource)
119 {
120 return AddScript(assetService, part, UUID.Random(), UUID.Random(), scriptName, scriptSource);
121 }
122
123 /// <summary>
124 /// Add a simple script to the given part.
125 /// </summary>
126 /// <remarks>
127 /// TODO: Accept input for item and asset IDs so that we have completely replicatable regression tests rather
128 /// than a random component.
129 /// </remarks>
130 /// <param name="assetService"></param>
131 /// <param name="part"></param>
132 /// <param name="itemId">Item UUID for the script</param>
133 /// <param name="assetId">Asset UUID for the script</param>
134 /// <param name="scriptName">Name of the script to add</param>
135 /// <param name="scriptSource">LSL script source</param>
136 /// <returns>The item that was added</returns>
137 public static TaskInventoryItem AddScript(
138 IAssetService assetService, SceneObjectPart part, UUID itemId, UUID assetId, string scriptName, string scriptSource)
139 {
140 AssetScriptText ast = new AssetScriptText();
141 ast.Source = scriptSource;
142 ast.Encode();
143
144 AssetBase asset
145 = AssetHelpers.CreateAsset(assetId, AssetType.LSLText, ast.AssetData, UUID.Zero);
146 assetService.Store(asset);
147 TaskInventoryItem item
148 = new TaskInventoryItem
149 { Name = scriptName, AssetID = assetId, ItemID = itemId,
150 Type = (int)AssetType.LSLText, InvType = (int)InventoryType.LSL };
151 part.Inventory.AddInventoryItem(item, true);
152
153 return item;
154 }
155
156 /// <summary>
157 /// Add a scene object item to the given part.
158 /// </summary>
159 /// <remarks>
160 /// TODO: Accept input for item and asset IDs to avoid mysterious script failures that try to use any of these
161 /// functions more than once in a test.
162 /// </remarks>
163 ///
164 /// <param name="assetService"></param>
165 /// <param name="sop"></param>
166 /// <param name="itemName"></param>
167 /// <param name="itemId"></param>
168 /// <param name="soToAdd"></param>
169 /// <param name="soAssetId"></param>
170 public static TaskInventoryItem AddSceneObject(
171 IAssetService assetService, SceneObjectPart sop, string itemName, UUID itemId, SceneObjectGroup soToAdd, UUID soAssetId)
172 {
173 AssetBase taskSceneObjectAsset = AssetHelpers.CreateAsset(soAssetId, soToAdd);
174 assetService.Store(taskSceneObjectAsset);
175 TaskInventoryItem taskSceneObjectItem
176 = new TaskInventoryItem
177 { Name = itemName,
178 AssetID = taskSceneObjectAsset.FullID,
179 ItemID = itemId,
180 OwnerID = soToAdd.OwnerID,
181 Type = (int)AssetType.Object,
182 InvType = (int)InventoryType.Object };
183 sop.Inventory.AddInventoryItem(taskSceneObjectItem, true);
184
185 return taskSceneObjectItem;
186 }
187
188 /// <summary>
189 /// Add a scene object item to the given part.
190 /// </summary>
191 /// <remarks>
192 /// TODO: Accept input for item and asset IDs to avoid mysterious script failures that try to use any of these
193 /// functions more than once in a test.
194 /// </remarks>
195 ///
196 /// <param name="assetService"></param>
197 /// <param name="sop"></param>
198 /// <param name="itemName"></param>
199 /// <param name="id"></param>
200 /// <param name="userId"></param>
201 public static TaskInventoryItem AddSceneObject(
202 IAssetService assetService, SceneObjectPart sop, string itemName, UUID itemId, UUID userId)
203 {
204 SceneObjectGroup taskSceneObject = SceneHelpers.CreateSceneObject(1, userId);
205
206 return TaskInventoryHelpers.AddSceneObject(
207 assetService, sop, itemName, itemId, taskSceneObject, TestHelpers.ParseTail(0x10));
208 }
209 }
210} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs b/OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs
new file mode 100644
index 0000000..2fbebc4
--- /dev/null
+++ b/OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs
@@ -0,0 +1,160 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Collections.Generic;
29using OpenMetaverse;
30using OpenSim.Framework.Communications;
31using OpenSim.Region.Framework.Scenes;
32using OpenSim.Services.Interfaces;
33
34namespace OpenSim.Tests.Common
35{
36 /// <summary>
37 /// Utility functions for carrying out user profile related tests.
38 /// </summary>
39 public static class UserAccountHelpers
40 {
41// /// <summary>
42// /// Create a test user with a standard inventory
43// /// </summary>
44// /// <param name="commsManager"></param>
45// /// <param name="callback">
46// /// Callback to invoke when inventory has been loaded. This is required because
47// /// loading may be asynchronous, even on standalone
48// /// </param>
49// /// <returns></returns>
50// public static CachedUserInfo CreateUserWithInventory(
51// CommunicationsManager commsManager, OnInventoryReceivedDelegate callback)
52// {
53// UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000099");
54// return CreateUserWithInventory(commsManager, userId, callback);
55// }
56//
57// /// <summary>
58// /// Create a test user with a standard inventory
59// /// </summary>
60// /// <param name="commsManager"></param>
61// /// <param name="userId">User ID</param>
62// /// <param name="callback">
63// /// Callback to invoke when inventory has been loaded. This is required because
64// /// loading may be asynchronous, even on standalone
65// /// </param>
66// /// <returns></returns>
67// public static CachedUserInfo CreateUserWithInventory(
68// CommunicationsManager commsManager, UUID userId, OnInventoryReceivedDelegate callback)
69// {
70// return CreateUserWithInventory(commsManager, "Bill", "Bailey", userId, callback);
71// }
72//
73// /// <summary>
74// /// Create a test user with a standard inventory
75// /// </summary>
76// /// <param name="commsManager"></param>
77// /// <param name="firstName">First name of user</param>
78// /// <param name="lastName">Last name of user</param>
79// /// <param name="userId">User ID</param>
80// /// <param name="callback">
81// /// Callback to invoke when inventory has been loaded. This is required because
82// /// loading may be asynchronous, even on standalone
83// /// </param>
84// /// <returns></returns>
85// public static CachedUserInfo CreateUserWithInventory(
86// CommunicationsManager commsManager, string firstName, string lastName,
87// UUID userId, OnInventoryReceivedDelegate callback)
88// {
89// return CreateUserWithInventory(commsManager, firstName, lastName, "troll", userId, callback);
90// }
91//
92// /// <summary>
93// /// Create a test user with a standard inventory
94// /// </summary>
95// /// <param name="commsManager"></param>
96// /// <param name="firstName">First name of user</param>
97// /// <param name="lastName">Last name of user</param>
98// /// <param name="password">Password</param>
99// /// <param name="userId">User ID</param>
100// /// <param name="callback">
101// /// Callback to invoke when inventory has been loaded. This is required because
102// /// loading may be asynchronous, even on standalone
103// /// </param>
104// /// <returns></returns>
105// public static CachedUserInfo CreateUserWithInventory(
106// CommunicationsManager commsManager, string firstName, string lastName, string password,
107// UUID userId, OnInventoryReceivedDelegate callback)
108// {
109// LocalUserServices lus = (LocalUserServices)commsManager.UserService;
110// lus.AddUser(firstName, lastName, password, "bill@bailey.com", 1000, 1000, userId);
111//
112// CachedUserInfo userInfo = commsManager.UserProfileCacheService.GetUserDetails(userId);
113// userInfo.OnInventoryReceived += callback;
114// userInfo.FetchInventory();
115//
116// return userInfo;
117// }
118
119 public static UserAccount CreateUserWithInventory(Scene scene)
120 {
121 return CreateUserWithInventory(scene, TestHelpers.ParseTail(99));
122 }
123
124 public static UserAccount CreateUserWithInventory(Scene scene, UUID userId)
125 {
126 return CreateUserWithInventory(scene, "Bill", "Bailey", userId, "troll");
127 }
128
129 public static UserAccount CreateUserWithInventory(Scene scene, int userId)
130 {
131 return CreateUserWithInventory(scene, "Bill", "Bailey", TestHelpers.ParseTail(userId), "troll");
132 }
133
134 public static UserAccount CreateUserWithInventory(
135 Scene scene, string firstName, string lastName, UUID userId, string pw)
136 {
137 UserAccount ua = new UserAccount(userId) { FirstName = firstName, LastName = lastName };
138 CreateUserWithInventory(scene, ua, pw);
139 return ua;
140 }
141
142 public static UserAccount CreateUserWithInventory(
143 Scene scene, string firstName, string lastName, int userId, string pw)
144 {
145 UserAccount ua
146 = new UserAccount(TestHelpers.ParseTail(userId)) { FirstName = firstName, LastName = lastName };
147 CreateUserWithInventory(scene, ua, pw);
148 return ua;
149 }
150
151 public static void CreateUserWithInventory(Scene scene, UserAccount ua, string pw)
152 {
153 // FIXME: This should really be set up by UserAccount itself
154 ua.ServiceURLs = new Dictionary<string, object>();
155 scene.UserAccountService.StoreUserAccount(ua);
156 scene.InventoryService.CreateUserInventory(ua.PrincipalID);
157 scene.AuthenticationService.SetPassword(ua.PrincipalID, pw);
158 }
159 }
160} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Helpers/UserInventoryHelpers.cs b/OpenSim/Tests/Common/Helpers/UserInventoryHelpers.cs
new file mode 100644
index 0000000..5a36332
--- /dev/null
+++ b/OpenSim/Tests/Common/Helpers/UserInventoryHelpers.cs
@@ -0,0 +1,370 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31using OpenSim.Framework;
32using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver;
33using OpenSim.Region.Framework.Scenes;
34using OpenSim.Services.Interfaces;
35
36namespace OpenSim.Tests.Common
37{
38 /// <summary>
39 /// Utility functions for carrying out user inventory tests.
40 /// </summary>
41 public static class UserInventoryHelpers
42 {
43 public static readonly string PATH_DELIMITER = "/";
44
45 /// <summary>
46 /// Add an existing scene object as an item in the user's inventory.
47 /// </summary>
48 /// <remarks>
49 /// Will be added to the system Objects folder.
50 /// </remarks>
51 /// <param name='scene'></param>
52 /// <param name='so'></param>
53 /// <param name='inventoryIdTail'></param>
54 /// <param name='assetIdTail'></param>
55 /// <returns>The inventory item created.</returns>
56 public static InventoryItemBase AddInventoryItem(
57 Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail)
58 {
59 return AddInventoryItem(
60 scene,
61 so.Name,
62 TestHelpers.ParseTail(inventoryIdTail),
63 InventoryType.Object,
64 AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so),
65 so.OwnerID);
66 }
67
68 /// <summary>
69 /// Add an existing scene object as an item in the user's inventory at the given path.
70 /// </summary>
71 /// <param name='scene'></param>
72 /// <param name='so'></param>
73 /// <param name='inventoryIdTail'></param>
74 /// <param name='assetIdTail'></param>
75 /// <returns>The inventory item created.</returns>
76 public static InventoryItemBase AddInventoryItem(
77 Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail, string path)
78 {
79 return AddInventoryItem(
80 scene,
81 so.Name,
82 TestHelpers.ParseTail(inventoryIdTail),
83 InventoryType.Object,
84 AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so),
85 so.OwnerID,
86 path);
87 }
88
89 /// <summary>
90 /// Adds the given item to the existing system folder for its type (e.g. an object will go in the "Objects"
91 /// folder).
92 /// </summary>
93 /// <param name="scene"></param>
94 /// <param name="itemName"></param>
95 /// <param name="itemId"></param>
96 /// <param name="itemType"></param>
97 /// <param name="asset">The serialized asset for this item</param>
98 /// <param name="userId"></param>
99 /// <returns></returns>
100 private static InventoryItemBase AddInventoryItem(
101 Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId)
102 {
103 return AddInventoryItem(
104 scene, itemName, itemId, itemType, asset, userId,
105 scene.InventoryService.GetFolderForType(userId, (FolderType)asset.Type).Name);
106 }
107
108 /// <summary>
109 /// Adds the given item to an inventory folder
110 /// </summary>
111 /// <param name="scene"></param>
112 /// <param name="itemName"></param>
113 /// <param name="itemId"></param>
114 /// <param name="itemType"></param>
115 /// <param name="asset">The serialized asset for this item</param>
116 /// <param name="userId"></param>
117 /// <param name="path">Existing inventory path at which to add.</param>
118 /// <returns></returns>
119 private static InventoryItemBase AddInventoryItem(
120 Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId, string path)
121 {
122 scene.AssetService.Store(asset);
123
124 InventoryItemBase item = new InventoryItemBase();
125 item.Name = itemName;
126 item.AssetID = asset.FullID;
127 item.ID = itemId;
128 item.Owner = userId;
129 item.AssetType = asset.Type;
130 item.InvType = (int)itemType;
131
132 InventoryFolderBase folder = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, path)[0];
133
134 item.Folder = folder.ID;
135 scene.AddInventoryItem(item);
136
137 return item;
138 }
139
140 /// <summary>
141 /// Creates a notecard in the objects folder and specify an item id.
142 /// </summary>
143 /// <param name="scene"></param>
144 /// <param name="itemName"></param>
145 /// <param name="itemId"></param>
146 /// <param name="userId"></param>
147 /// <returns></returns>
148 public static InventoryItemBase CreateInventoryItem(Scene scene, string itemName, UUID userId)
149 {
150 return CreateInventoryItem(scene, itemName, UUID.Random(), UUID.Random(), userId, InventoryType.Notecard);
151 }
152
153 /// <summary>
154 /// Creates an item of the given type with an accompanying asset.
155 /// </summary>
156 /// <param name="scene"></param>
157 /// <param name="itemName"></param>
158 /// <param name="itemId"></param>
159 /// <param name="userId"></param>
160 /// <param name="type">Type of item to create</param>
161 /// <returns></returns>
162 public static InventoryItemBase CreateInventoryItem(
163 Scene scene, string itemName, UUID userId, InventoryType type)
164 {
165 return CreateInventoryItem(scene, itemName, UUID.Random(), UUID.Random(), userId, type);
166 }
167
168 /// <summary>
169 /// Creates a notecard in the objects folder and specify an item id.
170 /// </summary>
171 /// <param name="scene"></param>
172 /// <param name="itemName"></param>
173 /// <param name="itemId"></param>
174 /// <param name="assetId"></param>
175 /// <param name="userId"></param>
176 /// <param name="type">Type of item to create</param>
177 /// <returns></returns>
178 public static InventoryItemBase CreateInventoryItem(
179 Scene scene, string itemName, UUID itemId, UUID assetId, UUID userId, InventoryType itemType)
180 {
181 AssetBase asset = null;
182
183 if (itemType == InventoryType.Notecard)
184 {
185 asset = AssetHelpers.CreateNotecardAsset();
186 asset.CreatorID = userId.ToString();
187 }
188 else if (itemType == InventoryType.Object)
189 {
190 asset = AssetHelpers.CreateAsset(assetId, SceneHelpers.CreateSceneObject(1, userId));
191 }
192 else
193 {
194 throw new Exception(string.Format("Inventory type {0} not supported", itemType));
195 }
196
197 return AddInventoryItem(scene, itemName, itemId, itemType, asset, userId);
198 }
199
200 /// <summary>
201 /// Create inventory folders starting from the user's root folder.
202 /// </summary>
203 /// <param name="inventoryService"></param>
204 /// <param name="userId"></param>
205 /// <param name="path">
206 /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER
207 /// </param>
208 /// <param name="useExistingFolders">
209 /// If true, then folders in the path which already the same name are
210 /// used. This applies to the terminal folder as well.
211 /// If false, then all folders in the path are created, even if there is already a folder at a particular
212 /// level with the same name.
213 /// </param>
214 /// <returns>
215 /// The folder created. If the path contains multiple folders then the last one created is returned.
216 /// Will return null if the root folder could not be found.
217 /// </returns>
218 public static InventoryFolderBase CreateInventoryFolder(
219 IInventoryService inventoryService, UUID userId, string path, bool useExistingFolders)
220 {
221 return CreateInventoryFolder(inventoryService, userId, UUID.Random(), path, useExistingFolders);
222 }
223
224 /// <summary>
225 /// Create inventory folders starting from the user's root folder.
226 /// </summary>
227 /// <param name="inventoryService"></param>
228 /// <param name="userId"></param>
229 /// <param name="folderId"></param>
230 /// <param name="path">
231 /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER
232 /// </param>
233 /// <param name="useExistingFolders">
234 /// If true, then folders in the path which already the same name are
235 /// used. This applies to the terminal folder as well.
236 /// If false, then all folders in the path are created, even if there is already a folder at a particular
237 /// level with the same name.
238 /// </param>
239 /// <returns>
240 /// The folder created. If the path contains multiple folders then the last one created is returned.
241 /// Will return null if the root folder could not be found.
242 /// </returns>
243 public static InventoryFolderBase CreateInventoryFolder(
244 IInventoryService inventoryService, UUID userId, UUID folderId, string path, bool useExistingFolders)
245 {
246 InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId);
247
248 if (null == rootFolder)
249 return null;
250
251 return CreateInventoryFolder(inventoryService, folderId, rootFolder, path, useExistingFolders);
252 }
253
254 /// <summary>
255 /// Create inventory folders starting from a given parent folder
256 /// </summary>
257 /// <remarks>
258 /// If any stem of the path names folders that already exist then these are not recreated. This includes the
259 /// final folder.
260 /// TODO: May need to make it an option to create duplicate folders.
261 /// </remarks>
262 /// <param name="inventoryService"></param>
263 /// <param name="folderId">ID of the folder to create</param>
264 /// <param name="parentFolder"></param>
265 /// <param name="path">
266 /// The folder to create.
267 /// </param>
268 /// <param name="useExistingFolders">
269 /// If true, then folders in the path which already the same name are
270 /// used. This applies to the terminal folder as well.
271 /// If false, then all folders in the path are created, even if there is already a folder at a particular
272 /// level with the same name.
273 /// </param>
274 /// <returns>
275 /// The folder created. If the path contains multiple folders then the last one created is returned.
276 /// </returns>
277 public static InventoryFolderBase CreateInventoryFolder(
278 IInventoryService inventoryService, UUID folderId, InventoryFolderBase parentFolder, string path, bool useExistingFolders)
279 {
280 string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None);
281
282 InventoryFolderBase folder = null;
283
284 if (useExistingFolders)
285 folder = InventoryArchiveUtils.FindFolderByPath(inventoryService, parentFolder, components[0]);
286
287 if (folder == null)
288 {
289// Console.WriteLine("Creating folder {0} at {1}", components[0], parentFolder.Name);
290
291 UUID folderIdForCreate;
292
293 if (components.Length > 1)
294 folderIdForCreate = UUID.Random();
295 else
296 folderIdForCreate = folderId;
297
298 folder
299 = new InventoryFolderBase(
300 folderIdForCreate, components[0], parentFolder.Owner, (short)AssetType.Unknown, parentFolder.ID, 0);
301
302 inventoryService.AddFolder(folder);
303 }
304// else
305// {
306// Console.WriteLine("Found existing folder {0}", folder.Name);
307// }
308
309 if (components.Length > 1)
310 return CreateInventoryFolder(inventoryService, folderId, folder, components[1], useExistingFolders);
311 else
312 return folder;
313 }
314
315 /// <summary>
316 /// Get the inventory folder that matches the path name. If there are multiple folders then only the first
317 /// is returned.
318 /// </summary>
319 /// <param name="inventoryService"></param>
320 /// <param name="userId"></param>
321 /// <param name="path"></param>
322 /// <returns>null if no folder matching the path was found</returns>
323 public static InventoryFolderBase GetInventoryFolder(IInventoryService inventoryService, UUID userId, string path)
324 {
325 List<InventoryFolderBase> folders = GetInventoryFolders(inventoryService, userId, path);
326
327 if (folders.Count != 0)
328 return folders[0];
329 else
330 return null;
331 }
332
333 /// <summary>
334 /// Get the inventory folders that match the path name.
335 /// </summary>
336 /// <param name="inventoryService"></param>
337 /// <param name="userId"></param>
338 /// <param name="path"></param>
339 /// <returns>An empty list if no matching folders were found</returns>
340 public static List<InventoryFolderBase> GetInventoryFolders(IInventoryService inventoryService, UUID userId, string path)
341 {
342 return InventoryArchiveUtils.FindFoldersByPath(inventoryService, userId, path);
343 }
344
345 /// <summary>
346 /// Get the inventory item that matches the path name. If there are multiple items then only the first
347 /// is returned.
348 /// </summary>
349 /// <param name="inventoryService"></param>
350 /// <param name="userId"></param>
351 /// <param name="path"></param>
352 /// <returns>null if no item matching the path was found</returns>
353 public static InventoryItemBase GetInventoryItem(IInventoryService inventoryService, UUID userId, string path)
354 {
355 return InventoryArchiveUtils.FindItemByPath(inventoryService, userId, path);
356 }
357
358 /// <summary>
359 /// Get the inventory items that match the path name.
360 /// </summary>
361 /// <param name="inventoryService"></param>
362 /// <param name="userId"></param>
363 /// <param name="path"></param>
364 /// <returns>An empty list if no matching items were found.</returns>
365 public static List<InventoryItemBase> GetInventoryItems(IInventoryService inventoryService, UUID userId, string path)
366 {
367 return InventoryArchiveUtils.FindItemsByPath(inventoryService, userId, path);
368 }
369 }
370} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/LongRunningAttribute.cs b/OpenSim/Tests/Common/LongRunningAttribute.cs
new file mode 100644
index 0000000..9831ea8
--- /dev/null
+++ b/OpenSim/Tests/Common/LongRunningAttribute.cs
@@ -0,0 +1,49 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Text;
31using NUnit.Framework;
32
33namespace OpenSim.Tests.Common
34{
35 [AttributeUsage(AttributeTargets.All,
36 AllowMultiple = false,
37 Inherited = true)]
38 public class LongRunningAttribute : CategoryAttribute
39 {
40 public LongRunningAttribute() : this("Long Running Test")
41 {
42
43 }
44
45 protected LongRunningAttribute(string category) : base(category)
46 {
47 }
48 }
49}
diff --git a/OpenSim/Tests/Common/Mock/BaseAssetRepository.cs b/OpenSim/Tests/Common/Mock/BaseAssetRepository.cs
new file mode 100644
index 0000000..cb4fb80
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/BaseAssetRepository.cs
@@ -0,0 +1,62 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31using OpenSim.Framework;
32
33namespace OpenSim.Tests.Common
34{
35 public class BaseAssetRepository
36 {
37 protected Dictionary<UUID, AssetBase> Assets = new Dictionary<UUID, AssetBase>();
38
39 public AssetBase FetchAsset(UUID uuid)
40 {
41 if (AssetsExist(new[] { uuid })[0])
42 return Assets[uuid];
43 else
44 return null;
45 }
46
47 public void CreateAsset(AssetBase asset)
48 {
49 Assets[asset.FullID] = asset;
50 }
51
52 public void UpdateAsset(AssetBase asset)
53 {
54 CreateAsset(asset);
55 }
56
57 public bool[] AssetsExist(UUID[] uuids)
58 {
59 return Array.ConvertAll(uuids, id => Assets.ContainsKey(id));
60 }
61 }
62} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs b/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs
new file mode 100644
index 0000000..dddf75d
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs
@@ -0,0 +1,69 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using OpenMetaverse;
31using OpenSim.Framework;
32using OpenSim.Data;
33
34namespace OpenSim.Tests.Common
35{
36 /// <summary>
37 /// In memory asset data plugin for test purposes. Could be another dll when properly filled out and when the
38 /// mono addin plugin system starts co-operating with the unit test system. Currently no locking since unit
39 /// tests are single threaded.
40 /// </summary>
41 public class MockAssetDataPlugin : BaseAssetRepository, IAssetDataPlugin
42 {
43 public string Version { get { return "0"; } }
44 public string Name { get { return "MockAssetDataPlugin"; } }
45
46 public void Initialise() {}
47 public void Initialise(string connect) {}
48 public void Dispose() {}
49
50 private readonly List<AssetBase> assets = new List<AssetBase>();
51
52 public AssetBase GetAsset(UUID uuid)
53 {
54 return assets.Find(x=>x.FullID == uuid);
55 }
56
57 public void StoreAsset(AssetBase asset)
58 {
59 assets.Add(asset);
60 }
61
62 public List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { return new List<AssetMetadata>(count); }
63
64 public bool Delete(string id)
65 {
66 return false;
67 }
68 }
69}
diff --git a/OpenSim/Tests/Common/Mock/MockGroupsServicesConnector.cs b/OpenSim/Tests/Common/Mock/MockGroupsServicesConnector.cs
new file mode 100644
index 0000000..7f530d0
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/MockGroupsServicesConnector.cs
@@ -0,0 +1,436 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Reflection;
32using log4net;
33using Mono.Addins;
34using Nini.Config;
35using OpenMetaverse;
36using OpenSim.Data;
37using OpenSim.Data.Null;
38using OpenSim.Framework;
39using OpenSim.Region.Framework.Interfaces;
40using OpenSim.Region.Framework.Scenes;
41using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups;
42
43namespace OpenSim.Tests.Common
44{
45 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
46 public class MockGroupsServicesConnector : ISharedRegionModule, IGroupsServicesConnector
47 {
48 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
49
50 IXGroupData m_data = new NullXGroupData(null, null);
51
52 public string Name
53 {
54 get { return "MockGroupsServicesConnector"; }
55 }
56
57 public Type ReplaceableInterface
58 {
59 get { return null; }
60 }
61
62 public void Initialise(IConfigSource config)
63 {
64 }
65
66 public void Close()
67 {
68 }
69
70 public void AddRegion(Scene scene)
71 {
72 m_log.DebugFormat("[MOCK GROUPS SERVICES CONNECTOR]: Adding to region {0}", scene.RegionInfo.RegionName);
73 scene.RegisterModuleInterface<IGroupsServicesConnector>(this);
74 }
75
76 public void RemoveRegion(Scene scene)
77 {
78 }
79
80 public void RegionLoaded(Scene scene)
81 {
82 }
83
84 public void PostInitialise()
85 {
86 }
87
88 public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID,
89 int membershipFee, bool openEnrollment, bool allowPublish,
90 bool maturePublish, UUID founderID)
91 {
92 XGroup group = new XGroup()
93 {
94 groupID = UUID.Random(),
95 ownerRoleID = UUID.Random(),
96 name = name,
97 charter = charter,
98 showInList = showInList,
99 insigniaID = insigniaID,
100 membershipFee = membershipFee,
101 openEnrollment = openEnrollment,
102 allowPublish = allowPublish,
103 maturePublish = maturePublish,
104 founderID = founderID,
105 everyonePowers = (ulong)XmlRpcGroupsServicesConnectorModule.DefaultEveryonePowers,
106 ownersPowers = (ulong)XmlRpcGroupsServicesConnectorModule.DefaultOwnerPowers
107 };
108
109 if (m_data.StoreGroup(group))
110 {
111 m_log.DebugFormat("[MOCK GROUPS SERVICES CONNECTOR]: Created group {0} {1}", group.name, group.groupID);
112 return group.groupID;
113 }
114 else
115 {
116 m_log.ErrorFormat("[MOCK GROUPS SERVICES CONNECTOR]: Failed to create group {0}", name);
117 return UUID.Zero;
118 }
119 }
120
121 public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList,
122 UUID insigniaID, int membershipFee, bool openEnrollment,
123 bool allowPublish, bool maturePublish)
124 {
125 }
126
127 public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
128 string title, ulong powers)
129 {
130 }
131
132 public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID)
133 {
134 }
135
136 public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description,
137 string title, ulong powers)
138 {
139 }
140
141 private XGroup GetXGroup(UUID groupID, string name)
142 {
143 XGroup group = m_data.GetGroup(groupID);
144
145
146 if (group == null)
147 m_log.DebugFormat("[MOCK GROUPS SERVICES CONNECTOR]: No group found with ID {0}", groupID);
148
149 return group;
150 }
151
152 public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID groupID, string groupName)
153 {
154 m_log.DebugFormat(
155 "[MOCK GROUPS SERVICES CONNECTOR]: Processing GetGroupRecord() for groupID {0}, name {1}",
156 groupID, groupName);
157
158 XGroup xg = GetXGroup(groupID, groupName);
159
160 if (xg == null)
161 return null;
162
163 GroupRecord gr = new GroupRecord()
164 {
165 GroupID = xg.groupID,
166 GroupName = xg.name,
167 AllowPublish = xg.allowPublish,
168 MaturePublish = xg.maturePublish,
169 Charter = xg.charter,
170 FounderID = xg.founderID,
171 // FIXME: group picture storage location unknown
172 MembershipFee = xg.membershipFee,
173 OpenEnrollment = xg.openEnrollment,
174 OwnerRoleID = xg.ownerRoleID,
175 ShowInList = xg.showInList
176 };
177
178 return gr;
179 }
180
181 public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID)
182 {
183 return default(GroupProfileData);
184 }
185
186 public void SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
187 {
188 }
189
190 public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
191 {
192 }
193
194 public void SetAgentGroupInfo(UUID requestingAgentID, UUID agentID, UUID groupID, bool acceptNotices, bool listInProfile)
195 {
196 m_log.DebugFormat(
197 "[MOCK GROUPS SERVICES CONNECTOR]: SetAgentGroupInfo, requestingAgentID {0}, agentID {1}, groupID {2}, acceptNotices {3}, listInProfile {4}",
198 requestingAgentID, agentID, groupID, acceptNotices, listInProfile);
199
200 XGroup group = GetXGroup(groupID, null);
201
202 if (group == null)
203 return;
204
205 XGroupMember xgm = null;
206 if (!group.members.TryGetValue(agentID, out xgm))
207 return;
208
209 xgm.acceptNotices = acceptNotices;
210 xgm.listInProfile = listInProfile;
211
212 m_data.StoreGroup(group);
213 }
214
215 public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID)
216 {
217 }
218
219 public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
220 {
221 return null;
222 }
223
224 public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID)
225 {
226 }
227
228 public void AddAgentToGroup(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID)
229 {
230 m_log.DebugFormat(
231 "[MOCK GROUPS SERVICES CONNECTOR]: AddAgentToGroup, requestingAgentID {0}, agentID {1}, groupID {2}, roleID {3}",
232 requestingAgentID, agentID, groupID, roleID);
233
234 XGroup group = GetXGroup(groupID, null);
235
236 if (group == null)
237 return;
238
239 XGroupMember groupMember = new XGroupMember()
240 {
241 agentID = agentID,
242 groupID = groupID,
243 roleID = roleID
244 };
245
246 group.members[agentID] = groupMember;
247
248 m_data.StoreGroup(group);
249 }
250
251 public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID)
252 {
253 }
254
255 public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
256 {
257 }
258
259 public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID)
260 {
261 }
262
263 public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search)
264 {
265 return null;
266 }
267
268 public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID)
269 {
270 return null;
271 }
272
273 public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID)
274 {
275 return null;
276 }
277
278 public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID)
279 {
280 return new List<GroupMembershipData>();
281 }
282
283 public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID)
284 {
285 return null;
286 }
287
288 public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID)
289 {
290 return null;
291 }
292
293 public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID groupID)
294 {
295 m_log.DebugFormat(
296 "[MOCK GROUPS SERVICES CONNECTOR]: GetGroupMembers, requestingAgentID {0}, groupID {1}",
297 requestingAgentID, groupID);
298
299 List<GroupMembersData> groupMembers = new List<GroupMembersData>();
300
301 XGroup group = GetXGroup(groupID, null);
302
303 if (group == null)
304 return groupMembers;
305
306 foreach (XGroupMember xgm in group.members.Values)
307 {
308 GroupMembersData gmd = new GroupMembersData();
309 gmd.AgentID = xgm.agentID;
310 gmd.IsOwner = group.founderID == gmd.AgentID;
311 gmd.AcceptNotices = xgm.acceptNotices;
312 gmd.ListInProfile = xgm.listInProfile;
313
314 groupMembers.Add(gmd);
315 }
316
317 return groupMembers;
318 }
319
320 public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID)
321 {
322 return null;
323 }
324
325 public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID groupID)
326 {
327 XGroup group = GetXGroup(groupID, null);
328
329 if (group == null)
330 return null;
331
332 List<GroupNoticeData> notices = new List<GroupNoticeData>();
333
334 foreach (XGroupNotice notice in group.notices.Values)
335 {
336 GroupNoticeData gnd = new GroupNoticeData()
337 {
338 NoticeID = notice.noticeID,
339 Timestamp = notice.timestamp,
340 FromName = notice.fromName,
341 Subject = notice.subject,
342 HasAttachment = notice.hasAttachment,
343 AssetType = (byte)notice.assetType
344 };
345
346 notices.Add(gnd);
347 }
348
349 return notices;
350 }
351
352 public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID)
353 {
354 m_log.DebugFormat(
355 "[MOCK GROUPS SERVICES CONNECTOR]: GetGroupNotices, requestingAgentID {0}, noticeID {1}",
356 requestingAgentID, noticeID);
357
358 // Yes, not an efficient way to do it.
359 Dictionary<UUID, XGroup> groups = m_data.GetGroups();
360
361 foreach (XGroup group in groups.Values)
362 {
363 if (group.notices.ContainsKey(noticeID))
364 {
365 XGroupNotice n = group.notices[noticeID];
366
367 GroupNoticeInfo gni = new GroupNoticeInfo();
368 gni.GroupID = n.groupID;
369 gni.Message = n.message;
370 gni.BinaryBucket = n.binaryBucket;
371 gni.noticeData.NoticeID = n.noticeID;
372 gni.noticeData.Timestamp = n.timestamp;
373 gni.noticeData.FromName = n.fromName;
374 gni.noticeData.Subject = n.subject;
375 gni.noticeData.HasAttachment = n.hasAttachment;
376 gni.noticeData.AssetType = (byte)n.assetType;
377
378 return gni;
379 }
380 }
381
382 return null;
383 }
384
385 public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket)
386 {
387 m_log.DebugFormat(
388 "[MOCK GROUPS SERVICES CONNECTOR]: AddGroupNotice, requestingAgentID {0}, groupID {1}, noticeID {2}, fromName {3}, subject {4}, message {5}, binaryBucket.Length {6}",
389 requestingAgentID, groupID, noticeID, fromName, subject, message, binaryBucket.Length);
390
391 XGroup group = GetXGroup(groupID, null);
392
393 if (group == null)
394 return;
395
396 XGroupNotice groupNotice = new XGroupNotice()
397 {
398 groupID = groupID,
399 noticeID = noticeID,
400 fromName = fromName,
401 subject = subject,
402 message = message,
403 timestamp = (uint)Util.UnixTimeSinceEpoch(),
404 hasAttachment = false,
405 assetType = 0,
406 binaryBucket = binaryBucket
407 };
408
409 group.notices[noticeID] = groupNotice;
410
411 m_data.StoreGroup(group);
412 }
413
414 public void ResetAgentGroupChatSessions(UUID agentID)
415 {
416 }
417
418 public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID)
419 {
420 return false;
421 }
422
423 public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID)
424 {
425 return false;
426 }
427
428 public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID)
429 {
430 }
431
432 public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID)
433 {
434 }
435 }
436} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs b/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs
new file mode 100644
index 0000000..5df8e04
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs
@@ -0,0 +1,371 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Reflection;
29using System.Collections.Generic;
30using log4net;
31using OpenMetaverse;
32using OpenSim.Framework;
33using OpenSim.Region.Framework.Interfaces;
34using OpenSim.Region.Framework.Scenes;
35
36namespace OpenSim.Data.Null
37{
38 public class NullDataService : ISimulationDataService
39 {
40 private NullDataStore m_store;
41
42 public NullDataService()
43 {
44 m_store = new NullDataStore();
45 }
46
47 public void StoreObject(SceneObjectGroup obj, UUID regionUUID)
48 {
49 m_store.StoreObject(obj, regionUUID);
50 }
51
52 public void RemoveObject(UUID uuid, UUID regionUUID)
53 {
54 m_store.RemoveObject(uuid, regionUUID);
55 }
56
57 public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items)
58 {
59 m_store.StorePrimInventory(primID, items);
60 }
61
62 public List<SceneObjectGroup> LoadObjects(UUID regionUUID)
63 {
64 return m_store.LoadObjects(regionUUID);
65 }
66
67 public void StoreTerrain(double[,] terrain, UUID regionID)
68 {
69 m_store.StoreTerrain(terrain, regionID);
70 }
71
72 public void StoreTerrain(TerrainData terrain, UUID regionID)
73 {
74 m_store.StoreTerrain(terrain, regionID);
75 }
76
77 public double[,] LoadTerrain(UUID regionID)
78 {
79 return m_store.LoadTerrain(regionID);
80 }
81
82 public TerrainData LoadTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ)
83 {
84 return m_store.LoadTerrain(regionID, pSizeX, pSizeY, pSizeZ);
85 }
86
87 public void StoreLandObject(ILandObject Parcel)
88 {
89 m_store.StoreLandObject(Parcel);
90 }
91
92 public void RemoveLandObject(UUID globalID)
93 {
94 m_store.RemoveLandObject(globalID);
95 }
96
97 public List<LandData> LoadLandObjects(UUID regionUUID)
98 {
99 return m_store.LoadLandObjects(regionUUID);
100 }
101
102 public void StoreRegionSettings(RegionSettings rs)
103 {
104 m_store.StoreRegionSettings(rs);
105 }
106
107 public RegionSettings LoadRegionSettings(UUID regionUUID)
108 {
109 return m_store.LoadRegionSettings(regionUUID);
110 }
111
112 public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
113 {
114 return m_store.LoadRegionWindlightSettings(regionUUID);
115 }
116
117 public void RemoveRegionWindlightSettings(UUID regionID)
118 {
119 }
120
121 public void StoreRegionWindlightSettings(RegionLightShareData wl)
122 {
123 m_store.StoreRegionWindlightSettings(wl);
124 }
125
126 public string LoadRegionEnvironmentSettings(UUID regionUUID)
127 {
128 return m_store.LoadRegionEnvironmentSettings(regionUUID);
129 }
130
131 public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings)
132 {
133 m_store.StoreRegionEnvironmentSettings(regionUUID, settings);
134 }
135
136 public void RemoveRegionEnvironmentSettings(UUID regionUUID)
137 {
138 m_store.RemoveRegionEnvironmentSettings(regionUUID);
139 }
140
141 public void SaveExtra(UUID regionID, string name, string value)
142 {
143 }
144
145 public void RemoveExtra(UUID regionID, string name)
146 {
147 }
148
149 public Dictionary<string, string> GetExtra(UUID regionID)
150 {
151 return null;
152 }
153 }
154
155 /// <summary>
156 /// Mock region data plugin. This obeys the api contract for persistence but stores everything in memory, so that
157 /// tests can check correct persistence.
158 /// </summary>
159 public class NullDataStore : ISimulationDataStore
160 {
161// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
162
163 protected Dictionary<UUID, RegionSettings> m_regionSettings = new Dictionary<UUID, RegionSettings>();
164 protected Dictionary<UUID, SceneObjectPart> m_sceneObjectParts = new Dictionary<UUID, SceneObjectPart>();
165 protected Dictionary<UUID, ICollection<TaskInventoryItem>> m_primItems
166 = new Dictionary<UUID, ICollection<TaskInventoryItem>>();
167 protected Dictionary<UUID, TerrainData> m_terrains = new Dictionary<UUID, TerrainData>();
168 protected Dictionary<UUID, LandData> m_landData = new Dictionary<UUID, LandData>();
169
170 public void Initialise(string dbfile)
171 {
172 return;
173 }
174
175 public void Dispose()
176 {
177 }
178
179 public void StoreRegionSettings(RegionSettings rs)
180 {
181 m_regionSettings[rs.RegionUUID] = rs;
182 }
183
184 public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID)
185 {
186 //This connector doesn't support the windlight module yet
187 //Return default LL windlight settings
188 return new RegionLightShareData();
189 }
190
191 public void RemoveRegionWindlightSettings(UUID regionID)
192 {
193 }
194
195 public void StoreRegionWindlightSettings(RegionLightShareData wl)
196 {
197 //This connector doesn't support the windlight module yet
198 }
199
200 #region Environment Settings
201 public string LoadRegionEnvironmentSettings(UUID regionUUID)
202 {
203 //This connector doesn't support the Environment module yet
204 return string.Empty;
205 }
206
207 public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings)
208 {
209 //This connector doesn't support the Environment module yet
210 }
211
212 public void RemoveRegionEnvironmentSettings(UUID regionUUID)
213 {
214 //This connector doesn't support the Environment module yet
215 }
216 #endregion
217
218 public RegionSettings LoadRegionSettings(UUID regionUUID)
219 {
220 RegionSettings rs = null;
221 m_regionSettings.TryGetValue(regionUUID, out rs);
222
223 if (rs == null)
224 rs = new RegionSettings();
225
226 return rs;
227 }
228
229 public void StoreObject(SceneObjectGroup obj, UUID regionUUID)
230 {
231 // We can't simply store groups here because on delinking, OpenSim will not update the original group
232 // directly. Rather, the newly delinked parts will be updated to be in their own scene object group
233 // Therefore, we need to store parts rather than groups.
234 foreach (SceneObjectPart prim in obj.Parts)
235 {
236// m_log.DebugFormat(
237// "[MOCK REGION DATA PLUGIN]: Storing part {0} {1} in object {2} {3} in region {4}",
238// prim.Name, prim.UUID, obj.Name, obj.UUID, regionUUID);
239
240 m_sceneObjectParts[prim.UUID] = prim;
241 }
242 }
243
244 public void RemoveObject(UUID obj, UUID regionUUID)
245 {
246 // All parts belonging to the object with the uuid are removed.
247 List<SceneObjectPart> parts = new List<SceneObjectPart>(m_sceneObjectParts.Values);
248 foreach (SceneObjectPart part in parts)
249 {
250 if (part.ParentGroup.UUID == obj)
251 {
252// m_log.DebugFormat(
253// "[MOCK REGION DATA PLUGIN]: Removing part {0} {1} as part of object {2} from {3}",
254// part.Name, part.UUID, obj, regionUUID);
255 m_sceneObjectParts.Remove(part.UUID);
256 }
257 }
258 }
259
260 public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items)
261 {
262 m_primItems[primID] = items;
263 }
264
265 public List<SceneObjectGroup> LoadObjects(UUID regionUUID)
266 {
267 Dictionary<UUID, SceneObjectGroup> objects = new Dictionary<UUID, SceneObjectGroup>();
268
269 // Create all of the SOGs from the root prims first
270 foreach (SceneObjectPart prim in m_sceneObjectParts.Values)
271 {
272 if (prim.IsRoot)
273 {
274// m_log.DebugFormat(
275// "[MOCK REGION DATA PLUGIN]: Loading root part {0} {1} in {2}", prim.Name, prim.UUID, regionUUID);
276 objects[prim.UUID] = new SceneObjectGroup(prim);
277 }
278 }
279
280 // Add all of the children objects to the SOGs
281 foreach (SceneObjectPart prim in m_sceneObjectParts.Values)
282 {
283 SceneObjectGroup sog;
284 if (prim.UUID != prim.ParentUUID)
285 {
286 if (objects.TryGetValue(prim.ParentUUID, out sog))
287 {
288 int originalLinkNum = prim.LinkNum;
289
290 sog.AddPart(prim);
291
292 // SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum.
293 // We override that here
294 if (originalLinkNum != 0)
295 prim.LinkNum = originalLinkNum;
296 }
297 else
298 {
299// m_log.WarnFormat(
300// "[MOCK REGION DATA PLUGIN]: Database contains an orphan child prim {0} {1} in region {2} pointing to missing parent {3}. This prim will not be loaded.",
301// prim.Name, prim.UUID, regionUUID, prim.ParentUUID);
302 }
303 }
304 }
305
306 // TODO: Load items. This is assymetric - we store items as a separate method but don't retrieve them that
307 // way!
308
309 return new List<SceneObjectGroup>(objects.Values);
310 }
311
312 public void StoreTerrain(TerrainData ter, UUID regionID)
313 {
314 m_terrains[regionID] = ter;
315 }
316
317 public void StoreTerrain(double[,] ter, UUID regionID)
318 {
319 m_terrains[regionID] = new HeightmapTerrainData(ter);
320 }
321
322 public TerrainData LoadTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ)
323 {
324 if (m_terrains.ContainsKey(regionID))
325 return m_terrains[regionID];
326 else
327 return null;
328 }
329
330 public double[,] LoadTerrain(UUID regionID)
331 {
332 if (m_terrains.ContainsKey(regionID))
333 return m_terrains[regionID].GetDoubles();
334 else
335 return null;
336 }
337
338 public void RemoveLandObject(UUID globalID)
339 {
340 if (m_landData.ContainsKey(globalID))
341 m_landData.Remove(globalID);
342 }
343
344 public void StoreLandObject(ILandObject land)
345 {
346 m_landData[land.LandData.GlobalID] = land.LandData;
347 }
348
349 public List<LandData> LoadLandObjects(UUID regionUUID)
350 {
351 return new List<LandData>(m_landData.Values);
352 }
353
354 public void Shutdown()
355 {
356 }
357
358 public void SaveExtra(UUID regionID, string name, string value)
359 {
360 }
361
362 public void RemoveExtra(UUID regionID, string name)
363 {
364 }
365
366 public Dictionary<string, string> GetExtra(UUID regionID)
367 {
368 return null;
369 }
370 }
371}
diff --git a/OpenSim/Tests/Common/Mock/MockScriptEngine.cs b/OpenSim/Tests/Common/Mock/MockScriptEngine.cs
new file mode 100644
index 0000000..d7a144c
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/MockScriptEngine.cs
@@ -0,0 +1,272 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Reflection;
32using Nini.Config;
33using OpenMetaverse;
34using OpenSim.Framework;
35using OpenSim.Region.Framework.Interfaces;
36using OpenSim.Region.Framework.Scenes;
37using OpenSim.Region.ScriptEngine.Interfaces;
38using OpenSim.Region.ScriptEngine.Shared;
39
40namespace OpenSim.Tests.Common
41{
42 public class MockScriptEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
43 {
44 public IConfigSource ConfigSource { get; private set; }
45
46 public IConfig Config { get; private set; }
47
48 private Scene m_scene;
49
50 /// <summary>
51 /// Expose posted events to tests.
52 /// </summary>
53 public Dictionary<UUID, List<EventParams>> PostedEvents { get; private set; }
54
55 /// <summary>
56 /// A very primitive way of hooking text cose to a posed event.
57 /// </summary>
58 /// <remarks>
59 /// May be replaced with something that uses more original code in the future.
60 /// </remarks>
61 public event Action<UUID, EventParams> PostEventHook;
62
63 public void Initialise(IConfigSource source)
64 {
65 ConfigSource = source;
66
67 // Can set later on if required
68 Config = new IniConfig("MockScriptEngine", ConfigSource);
69
70 PostedEvents = new Dictionary<UUID, List<EventParams>>();
71 }
72
73 public void Close()
74 {
75 }
76
77 public void AddRegion(Scene scene)
78 {
79 m_scene = scene;
80
81 m_scene.StackModuleInterface<IScriptModule>(this);
82 }
83
84 public void RemoveRegion(Scene scene)
85 {
86 }
87
88 public void RegionLoaded(Scene scene)
89 {
90 }
91
92 public string Name { get { return "Mock Script Engine"; } }
93 public string ScriptEngineName { get { return Name; } }
94
95 public Type ReplaceableInterface { get { return null; } }
96
97#pragma warning disable 0067
98 public event ScriptRemoved OnScriptRemoved;
99 public event ObjectRemoved OnObjectRemoved;
100#pragma warning restore 0067
101
102 public string GetXMLState (UUID itemID)
103 {
104 throw new System.NotImplementedException ();
105 }
106
107 public bool SetXMLState(UUID itemID, string xml)
108 {
109 throw new System.NotImplementedException ();
110 }
111
112 public bool PostScriptEvent(UUID itemID, string name, object[] args)
113 {
114// Console.WriteLine("Posting event {0} for {1}", name, itemID);
115
116 return PostScriptEvent(itemID, new EventParams(name, args, null));
117 }
118
119 public bool PostScriptEvent(UUID itemID, EventParams evParams)
120 {
121 List<EventParams> eventsForItem;
122
123 if (!PostedEvents.ContainsKey(itemID))
124 {
125 eventsForItem = new List<EventParams>();
126 PostedEvents.Add(itemID, eventsForItem);
127 }
128 else
129 {
130 eventsForItem = PostedEvents[itemID];
131 }
132
133 eventsForItem.Add(evParams);
134
135 if (PostEventHook != null)
136 PostEventHook(itemID, evParams);
137
138 return true;
139 }
140
141 public bool PostObjectEvent(uint localID, EventParams evParams)
142 {
143 return PostObjectEvent(m_scene.GetSceneObjectPart(localID), evParams);
144 }
145
146 public bool PostObjectEvent(UUID itemID, string name, object[] args)
147 {
148 return PostObjectEvent(m_scene.GetSceneObjectPart(itemID), new EventParams(name, args, null));
149 }
150
151 private bool PostObjectEvent(SceneObjectPart part, EventParams evParams)
152 {
153 foreach (TaskInventoryItem item in part.Inventory.GetInventoryItems(InventoryType.LSL))
154 PostScriptEvent(item.ItemID, evParams);
155
156 return true;
157 }
158
159 public void SuspendScript(UUID itemID)
160 {
161 throw new System.NotImplementedException ();
162 }
163
164 public void ResumeScript(UUID itemID)
165 {
166 throw new System.NotImplementedException ();
167 }
168
169 public ArrayList GetScriptErrors(UUID itemID)
170 {
171 throw new System.NotImplementedException ();
172 }
173
174 public bool HasScript(UUID itemID, out bool running)
175 {
176 throw new System.NotImplementedException ();
177 }
178
179 public bool GetScriptState(UUID itemID)
180 {
181 throw new System.NotImplementedException ();
182 }
183
184 public void SaveAllState()
185 {
186 throw new System.NotImplementedException ();
187 }
188
189 public void StartProcessing()
190 {
191 throw new System.NotImplementedException ();
192 }
193
194 public float GetScriptExecutionTime(List<UUID> itemIDs)
195 {
196 throw new System.NotImplementedException ();
197 }
198
199 public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
200 {
201 throw new System.NotImplementedException ();
202 }
203
204 public IScriptWorkItem QueueEventHandler(object parms)
205 {
206 throw new System.NotImplementedException ();
207 }
208
209 public DetectParams GetDetectParams(UUID item, int number)
210 {
211 throw new System.NotImplementedException ();
212 }
213
214 public void SetMinEventDelay(UUID itemID, double delay)
215 {
216 throw new System.NotImplementedException ();
217 }
218
219 public int GetStartParameter(UUID itemID)
220 {
221 throw new System.NotImplementedException ();
222 }
223
224 public void SetScriptState(UUID itemID, bool state)
225 {
226 throw new System.NotImplementedException ();
227 }
228
229 public void SetState(UUID itemID, string newState)
230 {
231 throw new System.NotImplementedException ();
232 }
233
234 public void ApiResetScript(UUID itemID)
235 {
236 throw new System.NotImplementedException ();
237 }
238
239 public void ResetScript (UUID itemID)
240 {
241 throw new System.NotImplementedException ();
242 }
243
244 public IScriptApi GetApi(UUID itemID, string name)
245 {
246 throw new System.NotImplementedException ();
247 }
248
249 public Scene World { get { return m_scene; } }
250
251 public IScriptModule ScriptModule { get { return this; } }
252
253 public string ScriptEnginePath { get { throw new System.NotImplementedException (); }}
254
255 public string ScriptClassName { get { throw new System.NotImplementedException (); } }
256
257 public string ScriptBaseClassName { get { throw new System.NotImplementedException (); } }
258
259 public string[] ScriptReferencedAssemblies { get { throw new System.NotImplementedException (); } }
260
261 public ParameterInfo[] ScriptBaseClassParameters { get { throw new System.NotImplementedException (); } }
262
263 public void ClearPostedEvents()
264 {
265 PostedEvents.Clear();
266 }
267
268 public void SleepScript(UUID itemID, int delay)
269 {
270 }
271 }
272}
diff --git a/OpenSim/Tests/Common/Mock/TestClient.cs b/OpenSim/Tests/Common/Mock/TestClient.cs
new file mode 100644
index 0000000..0e1bc8f
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestClient.cs
@@ -0,0 +1,1323 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Net;
31using System.Reflection;
32using System.Threading;
33using log4net;
34using OpenMetaverse;
35using OpenMetaverse.Packets;
36using OpenSim.Framework;
37using OpenSim.Region.Framework.Interfaces;
38using OpenSim.Region.Framework.Scenes;
39using OpenSim.Framework.Client;
40
41namespace OpenSim.Tests.Common
42{
43 public class TestClient : IClientAPI, IClientCore
44 {
45 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46
47 EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing");
48
49 private Scene m_scene;
50
51 // Properties so that we can get at received data for test purposes
52 public List<uint> ReceivedKills { get; private set; }
53 public List<UUID> ReceivedOfflineNotifications { get; private set; }
54 public List<UUID> ReceivedOnlineNotifications { get; private set; }
55 public List<UUID> ReceivedFriendshipTerminations { get; private set; }
56
57 public List<ImageDataPacket> SentImageDataPackets { get; private set; }
58 public List<ImagePacketPacket> SentImagePacketPackets { get; private set; }
59 public List<ImageNotInDatabasePacket> SentImageNotInDatabasePackets { get; private set; }
60
61 // Test client specific events - for use by tests to implement some IClientAPI behaviour.
62 public event Action<RegionInfo, Vector3, Vector3> OnReceivedMoveAgentIntoRegion;
63 public event Action<ulong, IPEndPoint> OnTestClientInformClientOfNeighbour;
64 public event TestClientOnSendRegionTeleportDelegate OnTestClientSendRegionTeleport;
65
66 public event Action<ISceneEntity, PrimUpdateFlags> OnReceivedEntityUpdate;
67
68 public event OnReceivedChatMessageDelegate OnReceivedChatMessage;
69 public event Action<GridInstantMessage> OnReceivedInstantMessage;
70
71 public event Action<UUID> OnReceivedSendRebakeAvatarTextures;
72
73 public delegate void TestClientOnSendRegionTeleportDelegate(
74 ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
75 uint locationID, uint flags, string capsURL);
76
77 public delegate void OnReceivedChatMessageDelegate(
78 string message, byte type, Vector3 fromPos, string fromName,
79 UUID fromAgentID, UUID ownerID, byte source, byte audible);
80
81
82// disable warning: public events, part of the public API
83#pragma warning disable 67
84
85 public event Action<IClientAPI> OnLogout;
86 public event ObjectPermissions OnObjectPermissions;
87
88 public event MoneyTransferRequest OnMoneyTransferRequest;
89 public event ParcelBuy OnParcelBuy;
90 public event Action<IClientAPI> OnConnectionClosed;
91
92 public event ImprovedInstantMessage OnInstantMessage;
93 public event ChatMessage OnChatFromClient;
94 public event TextureRequest OnRequestTexture;
95 public event RezObject OnRezObject;
96 public event ModifyTerrain OnModifyTerrain;
97 public event BakeTerrain OnBakeTerrain;
98 public event SetAppearance OnSetAppearance;
99 public event AvatarNowWearing OnAvatarNowWearing;
100 public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
101 public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
102 public event UUIDNameRequest OnDetachAttachmentIntoInv;
103 public event ObjectAttach OnObjectAttach;
104 public event ObjectDeselect OnObjectDetach;
105 public event ObjectDrop OnObjectDrop;
106 public event StartAnim OnStartAnim;
107 public event StopAnim OnStopAnim;
108 public event LinkObjects OnLinkObjects;
109 public event DelinkObjects OnDelinkObjects;
110 public event RequestMapBlocks OnRequestMapBlocks;
111 public event RequestMapName OnMapNameRequest;
112 public event TeleportLocationRequest OnTeleportLocationRequest;
113 public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
114 public event TeleportCancel OnTeleportCancel;
115 public event DisconnectUser OnDisconnectUser;
116 public event RequestAvatarProperties OnRequestAvatarProperties;
117 public event SetAlwaysRun OnSetAlwaysRun;
118
119 public event DeRezObject OnDeRezObject;
120 public event Action<IClientAPI> OnRegionHandShakeReply;
121 public event GenericCall1 OnRequestWearables;
122 public event Action<IClientAPI, bool> OnCompleteMovementToRegion;
123 public event UpdateAgent OnPreAgentUpdate;
124 public event UpdateAgent OnAgentUpdate;
125 public event UpdateAgent OnAgentCameraUpdate;
126 public event AgentRequestSit OnAgentRequestSit;
127 public event AgentSit OnAgentSit;
128 public event AvatarPickerRequest OnAvatarPickerRequest;
129 public event Action<IClientAPI> OnRequestAvatarsData;
130 public event AddNewPrim OnAddPrim;
131 public event RequestGodlikePowers OnRequestGodlikePowers;
132 public event GodKickUser OnGodKickUser;
133 public event ObjectDuplicate OnObjectDuplicate;
134 public event GrabObject OnGrabObject;
135 public event DeGrabObject OnDeGrabObject;
136 public event MoveObject OnGrabUpdate;
137 public event SpinStart OnSpinStart;
138 public event SpinObject OnSpinUpdate;
139 public event SpinStop OnSpinStop;
140 public event ViewerEffectEventHandler OnViewerEffect;
141
142 public event FetchInventory OnAgentDataUpdateRequest;
143 public event TeleportLocationRequest OnSetStartLocationRequest;
144
145 public event UpdateShape OnUpdatePrimShape;
146 public event ObjectExtraParams OnUpdateExtraParams;
147 public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
148 public event ObjectSelect OnObjectSelect;
149 public event ObjectRequest OnObjectRequest;
150 public event GenericCall7 OnObjectDescription;
151 public event GenericCall7 OnObjectName;
152 public event GenericCall7 OnObjectClickAction;
153 public event GenericCall7 OnObjectMaterial;
154 public event UpdatePrimFlags OnUpdatePrimFlags;
155 public event UpdatePrimTexture OnUpdatePrimTexture;
156 public event UpdateVector OnUpdatePrimGroupPosition;
157 public event UpdateVector OnUpdatePrimSinglePosition;
158 public event UpdatePrimRotation OnUpdatePrimGroupRotation;
159 public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
160 public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
161 public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
162 public event UpdateVector OnUpdatePrimScale;
163 public event UpdateVector OnUpdatePrimGroupScale;
164 public event StatusChange OnChildAgentStatus;
165 public event GenericCall2 OnStopMovement;
166 public event Action<UUID> OnRemoveAvatar;
167
168 public event CreateNewInventoryItem OnCreateNewInventoryItem;
169 public event LinkInventoryItem OnLinkInventoryItem;
170 public event CreateInventoryFolder OnCreateNewInventoryFolder;
171 public event UpdateInventoryFolder OnUpdateInventoryFolder;
172 public event MoveInventoryFolder OnMoveInventoryFolder;
173 public event RemoveInventoryFolder OnRemoveInventoryFolder;
174 public event RemoveInventoryItem OnRemoveInventoryItem;
175 public event FetchInventoryDescendents OnFetchInventoryDescendents;
176 public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
177 public event FetchInventory OnFetchInventory;
178 public event RequestTaskInventory OnRequestTaskInventory;
179 public event UpdateInventoryItem OnUpdateInventoryItem;
180 public event CopyInventoryItem OnCopyInventoryItem;
181 public event MoveInventoryItem OnMoveInventoryItem;
182 public event UDPAssetUploadRequest OnAssetUploadRequest;
183 public event RequestTerrain OnRequestTerrain;
184 public event RequestTerrain OnUploadTerrain;
185 public event XferReceive OnXferReceive;
186 public event RequestXfer OnRequestXfer;
187 public event ConfirmXfer OnConfirmXfer;
188 public event AbortXfer OnAbortXfer;
189 public event RezScript OnRezScript;
190 public event UpdateTaskInventory OnUpdateTaskInventory;
191 public event MoveTaskInventory OnMoveTaskItem;
192 public event RemoveTaskInventory OnRemoveTaskItem;
193 public event RequestAsset OnRequestAsset;
194 public event GenericMessage OnGenericMessage;
195 public event UUIDNameRequest OnNameFromUUIDRequest;
196 public event UUIDNameRequest OnUUIDGroupNameRequest;
197
198 public event ParcelPropertiesRequest OnParcelPropertiesRequest;
199 public event ParcelDivideRequest OnParcelDivideRequest;
200 public event ParcelJoinRequest OnParcelJoinRequest;
201 public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
202 public event ParcelAbandonRequest OnParcelAbandonRequest;
203 public event ParcelGodForceOwner OnParcelGodForceOwner;
204 public event ParcelReclaim OnParcelReclaim;
205 public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
206 public event ParcelAccessListRequest OnParcelAccessListRequest;
207 public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
208 public event ParcelSelectObjects OnParcelSelectObjects;
209 public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
210 public event ParcelDeedToGroup OnParcelDeedToGroup;
211 public event ObjectDeselect OnObjectDeselect;
212 public event RegionInfoRequest OnRegionInfoRequest;
213 public event EstateCovenantRequest OnEstateCovenantRequest;
214 public event EstateChangeInfo OnEstateChangeInfo;
215 public event EstateManageTelehub OnEstateManageTelehub;
216 public event CachedTextureRequest OnCachedTextureRequest;
217
218 public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
219
220 public event FriendActionDelegate OnApproveFriendRequest;
221 public event FriendActionDelegate OnDenyFriendRequest;
222 public event FriendshipTermination OnTerminateFriendship;
223 public event GrantUserFriendRights OnGrantUserRights;
224
225 public event EconomyDataRequest OnEconomyDataRequest;
226 public event MoneyBalanceRequest OnMoneyBalanceRequest;
227 public event UpdateAvatarProperties OnUpdateAvatarProperties;
228
229 public event ObjectIncludeInSearch OnObjectIncludeInSearch;
230 public event UUIDNameRequest OnTeleportHomeRequest;
231
232 public event ScriptAnswer OnScriptAnswer;
233 public event RequestPayPrice OnRequestPayPrice;
234 public event ObjectSaleInfo OnObjectSaleInfo;
235 public event ObjectBuy OnObjectBuy;
236 public event BuyObjectInventory OnBuyObjectInventory;
237 public event AgentSit OnUndo;
238 public event AgentSit OnRedo;
239 public event LandUndo OnLandUndo;
240
241 public event ForceReleaseControls OnForceReleaseControls;
242
243 public event GodLandStatRequest OnLandStatRequest;
244 public event RequestObjectPropertiesFamily OnObjectGroupRequest;
245
246 public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
247 public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
248 public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
249 public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
250 public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
251 public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
252 public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
253 public event EstateRestartSimRequest OnEstateRestartSimRequest;
254 public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
255 public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
256 public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
257 public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
258 public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
259 public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
260 public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
261 public event ScriptReset OnScriptReset;
262 public event GetScriptRunning OnGetScriptRunning;
263 public event SetScriptRunning OnSetScriptRunning;
264 public event Action<Vector3, bool, bool> OnAutoPilotGo;
265
266 public event TerrainUnacked OnUnackedTerrain;
267
268 public event RegionHandleRequest OnRegionHandleRequest;
269 public event ParcelInfoRequest OnParcelInfoRequest;
270
271 public event ActivateGesture OnActivateGesture;
272 public event DeactivateGesture OnDeactivateGesture;
273 public event ObjectOwner OnObjectOwner;
274
275 public event DirPlacesQuery OnDirPlacesQuery;
276 public event DirFindQuery OnDirFindQuery;
277 public event DirLandQuery OnDirLandQuery;
278 public event DirPopularQuery OnDirPopularQuery;
279 public event DirClassifiedQuery OnDirClassifiedQuery;
280 public event EventInfoRequest OnEventInfoRequest;
281 public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
282
283 public event MapItemRequest OnMapItemRequest;
284
285 public event OfferCallingCard OnOfferCallingCard;
286 public event AcceptCallingCard OnAcceptCallingCard;
287 public event DeclineCallingCard OnDeclineCallingCard;
288
289 public event SoundTrigger OnSoundTrigger;
290
291 public event StartLure OnStartLure;
292 public event TeleportLureRequest OnTeleportLureRequest;
293 public event NetworkStats OnNetworkStatsUpdate;
294
295 public event ClassifiedInfoRequest OnClassifiedInfoRequest;
296 public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
297 public event ClassifiedDelete OnClassifiedDelete;
298 public event ClassifiedDelete OnClassifiedGodDelete;
299
300 public event EventNotificationAddRequest OnEventNotificationAddRequest;
301 public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
302 public event EventGodDelete OnEventGodDelete;
303
304 public event ParcelDwellRequest OnParcelDwellRequest;
305
306 public event UserInfoRequest OnUserInfoRequest;
307 public event UpdateUserInfo OnUpdateUserInfo;
308
309 public event RetrieveInstantMessages OnRetrieveInstantMessages;
310
311 public event PickDelete OnPickDelete;
312 public event PickGodDelete OnPickGodDelete;
313 public event PickInfoUpdate OnPickInfoUpdate;
314 public event AvatarNotesUpdate OnAvatarNotesUpdate;
315
316 public event MuteListRequest OnMuteListRequest;
317
318 public event AvatarInterestUpdate OnAvatarInterestUpdate;
319
320 public event PlacesQuery OnPlacesQuery;
321
322 public event FindAgentUpdate OnFindAgent;
323 public event TrackAgentUpdate OnTrackAgent;
324 public event NewUserReport OnUserReport;
325 public event SaveStateHandler OnSaveState;
326 public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
327 public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
328 public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
329 public event FreezeUserUpdate OnParcelFreezeUser;
330 public event EjectUserUpdate OnParcelEjectUser;
331 public event ParcelBuyPass OnParcelBuyPass;
332 public event ParcelGodMark OnParcelGodMark;
333 public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest;
334 public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
335 public event SimWideDeletesDelegate OnSimWideDeletes;
336 public event SendPostcard OnSendPostcard;
337 public event MuteListEntryUpdate OnUpdateMuteListEntry;
338 public event MuteListEntryRemove OnRemoveMuteListEntry;
339 public event GodlikeMessage onGodlikeMessage;
340 public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate;
341
342#pragma warning restore 67
343
344 /// <value>
345 /// This agent's UUID
346 /// </value>
347 private UUID m_agentId;
348
349 public ISceneAgent SceneAgent { get; set; }
350
351 /// <value>
352 /// The last caps seed url that this client was given.
353 /// </value>
354 public string CapsSeedUrl;
355
356 private Vector3 startPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 2);
357
358 public virtual Vector3 StartPos
359 {
360 get { return startPos; }
361 set { }
362 }
363
364 public virtual UUID AgentId
365 {
366 get { return m_agentId; }
367 }
368
369 public UUID SessionId { get; set; }
370
371 public UUID SecureSessionId { get; set; }
372
373 public virtual string FirstName
374 {
375 get { return m_firstName; }
376 }
377 private string m_firstName;
378
379 public virtual string LastName
380 {
381 get { return m_lastName; }
382 }
383 private string m_lastName;
384
385 public virtual String Name
386 {
387 get { return FirstName + " " + LastName; }
388 }
389
390 public bool IsActive
391 {
392 get { return true; }
393 set { }
394 }
395
396 public bool IsLoggingOut { get; set; }
397
398 public UUID ActiveGroupId
399 {
400 get { return UUID.Zero; }
401 }
402
403 public string ActiveGroupName
404 {
405 get { return String.Empty; }
406 }
407
408 public ulong ActiveGroupPowers
409 {
410 get { return 0; }
411 }
412
413 public bool IsGroupMember(UUID groupID)
414 {
415 return false;
416 }
417
418 public ulong GetGroupPowers(UUID groupID)
419 {
420 return 0;
421 }
422
423 public virtual int NextAnimationSequenceNumber
424 {
425 get { return 1; }
426 }
427
428 public IScene Scene
429 {
430 get { return m_scene; }
431 }
432
433 public bool SendLogoutPacketWhenClosing
434 {
435 set { }
436 }
437
438 private uint m_circuitCode;
439
440 public uint CircuitCode
441 {
442 get { return m_circuitCode; }
443 set { m_circuitCode = value; }
444 }
445
446 public IPEndPoint RemoteEndPoint
447 {
448 get { return new IPEndPoint(IPAddress.Loopback, (ushort)m_circuitCode); }
449 }
450
451 /// <summary>
452 /// Constructor
453 /// </summary>
454 /// <param name="agentData"></param>
455 /// <param name="scene"></param>
456 /// <param name="sceneManager"></param>
457 public TestClient(AgentCircuitData agentData, Scene scene)
458 {
459 m_agentId = agentData.AgentID;
460 m_firstName = agentData.firstname;
461 m_lastName = agentData.lastname;
462 m_circuitCode = agentData.circuitcode;
463 m_scene = scene;
464 SessionId = agentData.SessionID;
465 SecureSessionId = agentData.SecureSessionID;
466 CapsSeedUrl = agentData.CapsPath;
467
468 ReceivedKills = new List<uint>();
469 ReceivedOfflineNotifications = new List<UUID>();
470 ReceivedOnlineNotifications = new List<UUID>();
471 ReceivedFriendshipTerminations = new List<UUID>();
472
473 SentImageDataPackets = new List<ImageDataPacket>();
474 SentImagePacketPackets = new List<ImagePacketPacket>();
475 SentImageNotInDatabasePackets = new List<ImageNotInDatabasePacket>();
476 }
477
478 /// <summary>
479 /// Trigger chat coming from this connection.
480 /// </summary>
481 /// <param name="channel"></param>
482 /// <param name="type"></param>
483 /// <param name="message"></param>
484 public bool Chat(int channel, ChatTypeEnum type, string message)
485 {
486 ChatMessage handlerChatFromClient = OnChatFromClient;
487
488 if (handlerChatFromClient != null)
489 {
490 OSChatMessage args = new OSChatMessage();
491 args.Channel = channel;
492 args.From = Name;
493 args.Message = message;
494 args.Type = type;
495
496 args.Scene = Scene;
497 args.Sender = this;
498 args.SenderUUID = AgentId;
499
500 handlerChatFromClient(this, args);
501 }
502
503 return true;
504 }
505
506 /// <summary>
507 /// Attempt a teleport to the given region.
508 /// </summary>
509 /// <param name="regionHandle"></param>
510 /// <param name="position"></param>
511 /// <param name="lookAt"></param>
512 public void Teleport(ulong regionHandle, Vector3 position, Vector3 lookAt)
513 {
514 OnTeleportLocationRequest(this, regionHandle, position, lookAt, 16);
515 }
516
517 public void CompleteMovement()
518 {
519 if (OnCompleteMovementToRegion != null)
520 OnCompleteMovementToRegion(this, true);
521 }
522
523 /// <summary>
524 /// Emulate sending an IM from the viewer to the simulator.
525 /// </summary>
526 /// <param name='im'></param>
527 public void HandleImprovedInstantMessage(GridInstantMessage im)
528 {
529 ImprovedInstantMessage handlerInstantMessage = OnInstantMessage;
530
531 if (handlerInstantMessage != null)
532 handlerInstantMessage(this, im);
533 }
534
535 public virtual void ActivateGesture(UUID assetId, UUID gestureId)
536 {
537 }
538
539 public virtual void SendWearables(AvatarWearable[] wearables, int serial)
540 {
541 }
542
543 public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry)
544 {
545 }
546
547 public void SendCachedTextureResponse(ISceneEntity avatar, int serial, List<CachedTextureResponseArg> cachedTextures)
548 {
549
550 }
551
552 public virtual void Kick(string message)
553 {
554 }
555
556 public virtual void SendStartPingCheck(byte seq)
557 {
558 }
559
560 public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
561 {
562 }
563
564 public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
565 {
566 }
567
568 public virtual void SendKillObject(List<uint> localID)
569 {
570 ReceivedKills.AddRange(localID);
571 }
572
573 public virtual void SetChildAgentThrottle(byte[] throttle)
574 {
575 }
576
577 public byte[] GetThrottlesPacked(float multiplier)
578 {
579 return new byte[0];
580 }
581
582 public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs)
583 {
584 }
585
586 public virtual void SendChatMessage(
587 string message, byte type, Vector3 fromPos, string fromName,
588 UUID fromAgentID, UUID ownerID, byte source, byte audible)
589 {
590// Console.WriteLine("mmm {0} {1} {2}", message, Name, AgentId);
591 if (OnReceivedChatMessage != null)
592 OnReceivedChatMessage(message, type, fromPos, fromName, fromAgentID, ownerID, source, audible);
593 }
594
595 public void SendInstantMessage(GridInstantMessage im)
596 {
597 if (OnReceivedInstantMessage != null)
598 OnReceivedInstantMessage(im);
599 }
600
601 public void SendGenericMessage(string method, UUID invoice, List<string> message)
602 {
603
604 }
605
606 public void SendGenericMessage(string method, UUID invoice, List<byte[]> message)
607 {
608
609 }
610
611 public virtual void SendLayerData(float[] map)
612 {
613 }
614
615 public virtual void SendLayerData(int px, int py, float[] map)
616 {
617 }
618 public virtual void SendLayerData(int px, int py, float[] map, bool track)
619 {
620 }
621
622 public virtual void SendWindData(Vector2[] windSpeeds) { }
623
624 public virtual void SendCloudData(float[] cloudCover) { }
625
626 public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
627 {
628 if (OnReceivedMoveAgentIntoRegion != null)
629 OnReceivedMoveAgentIntoRegion(regInfo, pos, look);
630 }
631
632 public virtual AgentCircuitData RequestClientInfo()
633 {
634 AgentCircuitData agentData = new AgentCircuitData();
635 agentData.AgentID = AgentId;
636 agentData.SessionID = SessionId;
637 agentData.SecureSessionID = UUID.Zero;
638 agentData.circuitcode = m_circuitCode;
639 agentData.child = false;
640 agentData.firstname = m_firstName;
641 agentData.lastname = m_lastName;
642
643 ICapabilitiesModule capsModule = m_scene.RequestModuleInterface<ICapabilitiesModule>();
644 if (capsModule != null)
645 {
646 agentData.CapsPath = capsModule.GetCapsPath(m_agentId);
647 agentData.ChildrenCapSeeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(m_agentId));
648 }
649
650 return agentData;
651 }
652
653 public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint)
654 {
655 if (OnTestClientInformClientOfNeighbour != null)
656 OnTestClientInformClientOfNeighbour(neighbourHandle, neighbourExternalEndPoint);
657 }
658
659 public virtual void SendRegionTeleport(
660 ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
661 uint locationID, uint flags, string capsURL)
662 {
663 m_log.DebugFormat(
664 "[TEST CLIENT]: Received SendRegionTeleport for {0} {1} on {2}", m_firstName, m_lastName, m_scene.Name);
665
666 CapsSeedUrl = capsURL;
667
668 if (OnTestClientSendRegionTeleport != null)
669 OnTestClientSendRegionTeleport(
670 regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL);
671 }
672
673 public virtual void SendTeleportFailed(string reason)
674 {
675 m_log.DebugFormat(
676 "[TEST CLIENT]: Teleport failed for {0} {1} on {2} with reason {3}",
677 m_firstName, m_lastName, m_scene.Name, reason);
678 }
679
680 public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt,
681 IPEndPoint newRegionExternalEndPoint, string capsURL)
682 {
683 // This is supposed to send a packet to the client telling it's ready to start region crossing.
684 // Instead I will just signal I'm ready, mimicking the communication behavior.
685 // It's ugly, but avoids needless communication setup. This is used in ScenePresenceTests.cs.
686 // Arthur V.
687
688 wh.Set();
689 }
690
691 public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
692 {
693 }
694
695 public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags)
696 {
697 }
698
699 public virtual void SendTeleportStart(uint flags)
700 {
701 }
702
703 public void SendTeleportProgress(uint flags, string message)
704 {
705 }
706
707 public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance, int transactionType, UUID sourceID, bool sourceIsGroup, UUID destID, bool destIsGroup, int amount, string item)
708 {
709 }
710
711 public virtual void SendPayPrice(UUID objectID, int[] payPrice)
712 {
713 }
714
715 public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
716 {
717 }
718
719 public virtual void SendDialog(string objectname, UUID objectID, UUID ownerID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
720 {
721 }
722
723 public void SendAvatarDataImmediate(ISceneEntity avatar)
724 {
725 }
726
727 public void SendEntityUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags)
728 {
729 if (OnReceivedEntityUpdate != null)
730 OnReceivedEntityUpdate(entity, updateFlags);
731 }
732
733 public void ReprioritizeUpdates()
734 {
735 }
736
737 public void FlushPrimUpdates()
738 {
739 }
740
741 public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID,
742 List<InventoryItemBase> items,
743 List<InventoryFolderBase> folders,
744 int version,
745 bool fetchFolders,
746 bool fetchItems)
747 {
748 }
749
750 public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item)
751 {
752 }
753
754 public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID)
755 {
756 }
757
758 public virtual void SendRemoveInventoryItem(UUID itemID)
759 {
760 }
761
762 public virtual void SendBulkUpdateInventory(InventoryNodeBase node)
763 {
764 }
765
766 public void SendTakeControls(int controls, bool passToAgent, bool TakeControls)
767 {
768 }
769
770 public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName)
771 {
772 }
773
774 public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data)
775 {
776 }
777
778 public virtual void SendAbortXferPacket(ulong xferID)
779 {
780
781 }
782
783 public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit,
784 int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor,
785 int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay,
786 int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
787 {
788 }
789
790 public virtual void SendNameReply(UUID profileId, string firstname, string lastname)
791 {
792 }
793
794 public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID)
795 {
796 }
797
798 public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain,
799 byte flags)
800 {
801 }
802
803 public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain)
804 {
805 }
806
807 public void SendAttachedSoundGainChange(UUID objectID, float gain)
808 {
809
810 }
811
812 public void SendAlertMessage(string message)
813 {
814 }
815
816 public void SendAgentAlertMessage(string message, bool modal)
817 {
818 }
819
820 public void SendSystemAlertMessage(string message)
821 {
822 }
823
824 public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message,
825 string url)
826 {
827 }
828
829 public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
830 {
831 if (OnRegionHandShakeReply != null)
832 {
833 OnRegionHandShakeReply(this);
834 }
835 }
836
837 public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
838 {
839 }
840
841 public void SendConfirmXfer(ulong xferID, uint PacketID)
842 {
843 }
844
845 public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName)
846 {
847 }
848
849 public void SendInitiateDownload(string simFileName, string clientFileName)
850 {
851 }
852
853 public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
854 {
855 ImageDataPacket im = new ImageDataPacket();
856 im.Header.Reliable = false;
857 im.ImageID.Packets = numParts;
858 im.ImageID.ID = ImageUUID;
859
860 if (ImageSize > 0)
861 im.ImageID.Size = ImageSize;
862
863 im.ImageData.Data = ImageData;
864 im.ImageID.Codec = imageCodec;
865 im.Header.Zerocoded = true;
866 SentImageDataPackets.Add(im);
867 }
868
869 public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
870 {
871 ImagePacketPacket im = new ImagePacketPacket();
872 im.Header.Reliable = false;
873 im.ImageID.Packet = partNumber;
874 im.ImageID.ID = imageUuid;
875 im.ImageData.Data = imageData;
876 SentImagePacketPackets.Add(im);
877 }
878
879 public void SendImageNotFound(UUID imageid)
880 {
881 ImageNotInDatabasePacket p = new ImageNotInDatabasePacket();
882 p.ImageID.ID = imageid;
883
884 SentImageNotInDatabasePackets.Add(p);
885 }
886
887 public void SendShutdownConnectionNotice()
888 {
889 }
890
891 public void SendSimStats(SimStats stats)
892 {
893 }
894
895 public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags)
896 {
897 }
898
899 public void SendObjectPropertiesReply(ISceneEntity entity)
900 {
901 }
902
903 public void SendAgentOffline(UUID[] agentIDs)
904 {
905 ReceivedOfflineNotifications.AddRange(agentIDs);
906 }
907
908 public void SendAgentOnline(UUID[] agentIDs)
909 {
910 ReceivedOnlineNotifications.AddRange(agentIDs);
911 }
912
913 public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot,
914 Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
915 {
916 }
917
918 public void SendAdminResponse(UUID Token, uint AdminLevel)
919 {
920
921 }
922
923 public void SendGroupMembership(GroupMembershipData[] GroupMembership)
924 {
925
926 }
927
928 public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase)
929 {
930 }
931
932 public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
933 {
934 }
935
936 public void SendViewerTime(int phase)
937 {
938 }
939
940 public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember,
941 string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL,
942 UUID partnerID)
943 {
944 }
945
946 public int DebugPacketLevel { get; set; }
947
948 public void InPacket(object NewPack)
949 {
950 }
951
952 public void ProcessInPacket(Packet NewPack)
953 {
954 }
955
956 /// <summary>
957 /// This is a TestClient only method to do shutdown tasks that are normally carried out by LLUDPServer.RemoveClient()
958 /// </summary>
959 public void Logout()
960 {
961 // We must set this here so that the presence is removed from the PresenceService by the PresenceDetector
962 IsLoggingOut = true;
963
964 Close();
965 }
966
967 public void Close()
968 {
969 Close(false);
970 }
971
972 public void Close(bool force)
973 {
974 // Fire the callback for this connection closing
975 // This is necesary to get the presence detector to notice that a client has logged out.
976 if (OnConnectionClosed != null)
977 OnConnectionClosed(this);
978
979 m_scene.RemoveClient(AgentId, true);
980 }
981
982 public void Start()
983 {
984 throw new NotImplementedException();
985 }
986
987 public void Stop()
988 {
989 }
990
991 public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message)
992 {
993
994 }
995 public void SendLogoutPacket()
996 {
997 }
998
999 public void Terminate()
1000 {
1001 }
1002
1003 public ClientInfo GetClientInfo()
1004 {
1005 return null;
1006 }
1007
1008 public void SetClientInfo(ClientInfo info)
1009 {
1010 }
1011
1012 public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question)
1013 {
1014 }
1015 public void SendHealth(float health)
1016 {
1017 }
1018
1019 public void SendTelehubInfo(UUID ObjectID, string ObjectName, Vector3 ObjectPos, Quaternion ObjectRot, List<Vector3> SpawnPoint)
1020 {
1021 }
1022
1023 public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID)
1024 {
1025 }
1026
1027 public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID)
1028 {
1029 }
1030
1031 public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
1032 {
1033 }
1034
1035 public void SendEstateCovenantInformation(UUID covenant)
1036 {
1037 }
1038
1039 public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, uint covenantChanged, string abuseEmail, UUID estateOwner)
1040 {
1041 }
1042
1043 public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, ILandObject lo, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
1044 {
1045 }
1046
1047 public void SendLandAccessListData(List<LandAccessEntry> accessList, uint accessFlag, int localLandID)
1048 {
1049 }
1050
1051 public void SendForceClientSelectObjects(List<uint> objectIDs)
1052 {
1053 }
1054
1055 public void SendCameraConstraint(Vector4 ConstraintPlane)
1056 {
1057 }
1058
1059 public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount)
1060 {
1061 }
1062
1063 public void SendLandParcelOverlay(byte[] data, int sequence_id)
1064 {
1065 }
1066
1067 public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
1068 {
1069 }
1070
1071 public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType,
1072 string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
1073 {
1074 }
1075
1076 public void SendGroupNameReply(UUID groupLLUID, string GroupName)
1077 {
1078 }
1079
1080 public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia)
1081 {
1082 }
1083
1084 public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running)
1085 {
1086 }
1087
1088 public void SendAsset(AssetRequestToClient req)
1089 {
1090 }
1091
1092 public void SendTexture(AssetBase TextureAsset)
1093 {
1094
1095 }
1096
1097 public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters)
1098 {
1099 }
1100
1101 public void SendClearFollowCamProperties (UUID objectID)
1102 {
1103 }
1104
1105 public void SendRegionHandle (UUID regoinID, ulong handle)
1106 {
1107 }
1108
1109 public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
1110 {
1111 }
1112
1113 public void SetClientOption(string option, string value)
1114 {
1115 }
1116
1117 public string GetClientOption(string option)
1118 {
1119 return string.Empty;
1120 }
1121
1122 public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
1123 {
1124 }
1125
1126 public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data)
1127 {
1128 }
1129
1130 public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data)
1131 {
1132 }
1133
1134 public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data)
1135 {
1136 }
1137
1138 public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data)
1139 {
1140 }
1141
1142 public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data)
1143 {
1144 }
1145
1146 public void SendDirLandReply(UUID queryID, DirLandReplyData[] data)
1147 {
1148 }
1149
1150 public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data)
1151 {
1152 }
1153
1154 public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
1155 {
1156 }
1157
1158 public void SendEventInfoReply (EventData info)
1159 {
1160 }
1161
1162 public void SendOfferCallingCard (UUID destID, UUID transactionID)
1163 {
1164 }
1165
1166 public void SendAcceptCallingCard (UUID transactionID)
1167 {
1168 }
1169
1170 public void SendDeclineCallingCard (UUID transactionID)
1171 {
1172 }
1173
1174 public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
1175 {
1176 }
1177
1178 public void SendJoinGroupReply(UUID groupID, bool success)
1179 {
1180 }
1181
1182 public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss)
1183 {
1184 }
1185
1186 public void SendLeaveGroupReply(UUID groupID, bool success)
1187 {
1188 }
1189
1190 public void SendTerminateFriend(UUID exFriendID)
1191 {
1192 ReceivedFriendshipTerminations.Add(exFriendID);
1193 }
1194
1195 public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
1196 {
1197 //throw new NotImplementedException();
1198 return false;
1199 }
1200
1201 public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name)
1202 {
1203 }
1204
1205 public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
1206 {
1207 }
1208
1209 public void SendAgentDropGroup(UUID groupID)
1210 {
1211 }
1212
1213 public void SendAvatarNotesReply(UUID targetID, string text)
1214 {
1215 }
1216
1217 public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks)
1218 {
1219 }
1220
1221 public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds)
1222 {
1223 }
1224
1225 public void SendParcelDwellReply(int localID, UUID parcelID, float dwell)
1226 {
1227 }
1228
1229 public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
1230 {
1231 }
1232
1233 public void SendCreateGroupReply(UUID groupID, bool success, string message)
1234 {
1235 }
1236
1237 public void RefreshGroupMembership()
1238 {
1239 }
1240
1241 public void SendUseCachedMuteList()
1242 {
1243 }
1244
1245 public void SendMuteListUpdate(string filename)
1246 {
1247 }
1248
1249 public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled)
1250 {
1251 }
1252
1253 public bool TryGet<T>(out T iface)
1254 {
1255 iface = default(T);
1256 return false;
1257 }
1258
1259 public T Get<T>()
1260 {
1261 return default(T);
1262 }
1263
1264 public void Disconnect(string reason)
1265 {
1266 }
1267
1268 public void Disconnect()
1269 {
1270 }
1271
1272 public void SendRebakeAvatarTextures(UUID textureID)
1273 {
1274 if (OnReceivedSendRebakeAvatarTextures != null)
1275 OnReceivedSendRebakeAvatarTextures(textureID);
1276 }
1277
1278 public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages)
1279 {
1280 }
1281
1282 public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt)
1283 {
1284 }
1285
1286 public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier)
1287 {
1288 }
1289
1290 public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt)
1291 {
1292 }
1293
1294 public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes)
1295 {
1296 }
1297
1298 public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
1299 {
1300 }
1301
1302 public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
1303 {
1304 }
1305
1306 public void SendTextBoxRequest(string message, int chatChannel, string objectname, UUID ownerID, string ownerFirstName, string ownerLastName, UUID objectId)
1307 {
1308 }
1309
1310 public void SendAgentTerseUpdate(ISceneEntity presence)
1311 {
1312 }
1313
1314 public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data)
1315 {
1316 }
1317
1318 public void SendPartPhysicsProprieties(ISceneEntity entity)
1319 {
1320 }
1321
1322 }
1323}
diff --git a/OpenSim/Tests/Common/Mock/TestEventQueueGetModule.cs b/OpenSim/Tests/Common/Mock/TestEventQueueGetModule.cs
new file mode 100644
index 0000000..f2bae58
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestEventQueueGetModule.cs
@@ -0,0 +1,182 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Net;
32using System.Reflection;
33using System.Threading;
34using log4net;
35using Nini.Config;
36using Mono.Addins;
37using OpenMetaverse;
38using OpenMetaverse.StructuredData;
39using OpenSim.Framework;
40using OpenSim.Framework.Servers;
41using OpenSim.Region.ClientStack.Linden;
42using OpenSim.Region.Framework.Interfaces;
43using OpenSim.Region.Framework.Scenes;
44
45namespace OpenSim.Tests.Common
46{
47 public class TestEventQueueGetModule : IEventQueue, INonSharedRegionModule
48 {
49 public class Event
50 {
51 public string Name { get; set; }
52 public object[] Args { get; set; }
53
54 public Event(string name, object[] args)
55 {
56 name = Name;
57 args = Args;
58 }
59 }
60
61 public Dictionary<UUID, List<Event>> Events { get; set; }
62
63 public void Initialise(IConfigSource source) {}
64
65 public void Close() {}
66
67 public void AddRegion(Scene scene)
68 {
69 Events = new Dictionary<UUID, List<Event>>();
70 scene.RegisterModuleInterface<IEventQueue>(this);
71 }
72
73 public void RemoveRegion (Scene scene) {}
74
75 public void RegionLoaded (Scene scene) {}
76
77 public string Name { get { return "TestEventQueueGetModule"; } }
78
79 public Type ReplaceableInterface { get { return null; } }
80
81 private void AddEvent(UUID avatarID, string name, params object[] args)
82 {
83 Console.WriteLine("Adding event {0} for {1}", name, avatarID);
84
85 List<Event> avEvents;
86
87 if (!Events.ContainsKey(avatarID))
88 {
89 avEvents = new List<Event>();
90 Events[avatarID] = avEvents;
91 }
92 else
93 {
94 avEvents = Events[avatarID];
95 }
96
97 avEvents.Add(new Event(name, args));
98 }
99
100 public void ClearEvents()
101 {
102 if (Events != null)
103 Events.Clear();
104 }
105
106 public bool Enqueue(OSD o, UUID avatarID)
107 {
108 AddEvent(avatarID, "Enqueue", o);
109 return true;
110 }
111
112 public void DisableSimulator(ulong handle, UUID avatarID)
113 {
114 AddEvent(avatarID, "DisableSimulator", handle);
115 }
116
117 public void EnableSimulator (ulong handle, IPEndPoint endPoint, UUID avatarID, int regionSizeX, int regionSizeY)
118 {
119 AddEvent(avatarID, "EnableSimulator", handle);
120 }
121
122 public void EstablishAgentCommunication (UUID avatarID, IPEndPoint endPoint, string capsPath,
123 ulong regionHandle, int regionSizeX, int regionSizeY)
124 {
125 AddEvent(avatarID, "EstablishAgentCommunication", endPoint, capsPath);
126 }
127
128 public void TeleportFinishEvent (ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
129 uint locationID, uint flags, string capsURL, UUID agentID, int regionSizeX, int regionSizeY)
130 {
131 AddEvent(agentID, "TeleportFinishEvent", regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL);
132 }
133
134 public void CrossRegion (ulong handle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint,
135 string capsURL, UUID avatarID, UUID sessionID, int regionSizeX, int regionSizeY)
136 {
137 AddEvent(avatarID, "CrossRegion", handle, pos, lookAt, newRegionExternalEndPoint, capsURL, sessionID);
138 }
139
140 public void ChatterboxInvitation(
141 UUID sessionID, string sessionName, UUID fromAgent, string message, UUID toAgent, string fromName,
142 byte dialog, uint timeStamp, bool offline, int parentEstateID, Vector3 position, uint ttl,
143 UUID transactionID, bool fromGroup, byte[] binaryBucket)
144 {
145 AddEvent(
146 toAgent, "ChatterboxInvitation", sessionID, sessionName, fromAgent, message, toAgent, fromName, dialog,
147 timeStamp, offline, parentEstateID, position, ttl, transactionID, fromGroup, binaryBucket);
148 }
149
150 public void ChatterBoxSessionAgentListUpdates (UUID sessionID, UUID fromAgent, UUID toAgent, bool canVoiceChat, bool isModerator, bool textMute)
151 {
152 AddEvent(toAgent, "ChatterBoxSessionAgentListUpdates", sessionID, fromAgent, canVoiceChat, isModerator, textMute);
153 }
154
155 public void ParcelProperties (OpenMetaverse.Messages.Linden.ParcelPropertiesMessage parcelPropertiesMessage, UUID avatarID)
156 {
157 AddEvent(avatarID, "ParcelProperties", parcelPropertiesMessage);
158 }
159
160 public void GroupMembership (OpenMetaverse.Packets.AgentGroupDataUpdatePacket groupUpdate, UUID avatarID)
161 {
162 AddEvent(avatarID, "GroupMembership", groupUpdate);
163 }
164
165 public OSD ScriptRunningEvent (UUID objectID, UUID itemID, bool running, bool mono)
166 {
167 Console.WriteLine("ONE");
168 throw new System.NotImplementedException ();
169 }
170
171 public OSD BuildEvent(string eventName, OSD eventBody)
172 {
173 Console.WriteLine("TWO");
174 throw new System.NotImplementedException ();
175 }
176
177 public void partPhysicsProperties (uint localID, byte physhapetype, float density, float friction, float bounce, float gravmod, UUID avatarID)
178 {
179 AddEvent(avatarID, "partPhysicsProperties", localID, physhapetype, density, friction, bounce, gravmod);
180 }
181 }
182} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/TestHttpClientContext.cs b/OpenSim/Tests/Common/Mock/TestHttpClientContext.cs
new file mode 100644
index 0000000..5a55b09
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestHttpClientContext.cs
@@ -0,0 +1,110 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.IO;
31using System.Net;
32using System.Net.Sockets;
33using System.Text;
34using HttpServer;
35using OpenSim.Framework;
36
37namespace OpenSim.Tests.Common
38{
39 public class TestHttpClientContext: IHttpClientContext
40 {
41 /// <summary>
42 /// Bodies of responses from the server.
43 /// </summary>
44 public string ResponseBody
45 {
46 get { return Encoding.UTF8.GetString(m_responseStream.ToArray()); }
47 }
48
49 public Byte[] ResponseBodyBytes
50 {
51 get{ return m_responseStream.ToArray(); }
52 }
53
54 private MemoryStream m_responseStream = new MemoryStream();
55
56 public bool IsSecured { get; set; }
57
58 public bool Secured
59 {
60 get { return IsSecured; }
61 set { IsSecured = value; }
62 }
63
64 public TestHttpClientContext(bool secured)
65 {
66 Secured = secured;
67 }
68
69 public void Disconnect(SocketError error)
70 {
71// Console.WriteLine("TestHttpClientContext.Disconnect Received disconnect with status {0}", error);
72 }
73
74 public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body) {Console.WriteLine("x");}
75 public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) {Console.WriteLine("xx");}
76 public void Respond(string body) { Console.WriteLine("xxx");}
77
78 public void Send(byte[] buffer)
79 {
80 // Getting header data here
81// Console.WriteLine("xxxx: Got {0}", Encoding.UTF8.GetString(buffer));
82 }
83
84 public void Send(byte[] buffer, int offset, int size)
85 {
86// Util.PrintCallStack();
87//
88// Console.WriteLine(
89// "TestHttpClientContext.Send(byte[], int, int) got offset={0}, size={1}, buffer={2}",
90// offset, size, Encoding.UTF8.GetString(buffer));
91
92 m_responseStream.Write(buffer, offset, size);
93 }
94
95 public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType) {Console.WriteLine("xxxxxx");}
96 public void Close() { }
97 public bool EndWhenDone { get { return false;} set { return;}}
98
99 public HTTPNetworkContext GiveMeTheNetworkStreamIKnowWhatImDoing()
100 {
101 return new HTTPNetworkContext();
102 }
103
104 public event EventHandler<DisconnectedEventArgs> Disconnected = delegate { };
105 /// <summary>
106 /// A request have been received in the context.
107 /// </summary>
108 public event EventHandler<RequestEventArgs> RequestReceived = delegate { };
109 }
110} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/TestHttpRequest.cs b/OpenSim/Tests/Common/Mock/TestHttpRequest.cs
new file mode 100644
index 0000000..b868895
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestHttpRequest.cs
@@ -0,0 +1,174 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Specialized;
30using System.IO;
31using HttpServer;
32using HttpServer.FormDecoders;
33
34namespace OpenSim.Tests.Common
35{
36 public class TestHttpRequest: IHttpRequest
37 {
38 private string _uriPath;
39 public bool BodyIsComplete
40 {
41 get { return true; }
42 }
43 public string[] AcceptTypes
44 {
45 get {return _acceptTypes; }
46 }
47 private string[] _acceptTypes;
48 public Stream Body
49 {
50 get { return _body; }
51 set { _body = value;}
52 }
53 private Stream _body;
54 public ConnectionType Connection
55 {
56 get { return _connection; }
57 set { _connection = value; }
58 }
59 private ConnectionType _connection;
60 public int ContentLength
61 {
62 get { return _contentLength; }
63 set { _contentLength = value; }
64 }
65 private int _contentLength;
66 public NameValueCollection Headers
67 {
68 get { return _headers; }
69 }
70 private NameValueCollection _headers = new NameValueCollection();
71
72 public string HttpVersion { get; set; }
73
74 public string Method
75 {
76 get { return _method; }
77 set { _method = value; }
78 }
79 private string _method = null;
80 public HttpInput QueryString
81 {
82 get { return _queryString; }
83 }
84 private HttpInput _queryString = null;
85 public Uri Uri
86 {
87 get { return _uri; }
88 set { _uri = value; }
89 }
90 private Uri _uri = null;
91 public string[] UriParts
92 {
93 get { return _uri.Segments; }
94 }
95 public HttpParam Param
96 {
97 get { return null; }
98 }
99 public HttpForm Form
100 {
101 get { return null; }
102 }
103 public bool IsAjax
104 {
105 get { return false; }
106 }
107 public RequestCookies Cookies
108 {
109 get { return null; }
110 }
111
112 public TestHttpRequest()
113 {
114 HttpVersion = "HTTP/1.1";
115 }
116
117 public TestHttpRequest(string contentEncoding, string contentType, string userAgent,
118 string remoteAddr, string remotePort, string[] acceptTypes,
119 ConnectionType connectionType, int contentLength, Uri uri) : base()
120 {
121 _headers["content-encoding"] = contentEncoding;
122 _headers["content-type"] = contentType;
123 _headers["user-agent"] = userAgent;
124 _headers["remote_addr"] = remoteAddr;
125 _headers["remote_port"] = remotePort;
126
127 _acceptTypes = acceptTypes;
128 _connection = connectionType;
129 _contentLength = contentLength;
130 _uri = uri;
131 }
132
133 public void DecodeBody(FormDecoderProvider providers) {}
134 public void SetCookies(RequestCookies cookies) {}
135 public void AddHeader(string name, string value)
136 {
137 _headers.Add(name, value);
138 }
139 public int AddToBody(byte[] bytes, int offset, int length)
140 {
141 return 0;
142 }
143 public void Clear() {}
144
145 public object Clone()
146 {
147 TestHttpRequest clone = new TestHttpRequest();
148 clone._acceptTypes = _acceptTypes;
149 clone._connection = _connection;
150 clone._contentLength = _contentLength;
151 clone._uri = _uri;
152 clone._headers = new NameValueCollection(_headers);
153
154 return clone;
155 }
156 public IHttpResponse CreateResponse(IHttpClientContext context)
157 {
158 return new HttpResponse(context, this);
159 }
160 /// <summary>
161 /// Path and query (will be merged with the host header) and put in Uri
162 /// </summary>
163 /// <see cref="Uri"/>
164 public string UriPath
165 {
166 get { return _uriPath; }
167 set
168 {
169 _uriPath = value;
170
171 }
172 }
173 }
174} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/TestHttpResponse.cs b/OpenSim/Tests/Common/Mock/TestHttpResponse.cs
new file mode 100644
index 0000000..ff47c10
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestHttpResponse.cs
@@ -0,0 +1,171 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.IO;
30using System.Net;
31using System.Text;
32using HttpServer;
33
34namespace OpenSim.Tests.Common
35{
36 public class TestHttpResponse: IHttpResponse
37 {
38 public Stream Body
39 {
40 get { return _body; }
41
42 set { _body = value; }
43 }
44 private Stream _body;
45
46 public string ProtocolVersion
47 {
48 get { return _protocolVersion; }
49 set { _protocolVersion = value; }
50 }
51 private string _protocolVersion;
52
53 public bool Chunked
54 {
55 get { return _chunked; }
56
57 set { _chunked = value; }
58 }
59 private bool _chunked;
60
61 public ConnectionType Connection
62 {
63 get { return _connection; }
64
65 set { _connection = value; }
66 }
67 private ConnectionType _connection;
68
69 public Encoding Encoding
70 {
71 get { return _encoding; }
72
73 set { _encoding = value; }
74 }
75 private Encoding _encoding;
76
77 public int KeepAlive
78 {
79 get { return _keepAlive; }
80
81 set { _keepAlive = value; }
82 }
83 private int _keepAlive;
84
85 public HttpStatusCode Status
86 {
87 get { return _status; }
88
89 set { _status = value; }
90 }
91 private HttpStatusCode _status;
92
93 public string Reason
94 {
95 get { return _reason; }
96
97 set { _reason = value; }
98 }
99 private string _reason;
100
101 public long ContentLength
102 {
103 get { return _contentLength; }
104
105 set { _contentLength = value; }
106 }
107 private long _contentLength;
108
109 public string ContentType
110 {
111 get { return _contentType; }
112
113 set { _contentType = value; }
114 }
115 private string _contentType;
116
117 public bool HeadersSent
118 {
119 get { return _headersSent; }
120 }
121 private bool _headersSent;
122
123 public bool Sent
124 {
125 get { return _sent; }
126 }
127 private bool _sent;
128
129 public ResponseCookies Cookies
130 {
131 get { return _cookies; }
132 }
133 private ResponseCookies _cookies = null;
134
135 public TestHttpResponse()
136 {
137 _headersSent = false;
138 _sent = false;
139 }
140
141 public void AddHeader(string name, string value) {}
142
143 public void Send()
144 {
145 if (!_headersSent) SendHeaders();
146 if (_sent) throw new InvalidOperationException("stuff already sent");
147 _sent = true;
148 }
149
150 public void SendBody(byte[] buffer, int offset, int count)
151 {
152 if (!_headersSent) SendHeaders();
153 _sent = true;
154 }
155
156 public void SendBody(byte[] buffer)
157 {
158 if (!_headersSent) SendHeaders();
159 _sent = true;
160 }
161
162 public void SendHeaders()
163 {
164 if (_headersSent) throw new InvalidOperationException("headers already sent");
165 _headersSent = true;
166 }
167
168 public void Redirect(Uri uri) {}
169 public void Redirect(string url) {}
170 }
171} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/TestInventoryDataPlugin.cs b/OpenSim/Tests/Common/Mock/TestInventoryDataPlugin.cs
new file mode 100644
index 0000000..c97a765
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestInventoryDataPlugin.cs
@@ -0,0 +1,219 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Reflection;
31using log4net;
32using OpenMetaverse;
33using OpenSim.Framework;
34using OpenSim.Data;
35
36namespace OpenSim.Tests.Common
37{
38 /// <summary>
39 /// In memory inventory data plugin for test purposes. Could be another dll when properly filled out and when the
40 /// mono addin plugin system starts co-operating with the unit test system. Currently no locking since unit
41 /// tests are single threaded.
42 /// </summary>
43 public class TestInventoryDataPlugin : IInventoryDataPlugin
44 {
45// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
46
47 /// <value>
48 /// Inventory folders
49 /// </value>
50 private Dictionary<UUID, InventoryFolderBase> m_folders = new Dictionary<UUID, InventoryFolderBase>();
51
52 //// <value>
53 /// Inventory items
54 /// </value>
55 private Dictionary<UUID, InventoryItemBase> m_items = new Dictionary<UUID, InventoryItemBase>();
56
57 /// <value>
58 /// User root folders
59 /// </value>
60 private Dictionary<UUID, InventoryFolderBase> m_rootFolders = new Dictionary<UUID, InventoryFolderBase>();
61
62 public string Version { get { return "0"; } }
63 public string Name { get { return "TestInventoryDataPlugin"; } }
64
65 public void Initialise() {}
66 public void Initialise(string connect) {}
67 public void Dispose() {}
68
69 public List<InventoryFolderBase> getFolderHierarchy(UUID parentID)
70 {
71 List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
72
73 foreach (InventoryFolderBase folder in m_folders.Values)
74 {
75 if (folder.ParentID == parentID)
76 {
77 folders.AddRange(getFolderHierarchy(folder.ID));
78 folders.Add(folder);
79 }
80 }
81
82 return folders;
83 }
84
85 public List<InventoryItemBase> getInventoryInFolder(UUID folderID)
86 {
87// InventoryFolderBase folder = m_folders[folderID];
88
89// m_log.DebugFormat("[MOCK INV DB]: Getting items in folder {0} {1}", folder.Name, folder.ID);
90
91 List<InventoryItemBase> items = new List<InventoryItemBase>();
92
93 foreach (InventoryItemBase item in m_items.Values)
94 {
95 if (item.Folder == folderID)
96 {
97// m_log.DebugFormat("[MOCK INV DB]: getInventoryInFolder() adding item {0}", item.Name);
98 items.Add(item);
99 }
100 }
101
102 return items;
103 }
104
105 public List<InventoryFolderBase> getUserRootFolders(UUID user) { return null; }
106
107 public InventoryFolderBase getUserRootFolder(UUID user)
108 {
109// m_log.DebugFormat("[MOCK INV DB]: Looking for root folder for {0}", user);
110
111 InventoryFolderBase folder = null;
112 m_rootFolders.TryGetValue(user, out folder);
113
114 return folder;
115 }
116
117 public List<InventoryFolderBase> getInventoryFolders(UUID parentID)
118 {
119// InventoryFolderBase parentFolder = m_folders[parentID];
120
121// m_log.DebugFormat("[MOCK INV DB]: Getting folders in folder {0} {1}", parentFolder.Name, parentFolder.ID);
122
123 List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
124
125 foreach (InventoryFolderBase folder in m_folders.Values)
126 {
127 if (folder.ParentID == parentID)
128 {
129// m_log.DebugFormat(
130// "[MOCK INV DB]: Found folder {0} {1} in {2} {3}",
131// folder.Name, folder.ID, parentFolder.Name, parentFolder.ID);
132
133 folders.Add(folder);
134 }
135 }
136
137 return folders;
138 }
139
140 public InventoryFolderBase getInventoryFolder(UUID folderId)
141 {
142 InventoryFolderBase folder = null;
143 m_folders.TryGetValue(folderId, out folder);
144
145 return folder;
146 }
147
148 public InventoryFolderBase queryInventoryFolder(UUID folderID)
149 {
150 return getInventoryFolder(folderID);
151 }
152
153 public void addInventoryFolder(InventoryFolderBase folder)
154 {
155// m_log.DebugFormat(
156// "[MOCK INV DB]: Adding inventory folder {0} {1} type {2}",
157// folder.Name, folder.ID, (AssetType)folder.Type);
158
159 m_folders[folder.ID] = folder;
160
161 if (folder.ParentID == UUID.Zero)
162 {
163// m_log.DebugFormat(
164// "[MOCK INV DB]: Adding root folder {0} {1} for {2}", folder.Name, folder.ID, folder.Owner);
165 m_rootFolders[folder.Owner] = folder;
166 }
167 }
168
169 public void updateInventoryFolder(InventoryFolderBase folder)
170 {
171 m_folders[folder.ID] = folder;
172 }
173
174 public void moveInventoryFolder(InventoryFolderBase folder)
175 {
176 // Simple replace
177 updateInventoryFolder(folder);
178 }
179
180 public void deleteInventoryFolder(UUID folderId)
181 {
182 if (m_folders.ContainsKey(folderId))
183 m_folders.Remove(folderId);
184 }
185
186 public void addInventoryItem(InventoryItemBase item)
187 {
188 InventoryFolderBase folder = m_folders[item.Folder];
189
190// m_log.DebugFormat(
191// "[MOCK INV DB]: Adding inventory item {0} {1} in {2} {3}", item.Name, item.ID, folder.Name, folder.ID);
192
193 m_items[item.ID] = item;
194 }
195
196 public void updateInventoryItem(InventoryItemBase item) { addInventoryItem(item); }
197
198 public void deleteInventoryItem(UUID itemId)
199 {
200 if (m_items.ContainsKey(itemId))
201 m_items.Remove(itemId);
202 }
203
204 public InventoryItemBase getInventoryItem(UUID itemId)
205 {
206 if (m_items.ContainsKey(itemId))
207 return m_items[itemId];
208 else
209 return null;
210 }
211
212 public InventoryItemBase queryInventoryItem(UUID item)
213 {
214 return null;
215 }
216
217 public List<InventoryItemBase> fetchActiveGestures(UUID avatarID) { return null; }
218 }
219}
diff --git a/OpenSim/Tests/Common/Mock/TestLLUDPServer.cs b/OpenSim/Tests/Common/Mock/TestLLUDPServer.cs
new file mode 100644
index 0000000..26887c9
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestLLUDPServer.cs
@@ -0,0 +1,171 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Net;
31using System.Net.Sockets;
32using Nini.Config;
33using OpenMetaverse.Packets;
34using OpenSim.Framework;
35using OpenSim.Region.ClientStack.LindenUDP;
36
37namespace OpenSim.Tests.Common
38{
39 /// <summary>
40 /// This class enables regression testing of the LLUDPServer by allowing us to intercept outgoing data.
41 /// </summary>
42 public class TestLLUDPServer : LLUDPServer
43 {
44 public List<Packet> PacketsSent { get; private set; }
45
46 public TestLLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
47 : base(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource, circuitManager)
48 {
49 PacketsSent = new List<Packet>();
50 }
51
52 public override void SendAckImmediate(IPEndPoint remoteEndpoint, PacketAckPacket ack)
53 {
54 PacketsSent.Add(ack);
55 }
56
57 public override void SendPacket(
58 LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting, UnackedPacketMethod method)
59 {
60 PacketsSent.Add(packet);
61 }
62
63 public void ClientOutgoingPacketHandler(IClientAPI client, bool resendUnacked, bool sendAcks, bool sendPing)
64 {
65 m_resendUnacked = resendUnacked;
66 m_sendAcks = sendAcks;
67 m_sendPing = sendPing;
68
69 ClientOutgoingPacketHandler(client);
70 }
71
72//// /// <summary>
73//// /// The chunks of data to pass to the LLUDPServer when it calls EndReceive
74//// /// </summary>
75//// protected Queue<ChunkSenderTuple> m_chunksToLoad = new Queue<ChunkSenderTuple>();
76//
77//// protected override void BeginReceive()
78//// {
79//// if (m_chunksToLoad.Count > 0 && m_chunksToLoad.Peek().BeginReceiveException)
80//// {
81//// ChunkSenderTuple tuple = m_chunksToLoad.Dequeue();
82//// reusedEpSender = tuple.Sender;
83//// throw new SocketException();
84//// }
85//// }
86//
87//// protected override bool EndReceive(out int numBytes, IAsyncResult result, ref EndPoint epSender)
88//// {
89//// numBytes = 0;
90////
91//// //m_log.Debug("Queue size " + m_chunksToLoad.Count);
92////
93//// if (m_chunksToLoad.Count <= 0)
94//// return false;
95////
96//// ChunkSenderTuple tuple = m_chunksToLoad.Dequeue();
97//// RecvBuffer = tuple.Data;
98//// numBytes = tuple.Data.Length;
99//// epSender = tuple.Sender;
100////
101//// return true;
102//// }
103//
104//// public override void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode)
105//// {
106//// // Don't do anything just yet
107//// }
108//
109// /// <summary>
110// /// Signal that this chunk should throw an exception on Socket.BeginReceive()
111// /// </summary>
112// /// <param name="epSender"></param>
113// public void LoadReceiveWithBeginException(EndPoint epSender)
114// {
115// ChunkSenderTuple tuple = new ChunkSenderTuple(epSender);
116// tuple.BeginReceiveException = true;
117// m_chunksToLoad.Enqueue(tuple);
118// }
119//
120// /// <summary>
121// /// Load some data to be received by the LLUDPServer on the next receive call
122// /// </summary>
123// /// <param name="data"></param>
124// /// <param name="epSender"></param>
125// public void LoadReceive(byte[] data, EndPoint epSender)
126// {
127// m_chunksToLoad.Enqueue(new ChunkSenderTuple(data, epSender));
128// }
129//
130// /// <summary>
131// /// Load a packet to be received by the LLUDPServer on the next receive call
132// /// </summary>
133// /// <param name="packet"></param>
134// public void LoadReceive(Packet packet, EndPoint epSender)
135// {
136// LoadReceive(packet.ToBytes(), epSender);
137// }
138//
139// /// <summary>
140// /// Calls the protected asynchronous result method. This fires out all data chunks currently queued for send
141// /// </summary>
142// /// <param name="result"></param>
143// public void ReceiveData(IAsyncResult result)
144// {
145// // Doesn't work the same way anymore
146//// while (m_chunksToLoad.Count > 0)
147//// OnReceivedData(result);
148// }
149 }
150
151 /// <summary>
152 /// Record the data and sender tuple
153 /// </summary>
154 public class ChunkSenderTuple
155 {
156 public byte[] Data;
157 public EndPoint Sender;
158 public bool BeginReceiveException;
159
160 public ChunkSenderTuple(byte[] data, EndPoint sender)
161 {
162 Data = data;
163 Sender = sender;
164 }
165
166 public ChunkSenderTuple(EndPoint sender)
167 {
168 Sender = sender;
169 }
170 }
171}
diff --git a/OpenSim/Tests/Common/Mock/TestLandChannel.cs b/OpenSim/Tests/Common/Mock/TestLandChannel.cs
new file mode 100644
index 0000000..89ebcd5
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestLandChannel.cs
@@ -0,0 +1,115 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System.Collections.Generic;
29using OpenMetaverse;
30using OpenSim.Framework;
31using OpenSim.Region.Framework.Interfaces;
32using OpenSim.Region.Framework.Scenes;
33using OpenSim.Region.CoreModules.World.Land;
34
35namespace OpenSim.Tests.Common
36{
37 /// <summary>
38 /// Land channel for test purposes
39 /// </summary>
40 public class TestLandChannel : ILandChannel
41 {
42 private Scene m_scene;
43 private List<ILandObject> m_parcels;
44
45 public TestLandChannel(Scene scene)
46 {
47 m_scene = scene;
48 m_parcels = new List<ILandObject>();
49 SetupDefaultParcel();
50 }
51
52 private void SetupDefaultParcel()
53 {
54 ILandObject obj = new LandObject(UUID.Zero, false, m_scene);
55 obj.LandData.Name = "Your Parcel";
56 m_parcels.Add(obj);
57 }
58
59 public List<ILandObject> ParcelsNearPoint(Vector3 position)
60 {
61 return new List<ILandObject>();
62 }
63
64 public List<ILandObject> AllParcels()
65 {
66 return m_parcels;
67 }
68
69 public void Clear(bool setupDefaultParcel)
70 {
71 m_parcels.Clear();
72
73 if (setupDefaultParcel)
74 SetupDefaultParcel();
75 }
76
77 protected ILandObject GetNoLand()
78 {
79 ILandObject obj = new LandObject(UUID.Zero, false, m_scene);
80 obj.LandData.Name = "NO LAND";
81 return obj;
82 }
83
84 public ILandObject GetLandObject(Vector3 position)
85 {
86 return GetLandObject(position.X, position.Y);
87 }
88
89 public ILandObject GetLandObject(int x, int y)
90 {
91 return GetNoLand();
92 }
93
94 public ILandObject GetLandObject(int localID)
95 {
96 return GetNoLand();
97 }
98
99 public ILandObject GetLandObject(float x, float y)
100 {
101 return GetNoLand();
102 }
103
104 public bool IsLandPrimCountTainted() { return false; }
105 public bool IsForcefulBansAllowed() { return false; }
106 public void UpdateLandObject(int localID, LandData data) {}
107 public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) {}
108 public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) {}
109 public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) {}
110 public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) {}
111
112 public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) {}
113 public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) {}
114 }
115} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs b/OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs
new file mode 100644
index 0000000..7b1d2b5
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs
@@ -0,0 +1,179 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.Collections.Specialized;
32using System.IO;
33using System.Net;
34using System.Text;
35using System.Web;
36using OpenSim.Framework.Servers.HttpServer;
37
38namespace OpenSim.Tests.Common
39{
40 public class TestOSHttpRequest : IOSHttpRequest
41 {
42 public string[] AcceptTypes
43 {
44 get
45 {
46 throw new NotImplementedException ();
47 }
48 }
49
50 public Encoding ContentEncoding
51 {
52 get
53 {
54 throw new NotImplementedException ();
55 }
56 }
57
58 public long ContentLength
59 {
60 get
61 {
62 throw new NotImplementedException ();
63 }
64 }
65
66 public long ContentLength64
67 {
68 get
69 {
70 throw new NotImplementedException ();
71 }
72 }
73
74 public string ContentType
75 {
76 get
77 {
78 throw new NotImplementedException ();
79 }
80 }
81
82 public HttpCookieCollection Cookies
83 {
84 get
85 {
86 throw new NotImplementedException ();
87 }
88 }
89
90 public bool HasEntityBody
91 {
92 get
93 {
94 throw new NotImplementedException ();
95 }
96 }
97
98 public NameValueCollection Headers { get; set; }
99
100 public string HttpMethod
101 {
102 get
103 {
104 throw new NotImplementedException ();
105 }
106 }
107
108 public Stream InputStream
109 {
110 get
111 {
112 throw new NotImplementedException ();
113 }
114 }
115
116 public bool IsSecured
117 {
118 get
119 {
120 throw new NotImplementedException ();
121 }
122 }
123
124 public bool KeepAlive
125 {
126 get
127 {
128 throw new NotImplementedException ();
129 }
130 }
131
132 public NameValueCollection QueryString
133 {
134 get
135 {
136 throw new NotImplementedException ();
137 }
138 }
139
140 public Hashtable Query
141 {
142 get
143 {
144 throw new NotImplementedException ();
145 }
146 }
147
148 public string RawUrl
149 {
150 get
151 {
152 throw new NotImplementedException ();
153 }
154 }
155
156 public IPEndPoint RemoteIPEndPoint
157 {
158 get
159 {
160 throw new NotImplementedException ();
161 }
162 }
163
164 public Uri Url { get; set; }
165
166 public string UserAgent
167 {
168 get
169 {
170 throw new NotImplementedException ();
171 }
172 }
173
174 public TestOSHttpRequest()
175 {
176 Headers = new NameValueCollection();
177 }
178 }
179} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs b/OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs
new file mode 100644
index 0000000..2e17f1e
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs
@@ -0,0 +1,133 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.IO;
31using System.Text;
32using System.Web;
33using OpenSim.Framework.Servers.HttpServer;
34
35namespace OpenSim.Tests.Common
36{
37 public class TestOSHttpResponse : IOSHttpResponse
38 {
39 /// <summary>
40 /// Content type property.
41 /// </summary>
42 /// <remarks>
43 /// Setting this property will also set IsContentTypeSet to
44 /// true.
45 /// </remarks>
46 public string ContentType { get; set; }
47
48 /// <summary>
49 /// Boolean property indicating whether the content type
50 /// property actively has been set.
51 /// </summary>
52 /// <remarks>
53 /// IsContentTypeSet will go away together with .NET base.
54 /// </remarks>
55 // public bool IsContentTypeSet
56 // {
57 // get { return _contentTypeSet; }
58 // }
59 // private bool _contentTypeSet;
60
61 /// <summary>
62 /// Length of the body content; 0 if there is no body.
63 /// </summary>
64 public long ContentLength { get; set; }
65
66 /// <summary>
67 /// Alias for ContentLength.
68 /// </summary>
69 public long ContentLength64 { get; set; }
70
71 /// <summary>
72 /// Encoding of the body content.
73 /// </summary>
74 public Encoding ContentEncoding { get; set; }
75
76 public bool KeepAlive { get; set; }
77
78 /// <summary>
79 /// Get or set the keep alive timeout property (default is
80 /// 20). Setting this to 0 also disables KeepAlive. Setting
81 /// this to something else but 0 also enable KeepAlive.
82 /// </summary>
83 public int KeepAliveTimeout { get; set; }
84
85 /// <summary>
86 /// Return the output stream feeding the body.
87 /// </summary>
88 /// <remarks>
89 /// On its way out...
90 /// </remarks>
91 public Stream OutputStream { get; private set; }
92
93 public string ProtocolVersion { get; set; }
94
95 /// <summary>
96 /// Return the output stream feeding the body.
97 /// </summary>
98 public Stream Body { get; private set; }
99
100 /// <summary>
101 /// Set a redirct location.
102 /// </summary>
103 public string RedirectLocation { private get; set; }
104
105 /// <summary>
106 /// Chunk transfers.
107 /// </summary>
108 public bool SendChunked { get; set; }
109
110 /// <summary>
111 /// HTTP status code.
112 /// </summary>
113 public int StatusCode { get; set; }
114
115 /// <summary>
116 /// HTTP status description.
117 /// </summary>
118 public string StatusDescription { get; set; }
119
120 public bool ReuseContext { get; set; }
121
122 /// <summary>
123 /// Add a header field and content to the response.
124 /// </summary>
125 /// <param name="key">string containing the header field
126 /// name</param>
127 /// <param name="value">string containing the header field
128 /// value</param>
129 public void AddHeader(string key, string value) { throw new NotImplementedException(); }
130
131 public void Send() { }
132 }
133} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/Mock/TestScene.cs b/OpenSim/Tests/Common/Mock/TestScene.cs
new file mode 100644
index 0000000..45acf91
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestScene.cs
@@ -0,0 +1,77 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using Nini.Config;
30using OpenSim.Framework;
31using OpenSim.Framework.Communications;
32using OpenSim.Framework.Servers;
33using OpenSim.Region.Framework;
34using OpenSim.Region.Framework.Interfaces;
35using OpenSim.Region.Framework.Scenes;
36using OpenSim.Region.Physics.Manager;
37using OpenSim.Services.Interfaces;
38
39namespace OpenSim.Tests.Common
40{
41 public class TestScene : Scene
42 {
43 public TestScene(
44 RegionInfo regInfo, AgentCircuitManager authen, PhysicsScene physicsScene,
45 SceneCommunicationService sceneGridService, ISimulationDataService simDataService, IEstateDataService estateDataService,
46 IConfigSource config, string simulatorVersion)
47 : base(regInfo, authen, physicsScene, sceneGridService, simDataService, estateDataService,
48 config, simulatorVersion)
49 {
50 }
51
52 ~TestScene()
53 {
54 //Console.WriteLine("TestScene destructor called for {0}", RegionInfo.RegionName);
55 Console.WriteLine("TestScene destructor called");
56 }
57
58 /// <summary>
59 /// Temporarily override session authentication for tests (namely teleport).
60 /// </summary>
61 /// <remarks>
62 /// TODO: This needs to be mocked out properly.
63 /// </remarks>
64 /// <param name="agent"></param>
65 /// <returns></returns>
66 public override bool VerifyUserPresence(AgentCircuitData agent, out string reason)
67 {
68 reason = String.Empty;
69 return true;
70 }
71
72 public AsyncSceneObjectGroupDeleter SceneObjectGroupDeleter
73 {
74 get { return m_asyncSceneObjectDeleter; }
75 }
76 }
77}
diff --git a/OpenSim/Tests/Common/Mock/TestXInventoryDataPlugin.cs b/OpenSim/Tests/Common/Mock/TestXInventoryDataPlugin.cs
new file mode 100644
index 0000000..2b272e6
--- /dev/null
+++ b/OpenSim/Tests/Common/Mock/TestXInventoryDataPlugin.cs
@@ -0,0 +1,152 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Linq;
31using System.Reflection;
32using log4net;
33using OpenMetaverse;
34using OpenSim.Framework;
35using OpenSim.Data;
36using OpenSim.Data.Null;
37
38namespace OpenSim.Tests.Common
39{
40 public class TestXInventoryDataPlugin : NullGenericDataHandler, IXInventoryData
41 {
42 private Dictionary<UUID, XInventoryFolder> m_allFolders = new Dictionary<UUID, XInventoryFolder>();
43 private Dictionary<UUID, XInventoryItem> m_allItems = new Dictionary<UUID, XInventoryItem>();
44
45 public TestXInventoryDataPlugin(string conn, string realm) {}
46
47 public XInventoryItem[] GetItems(string[] fields, string[] vals)
48 {
49// Console.WriteLine(
50// "Requesting items, fields {0}, vals {1}", string.Join(", ", fields), string.Join(", ", vals));
51
52 List<XInventoryItem> origItems = Get<XInventoryItem>(fields, vals, m_allItems.Values.ToList());
53
54 XInventoryItem[] items = origItems.Select(i => i.Clone()).ToArray();
55
56// Console.WriteLine("Found {0} items", items.Length);
57// Array.ForEach(items, i => Console.WriteLine("Found item {0} {1}", i.inventoryName, i.inventoryID));
58
59 return items;
60 }
61
62 public XInventoryFolder[] GetFolders(string[] fields, string[] vals)
63 {
64// Console.WriteLine(
65// "Requesting folders, fields {0}, vals {1}", string.Join(", ", fields), string.Join(", ", vals));
66
67 List<XInventoryFolder> origFolders
68 = Get<XInventoryFolder>(fields, vals, m_allFolders.Values.ToList());
69
70 XInventoryFolder[] folders = origFolders.Select(f => f.Clone()).ToArray();
71
72// Console.WriteLine("Found {0} folders", folders.Length);
73// Array.ForEach(folders, f => Console.WriteLine("Found folder {0} {1}", f.folderName, f.folderID));
74
75 return folders;
76 }
77
78 public bool StoreFolder(XInventoryFolder folder)
79 {
80 m_allFolders[folder.folderID] = folder.Clone();
81
82// Console.WriteLine("Added folder {0} {1}", folder.folderName, folder.folderID);
83
84 return true;
85 }
86
87 public bool StoreItem(XInventoryItem item)
88 {
89 m_allItems[item.inventoryID] = item.Clone();
90
91// Console.WriteLine(
92// "Added item {0} {1}, folder {2}, creator {3}, owner {4}",
93// item.inventoryName, item.inventoryID, item.parentFolderID, item.creatorID, item.avatarID);
94
95 return true;
96 }
97
98 public bool DeleteFolders(string field, string val)
99 {
100 return DeleteFolders(new string[] { field }, new string[] { val });
101 }
102
103 public bool DeleteFolders(string[] fields, string[] vals)
104 {
105 XInventoryFolder[] foldersToDelete = GetFolders(fields, vals);
106 Array.ForEach(foldersToDelete, f => m_allFolders.Remove(f.folderID));
107
108 return true;
109 }
110
111 public bool DeleteItems(string field, string val)
112 {
113 return DeleteItems(new string[] { field }, new string[] { val });
114 }
115
116 public bool DeleteItems(string[] fields, string[] vals)
117 {
118 XInventoryItem[] itemsToDelete = GetItems(fields, vals);
119 Array.ForEach(itemsToDelete, i => m_allItems.Remove(i.inventoryID));
120
121 return true;
122 }
123
124 public bool MoveItem(string id, string newParent) { throw new NotImplementedException(); }
125
126 public bool MoveFolder(string id, string newParent)
127 {
128 // Don't use GetFolders() here - it takes a clone!
129 XInventoryFolder folder = m_allFolders[new UUID(id)];
130
131 if (folder == null)
132 return false;
133
134 folder.parentFolderID = new UUID(newParent);
135
136// XInventoryFolder[] newParentFolders
137// = GetFolders(new string[] { "folderID" }, new string[] { folder.parentFolderID.ToString() });
138
139// Console.WriteLine(
140// "Moved folder {0} {1}, to {2} {3}",
141// folder.folderName, folder.folderID, newParentFolders[0].folderName, folder.parentFolderID);
142
143 // TODO: Really need to implement folder version incrementing, though this should be common code anyway,
144 // not reimplemented in each db plugin.
145
146 return true;
147 }
148
149 public XInventoryItem[] GetActiveGestures(UUID principalID) { throw new NotImplementedException(); }
150 public int GetAssetPermissions(UUID principalID, UUID assetID) { throw new NotImplementedException(); }
151 }
152} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/OpenSimTestCase.cs b/OpenSim/Tests/Common/OpenSimTestCase.cs
new file mode 100644
index 0000000..c1415af
--- /dev/null
+++ b/OpenSim/Tests/Common/OpenSimTestCase.cs
@@ -0,0 +1,55 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using NUnit.Framework;
30using OpenSim.Framework;
31using OpenSim.Framework.Servers;
32
33namespace OpenSim.Tests.Common
34{
35 [TestFixture]
36 public class OpenSimTestCase
37 {
38 [SetUp]
39 public virtual void SetUp()
40 {
41// TestHelpers.InMethod();
42 // Disable logging for each test so that one where logging is enabled doesn't cause all subsequent tests
43 // to have logging on if it failed with an exception.
44 TestHelpers.DisableLogging();
45
46 // This is an unfortunate bit of clean up we have to do because MainServer manages things through static
47 // variables and the VM is not restarted between tests.
48 if (MainServer.Instance != null)
49 {
50 MainServer.RemoveHttpServer(MainServer.Instance.Port);
51// MainServer.Instance = null;
52 }
53 }
54 }
55} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/QuaternionToleranceConstraint.cs b/OpenSim/Tests/Common/QuaternionToleranceConstraint.cs
new file mode 100644
index 0000000..b38c382
--- /dev/null
+++ b/OpenSim/Tests/Common/QuaternionToleranceConstraint.cs
@@ -0,0 +1,82 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using OpenMetaverse;
30using NUnit.Framework;
31using NUnit.Framework.Constraints;
32
33namespace OpenSim.Tests.Common
34{
35 public class QuaternionToleranceConstraint : ANumericalToleranceConstraint
36 {
37 private Quaternion _baseValue;
38 private Quaternion _valueToBeTested;
39
40 public QuaternionToleranceConstraint(Quaternion baseValue, double tolerance) : base(tolerance)
41 {
42 _baseValue = baseValue;
43 }
44
45 /// <summary>
46 /// Test whether the constraint is satisfied by a given value
47 /// </summary>
48 /// <param name="valueToBeTested">The value to be tested</param>
49 /// <returns>
50 /// True for success, false for failure
51 /// </returns>
52 public override bool Matches(object valueToBeTested)
53 {
54 if (valueToBeTested == null)
55 {
56 throw new ArgumentException("Constraint cannot be used upon null values.");
57 }
58 if (valueToBeTested.GetType() != typeof (Quaternion))
59 {
60 throw new ArgumentException("Constraint cannot be used upon non quaternion values.");
61 }
62
63 _valueToBeTested = (Quaternion)valueToBeTested;
64
65 return (IsWithinDoubleConstraint(_valueToBeTested.X, _baseValue.X) &&
66 IsWithinDoubleConstraint(_valueToBeTested.Y, _baseValue.Y) &&
67 IsWithinDoubleConstraint(_valueToBeTested.Z, _baseValue.Z) &&
68 IsWithinDoubleConstraint(_valueToBeTested.W, _baseValue.W));
69 }
70
71 public override void WriteDescriptionTo(MessageWriter writer)
72 {
73 writer.WriteExpectedValue(
74 string.Format("A value {0} within tolerance of plus or minus {1}", _baseValue, _tolerance));
75 }
76
77 public override void WriteActualValueTo(MessageWriter writer)
78 {
79 writer.WriteActualValue(_valueToBeTested);
80 }
81 }
82} \ No newline at end of file
diff --git a/OpenSim/Tests/Common/TestHelpers.cs b/OpenSim/Tests/Common/TestHelpers.cs
new file mode 100644
index 0000000..6bf23f8
--- /dev/null
+++ b/OpenSim/Tests/Common/TestHelpers.cs
@@ -0,0 +1,164 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Diagnostics;
30using System.IO;
31using System.Text;
32using NUnit.Framework;
33using OpenMetaverse;
34
35namespace OpenSim.Tests.Common
36{
37 public class TestHelpers
38 {
39 private static Stream EnableLoggingConfigStream
40 = new MemoryStream(
41 Encoding.UTF8.GetBytes(
42@"<log4net>
43 <!-- A1 is set to be a ConsoleAppender -->
44 <appender name=""A1"" type=""log4net.Appender.ConsoleAppender"">
45
46 <!-- A1 uses PatternLayout -->
47 <layout type=""log4net.Layout.PatternLayout"">
48 <!-- Print the date in ISO 8601 format -->
49 <!-- <conversionPattern value=""%date [%thread] %-5level %logger %ndc - %message%newline"" /> -->
50 <conversionPattern value=""%date %message%newline"" />
51 </layout>
52 </appender>
53
54 <!-- Set root logger level to DEBUG and its only appender to A1 -->
55 <root>
56 <level value=""DEBUG"" />
57 <appender-ref ref=""A1"" />
58 </root>
59</log4net>"));
60
61 private static MemoryStream DisableLoggingConfigStream
62 = new MemoryStream(
63 Encoding.UTF8.GetBytes(
64// "<?xml version=\"1.0\" encoding=\"utf-8\" ?><configuration><log4net><root><level value=\"OFF\"/><appender-ref ref=\"A1\"/></root></log4net></configuration>"));
65 //"<?xml version=\"1.0\" encoding=\"utf-8\" ?><configuration><log4net><root><level value=\"OFF\"/></root></log4net></configuration>")));
66// "<configuration><log4net><root><level value=\"OFF\"/></root></log4net></configuration>"));
67// "<configuration><log4net><root></root></log4net></configuration>")));
68// "<configuration><log4net><root/></log4net></configuration>"));
69 "<log4net><root/></log4net>"));
70
71 public static bool AssertThisDelegateCausesArgumentException(TestDelegate d)
72 {
73 try
74 {
75 d();
76 }
77 catch(ArgumentException)
78 {
79 return true;
80 }
81
82 return false;
83 }
84
85 /// <summary>
86 /// A debugging method that can be used to print out which test method you are in
87 /// </summary>
88 public static void InMethod()
89 {
90 StackTrace stackTrace = new StackTrace();
91 Console.WriteLine();
92 Console.WriteLine("===> In Test Method : {0} <===", stackTrace.GetFrame(1).GetMethod().Name);
93 }
94
95 public static void EnableLogging()
96 {
97 log4net.Config.XmlConfigurator.Configure(EnableLoggingConfigStream);
98 EnableLoggingConfigStream.Position = 0;
99 }
100
101 /// <summary>
102 /// Disable logging whilst running the tests.
103 /// </summary>
104 /// <remarks>
105 /// Remember, if a regression test throws an exception before completing this will not be invoked if it's at
106 /// the end of the test.
107 /// TODO: Always invoke this after every test - probably need to make all test cases inherit from a common
108 /// TestCase class where this can be done.
109 /// </remarks>
110 public static void DisableLogging()
111 {
112 log4net.Config.XmlConfigurator.Configure(DisableLoggingConfigStream);
113 DisableLoggingConfigStream.Position = 0;
114 }
115
116 /// <summary>
117 /// Parse a UUID stem into a full UUID.
118 /// </summary>
119 /// <remarks>
120 /// The fragment will come at the start of the UUID. The rest will be 0s
121 /// </remarks>
122 /// <returns></returns>
123 /// <param name='frag'>
124 /// A UUID fragment that will be parsed into a full UUID. Therefore, it can only contain
125 /// cahracters which are valid in a UUID, except for "-" which is currently only allowed if a full UUID is
126 /// given as the 'fragment'.
127 /// </param>
128 public static UUID ParseStem(string stem)
129 {
130 string rawUuid = stem.PadRight(32, '0');
131
132 return UUID.Parse(rawUuid);
133 }
134
135 /// <summary>
136 /// Parse tail section into full UUID.
137 /// </summary>
138 /// <param name="tail"></param>
139 /// <returns></returns>
140 public static UUID ParseTail(int tail)
141 {
142 return new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", tail));
143 }
144
145 /// <summary>
146 /// Parse a UUID tail section into a full UUID.
147 /// </summary>
148 /// <remarks>
149 /// The fragment will come at the end of the UUID. The rest will be 0s
150 /// </remarks>
151 /// <returns></returns>
152 /// <param name='frag'>
153 /// A UUID fragment that will be parsed into a full UUID. Therefore, it can only contain
154 /// cahracters which are valid in a UUID, except for "-" which is currently only allowed if a full UUID is
155 /// given as the 'fragment'.
156 /// </param>
157 public static UUID ParseTail(string stem)
158 {
159 string rawUuid = stem.PadLeft(32, '0');
160
161 return UUID.Parse(rawUuid);
162 }
163 }
164}
diff --git a/OpenSim/Tests/Common/TestLogging.cs b/OpenSim/Tests/Common/TestLogging.cs
new file mode 100644
index 0000000..4a08344
--- /dev/null
+++ b/OpenSim/Tests/Common/TestLogging.cs
@@ -0,0 +1,46 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.Text;
31using log4net.Appender;
32using log4net.Layout;
33
34namespace OpenSim.Tests.Common
35{
36 public static class TestLogging
37 {
38 public static void LogToConsole()
39 {
40 ConsoleAppender consoleAppender = new ConsoleAppender();
41 consoleAppender.Layout =
42 new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline");
43 log4net.Config.BasicConfigurator.Configure(consoleAppender);
44 }
45 }
46}
diff --git a/OpenSim/Tests/Common/VectorToleranceConstraint.cs b/OpenSim/Tests/Common/VectorToleranceConstraint.cs
new file mode 100644
index 0000000..2fa20ed
--- /dev/null
+++ b/OpenSim/Tests/Common/VectorToleranceConstraint.cs
@@ -0,0 +1,81 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using OpenMetaverse;
30using NUnit.Framework;
31using NUnit.Framework.Constraints;
32
33namespace OpenSim.Tests.Common
34{
35 public class VectorToleranceConstraint : ANumericalToleranceConstraint
36 {
37 private Vector3 _baseValue;
38 private Vector3 _valueToBeTested;
39
40 public VectorToleranceConstraint(Vector3 baseValue, double tolerance) : base(tolerance)
41 {
42 _baseValue = baseValue;
43 }
44
45 ///<summary>
46 ///Test whether the constraint is satisfied by a given value
47 ///</summary>
48 ///<param name="valueToBeTested">The value to be tested</param>
49 ///<returns>
50 ///True for success, false for failure
51 ///</returns>
52 public override bool Matches(object valueToBeTested)
53 {
54 if (valueToBeTested == null)
55 {
56 throw new ArgumentException("Constraint cannot be used upon null values.");
57 }
58 if (valueToBeTested.GetType() != typeof (Vector3))
59 {
60 throw new ArgumentException("Constraint cannot be used upon non vector values.");
61 }
62
63 _valueToBeTested = (Vector3) valueToBeTested;
64
65 return (IsWithinDoubleConstraint(_valueToBeTested.X, _baseValue.X) &&
66 IsWithinDoubleConstraint(_valueToBeTested.Y, _baseValue.Y) &&
67 IsWithinDoubleConstraint(_valueToBeTested.Z, _baseValue.Z));
68 }
69
70 public override void WriteDescriptionTo(MessageWriter writer)
71 {
72 writer.WriteExpectedValue(
73 string.Format("A value {0} within tolerance of plus or minus {1}", _baseValue, _tolerance));
74 }
75
76 public override void WriteActualValueTo(MessageWriter writer)
77 {
78 writer.WriteActualValue(_valueToBeTested);
79 }
80 }
81}