From 134f86e8d5c414409631b25b8c6f0ee45fbd8631 Mon Sep 17 00:00:00 2001 From: David Walter Seikel Date: Thu, 3 Nov 2016 21:44:39 +1000 Subject: Initial update to OpenSim 0.8.2.1 source code. --- .../Common/Helpers/BaseRequestHandlerHelpers.cs | 1 - OpenSim/Tests/Common/Helpers/ClientStackHelpers.cs | 95 +++++++ .../Tests/Common/Helpers/EntityTransferHelpers.cs | 123 ++++++++++ OpenSim/Tests/Common/Helpers/SceneHelpers.cs | 139 +++++++---- .../Tests/Common/Helpers/TaskInventoryHelpers.cs | 121 ++++++--- OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs | 2 +- .../Tests/Common/Helpers/UserInventoryHelpers.cs | 142 +++++++++-- OpenSim/Tests/Common/Mock/BaseAssetRepository.cs | 11 +- OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs | 2 +- .../Common/Mock/MockGroupsServicesConnector.cs | 178 ++++++++++++-- OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs | 29 ++- OpenSim/Tests/Common/Mock/MockScriptEngine.cs | 272 +++++++++++++++++++++ OpenSim/Tests/Common/Mock/TestClient.cs | 179 ++++++++------ .../Tests/Common/Mock/TestEventQueueGetModule.cs | 182 ++++++++++++++ OpenSim/Tests/Common/Mock/TestHttpClientContext.cs | 110 +++++++++ OpenSim/Tests/Common/Mock/TestHttpRequest.cs | 174 +++++++++++++ OpenSim/Tests/Common/Mock/TestHttpResponse.cs | 171 +++++++++++++ .../Tests/Common/Mock/TestInventoryDataPlugin.cs | 4 +- OpenSim/Tests/Common/Mock/TestLLUDPServer.cs | 171 +++++++++++++ OpenSim/Tests/Common/Mock/TestLandChannel.cs | 7 +- OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs | 2 +- OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs | 2 +- OpenSim/Tests/Common/Mock/TestScene.cs | 15 +- .../Tests/Common/Mock/TestXInventoryDataPlugin.cs | 51 +++- OpenSim/Tests/Common/OpenSimTestCase.cs | 15 +- OpenSim/Tests/Common/TestHelpers.cs | 38 +++ 26 files changed, 2011 insertions(+), 225 deletions(-) create mode 100644 OpenSim/Tests/Common/Helpers/ClientStackHelpers.cs create mode 100644 OpenSim/Tests/Common/Helpers/EntityTransferHelpers.cs create mode 100644 OpenSim/Tests/Common/Mock/MockScriptEngine.cs create mode 100644 OpenSim/Tests/Common/Mock/TestEventQueueGetModule.cs create mode 100644 OpenSim/Tests/Common/Mock/TestHttpClientContext.cs create mode 100644 OpenSim/Tests/Common/Mock/TestHttpRequest.cs create mode 100644 OpenSim/Tests/Common/Mock/TestHttpResponse.cs create mode 100644 OpenSim/Tests/Common/Mock/TestLLUDPServer.cs (limited to 'OpenSim/Tests/Common') diff --git a/OpenSim/Tests/Common/Helpers/BaseRequestHandlerHelpers.cs b/OpenSim/Tests/Common/Helpers/BaseRequestHandlerHelpers.cs index 49c99c5..82ecf9a 100644 --- a/OpenSim/Tests/Common/Helpers/BaseRequestHandlerHelpers.cs +++ b/OpenSim/Tests/Common/Helpers/BaseRequestHandlerHelpers.cs @@ -32,7 +32,6 @@ using NUnit.Framework; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; -using OpenSim.Tests.Common.Mock; namespace OpenSim.Tests.Common { 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 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Net; +using Nini.Config; +using OpenMetaverse; +using OpenMetaverse.Packets; +using OpenSim.Framework; +using OpenSim.Region.ClientStack.LindenUDP; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Tests.Common +{ + /// + /// This class adds full UDP client classes and associated scene presence to scene. + /// + /// + /// This is used for testing client stack code. For testing other code, use SceneHelper methods instead since + /// they operate without the burden of setting up UDP structures which should be unnecessary for testing scene + /// code. + /// + public static class ClientStackHelpers + { + public static ScenePresence AddChildClient( + Scene scene, LLUDPServer udpServer, UUID agentId, UUID sessionId, uint circuitCode) + { + IPEndPoint testEp = new IPEndPoint(IPAddress.Loopback, 999); + + UseCircuitCodePacket uccp = new UseCircuitCodePacket(); + + UseCircuitCodePacket.CircuitCodeBlock uccpCcBlock + = new UseCircuitCodePacket.CircuitCodeBlock(); + uccpCcBlock.Code = circuitCode; + uccpCcBlock.ID = agentId; + uccpCcBlock.SessionID = sessionId; + uccp.CircuitCode = uccpCcBlock; + + byte[] uccpBytes = uccp.ToBytes(); + UDPPacketBuffer upb = new UDPPacketBuffer(testEp, uccpBytes.Length); + upb.DataLength = uccpBytes.Length; // God knows why this isn't set by the constructor. + Buffer.BlockCopy(uccpBytes, 0, upb.Data, 0, uccpBytes.Length); + + AgentCircuitData acd = new AgentCircuitData(); + acd.AgentID = agentId; + acd.SessionID = sessionId; + + scene.AuthenticateHandler.AddNewCircuit(circuitCode, acd); + + udpServer.PacketReceived(upb); + + return scene.GetScenePresence(agentId); + } + + public static TestLLUDPServer AddUdpServer(Scene scene) + { + return AddUdpServer(scene, new IniConfigSource()); + } + + public static TestLLUDPServer AddUdpServer(Scene scene, IniConfigSource configSource) + { + uint port = 0; + AgentCircuitManager acm = scene.AuthenticateHandler; + + TestLLUDPServer udpServer = new TestLLUDPServer(IPAddress.Any, ref port, 0, false, configSource, acm); + udpServer.AddScene(scene); + + return udpServer; + } + } +} \ 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..b215f1e --- /dev/null +++ b/OpenSim/Tests/Common/Helpers/EntityTransferHelpers.cs @@ -0,0 +1,123 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Reflection; +using System.Text; +using System.Threading; +using log4net; +using Nini.Config; +using NUnit.Framework; +using OpenMetaverse; +using OpenSim.Framework; + +using OpenSim.Framework.Servers; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.CoreModules.Framework; +using OpenSim.Tests.Common; + +namespace OpenSim.Tests.Common +{ + public static class EntityTransferHelpers + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + /// + /// Set up correct handling of the InformClientOfNeighbour call from the source region that triggers the + /// viewer to setup a connection with the destination region. + /// + /// + /// + /// A list that will be populated with any TestClients set up in response to + /// being informed about a destination region. + /// + public static void SetupInformClientOfNeighbourTriggersNeighbourClientCreate( + TestClient tc, List neighbourTcs) + { + // XXX: Confusingly, this is also used for non-neighbour notification (as in teleports that do not use the + // event queue). + + tc.OnTestClientInformClientOfNeighbour += (neighbourHandle, neighbourExternalEndPoint) => + { + uint x, y; + Util.RegionHandleToRegionLoc(neighbourHandle, out x, out y); + + m_log.DebugFormat( + "[TEST CLIENT]: Processing inform client of neighbour located at {0},{1} at {2}", + x, y, neighbourExternalEndPoint); + + AgentCircuitData newAgent = tc.RequestClientInfo(); + + Scene neighbourScene; + SceneManager.Instance.TryGetScene(x, y, out neighbourScene); + + TestClient neighbourTc = new TestClient(newAgent, neighbourScene); + neighbourTcs.Add(neighbourTc); + neighbourScene.AddNewAgent(neighbourTc, PresenceType.User); + }; + } + + /// + /// Set up correct handling of the InformClientOfNeighbour call from the source region that triggers the + /// viewer to setup a connection with the destination region. + /// + /// + /// + /// A list that will be populated with any TestClients set up in response to + /// being informed about a destination region. + /// + public static void SetupSendRegionTeleportTriggersDestinationClientCreateAndCompleteMovement( + TestClient client, List destinationClients) + { + client.OnTestClientSendRegionTeleport + += (regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL) => + { + uint x, y; + Util.RegionHandleToRegionLoc(regionHandle, out x, out y); + + m_log.DebugFormat( + "[TEST CLIENT]: Processing send region teleport for destination at {0},{1} at {2}", + x, y, regionExternalEndPoint); + + AgentCircuitData newAgent = client.RequestClientInfo(); + + Scene destinationScene; + SceneManager.Instance.TryGetScene(x, y, out destinationScene); + + TestClient destinationClient = new TestClient(newAgent, destinationScene); + destinationClients.Add(destinationClient); + destinationScene.AddNewAgent(destinationClient, PresenceType.User); + + ThreadPool.UnsafeQueueUserWorkItem(o => destinationClient.CompleteMovement(), null); + }; + } + } +} \ No newline at end of file diff --git a/OpenSim/Tests/Common/Helpers/SceneHelpers.cs b/OpenSim/Tests/Common/Helpers/SceneHelpers.cs index ea3e348..df8b14c 100644 --- a/OpenSim/Tests/Common/Helpers/SceneHelpers.cs +++ b/OpenSim/Tests/Common/Helpers/SceneHelpers.cs @@ -30,12 +30,13 @@ using System.Net; using System.Collections.Generic; using Nini.Config; using OpenMetaverse; +using OpenSim.Data.Null; using OpenSim.Framework; -using OpenSim.Framework.Communications; + using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; -using OpenSim.Region.Physics.Manager; +using OpenSim.Region.PhysicsModules.SharedBase; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; @@ -47,8 +48,8 @@ using OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid; using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence; +using OpenSim.Region.PhysicsModule.BasicPhysics; using OpenSim.Services.Interfaces; -using OpenSim.Tests.Common.Mock; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Tests.Common @@ -63,9 +64,9 @@ namespace OpenSim.Tests.Common /// public SceneManager SceneManager { get; private set; } + public ISimulationDataService SimDataService { get; private set; } + private AgentCircuitManager m_acm = new AgentCircuitManager(); - private ISimulationDataService m_simDataService - = OpenSim.Server.Base.ServerUtils.LoadPlugin("OpenSim.Tests.Common.dll", null); private IEstateDataService m_estateDataService = null; private LocalAssetServicesConnector m_assetService; @@ -77,6 +78,8 @@ namespace OpenSim.Tests.Common private CoreAssetCache m_cache; + private PhysicsScene m_physicsScene; + public SceneHelpers() : this(null) {} public SceneHelpers(CoreAssetCache cache) @@ -96,6 +99,11 @@ namespace OpenSim.Tests.Common m_presenceService.PostInitialise(); m_cache = cache; + + m_physicsScene = StartPhysicsScene(); + + SimDataService + = OpenSim.Server.Base.ServerUtils.LoadPlugin("OpenSim.Tests.Common.dll", null); } /// @@ -115,6 +123,11 @@ namespace OpenSim.Tests.Common return SetupScene(name, id, x, y, new IniConfigSource()); } + public TestScene SetupScene(string name, UUID id, uint x, uint y, IConfigSource configSource) + { + return SetupScene(name, id, x, y, Constants.RegionSize, Constants.RegionSize, configSource); + } + /// /// Set up a scene. /// @@ -122,10 +135,12 @@ namespace OpenSim.Tests.Common /// ID of the region /// X co-ordinate of the region /// Y co-ordinate of the region + /// X size of scene + /// Y size of scene /// /// public TestScene SetupScene( - string name, UUID id, uint x, uint y, IConfigSource configSource) + string name, UUID id, uint x, uint y, uint sizeX, uint sizeY, IConfigSource configSource) { Console.WriteLine("Setting up test scene {0}", name); @@ -135,16 +150,20 @@ namespace OpenSim.Tests.Common RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1"); regInfo.RegionName = name; regInfo.RegionID = id; - - SceneCommunicationService scs = new SceneCommunicationService(); + regInfo.RegionSizeX = sizeX; + regInfo.RegionSizeY = sizeY; TestScene testScene = new TestScene( - regInfo, m_acm, scs, m_simDataService, m_estateDataService, false, configSource, null); + regInfo, m_acm, SimDataService, m_estateDataService, configSource, null); INonSharedRegionModule godsModule = new GodsModule(); godsModule.Initialise(new IniConfigSource()); godsModule.AddRegion(testScene); + // Add scene to physics + ((INonSharedRegionModule)m_physicsScene).AddRegion(testScene); + ((INonSharedRegionModule)m_physicsScene).RegionLoaded(testScene); + // Add scene to services m_assetService.AddRegion(testScene); @@ -182,12 +201,7 @@ namespace OpenSim.Tests.Common testScene.SetModuleInterfaces(); testScene.LandChannel = new TestLandChannel(testScene); - testScene.LoadWorldMap(); - - PhysicsPluginManager physicsPluginManager = new PhysicsPluginManager(); - physicsPluginManager.LoadPluginsFromAssembly("Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll"); - testScene.PhysicsScene - = physicsPluginManager.GetPhysicsScene("basicphysics", "ZeroMesher", new IniConfigSource(), "test"); + testScene.LoadWorldMap(); testScene.RegionInfo.EstateSettings = new EstateSettings(); testScene.LoginsEnabled = true; @@ -297,6 +311,11 @@ namespace OpenSim.Tests.Common /// private static LocalPresenceServicesConnector StartPresenceService() { + // Unfortunately, some services share data via statics, so we need to null every time to stop interference + // between tests. + // This is a massive non-obvious pita. + NullPresenceData.Instance = null; + IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("PresenceService"); @@ -311,6 +330,19 @@ namespace OpenSim.Tests.Common return presenceService; } + private static PhysicsScene StartPhysicsScene() + { + IConfigSource config = new IniConfigSource(); + config.AddConfig("Startup"); + config.Configs["Startup"].Set("physics", "basicphysics"); + + PhysicsScene pScene = new BasicScene(); + INonSharedRegionModule mod = pScene as INonSharedRegionModule; + mod.Initialise(config); + + return pScene; + } + /// /// Setup modules for a scene using their default settings. /// @@ -447,9 +479,6 @@ namespace OpenSim.Tests.Common /// Add a root agent where the details of the agent connection (apart from the id) are unimportant for the test /// /// - /// This can be used for tests where there is only one region or where there are multiple non-neighbour regions - /// and teleport doesn't take place. - /// /// XXX: Use the version of this method that takes the UserAccount structure wherever possible - this will /// make the agent circuit data (e.g. first, lastname) consistent with the user account data. /// @@ -462,22 +491,6 @@ namespace OpenSim.Tests.Common } /// - /// Add a root agent where the details of the agent connection (apart from the id) are unimportant for the test - /// - /// - /// XXX: Use the version of this method that takes the UserAccount structure wherever possible - this will - /// make the agent circuit data (e.g. first, lastname) consistent with the user account data. - /// - /// - /// - /// - /// - public static ScenePresence AddScenePresence(Scene scene, UUID agentId, SceneManager sceneManager) - { - return AddScenePresence(scene, GenerateAgentData(agentId), sceneManager); - } - - /// /// Add a root agent. /// /// @@ -508,7 +521,7 @@ namespace OpenSim.Tests.Common /// public static ScenePresence AddScenePresence(Scene scene, AgentCircuitData agentData) { - return AddScenePresence(scene, agentData, null); + return AddScenePresence(scene, new TestClient(agentData, scene), agentData); } /// @@ -528,9 +541,9 @@ namespace OpenSim.Tests.Common /// /// /// - /// /// - public static ScenePresence AddScenePresence(Scene scene, AgentCircuitData agentData, SceneManager sceneManager) + public static ScenePresence AddScenePresence( + Scene scene, IClientAPI client, AgentCircuitData agentData) { // We emulate the proper login sequence here by doing things in four stages @@ -541,7 +554,7 @@ namespace OpenSim.Tests.Common lpsc.m_PresenceService.LoginAgent(agentData.AgentID.ToString(), agentData.SessionID, agentData.SecureSessionID); // Stages 1 & 2 - ScenePresence sp = IntroduceClientToScene(scene, sceneManager, agentData, TeleportFlags.ViaLogin); + ScenePresence sp = IntroduceClientToScene(scene, client, agentData, TeleportFlags.ViaLogin); // Stage 3: Complete the entrance into the region. This converts the child agent into a root agent. sp.CompleteMovement(sp.ControllingClient, true); @@ -553,37 +566,37 @@ namespace OpenSim.Tests.Common /// Introduce an agent into the scene by adding a new client. /// /// The scene presence added - /// - /// Scene manager. Can be null if there is only one region in the test or multiple regions that are not - /// neighbours and where no teleporting takes place. - /// /// - /// /// /// private static ScenePresence IntroduceClientToScene( - Scene scene, SceneManager sceneManager, AgentCircuitData agentData, TeleportFlags tf) + Scene scene, IClientAPI client, AgentCircuitData agentData, TeleportFlags tf) { string reason; // Stage 1: tell the scene to expect a new user connection - if (!scene.NewUserConnection(agentData, (uint)tf, out reason)) + if (!scene.NewUserConnection(agentData, (uint)tf, null, out reason)) Console.WriteLine("NewUserConnection failed: " + reason); // Stage 2: add the new client as a child agent to the scene - TestClient client = new TestClient(agentData, scene, sceneManager); - scene.AddNewClient(client, PresenceType.User); + scene.AddNewAgent(client, PresenceType.User); - return scene.GetScenePresence(agentData.AgentID); + return scene.GetScenePresence(client.AgentId); } public static ScenePresence AddChildScenePresence(Scene scene, UUID agentId) { - AgentCircuitData acd = GenerateAgentData(agentId); + return AddChildScenePresence(scene, GenerateAgentData(agentId)); + } + + public static ScenePresence AddChildScenePresence(Scene scene, AgentCircuitData acd) + { acd.child = true; // XXX: ViaLogin may not be correct for child agents - return IntroduceClientToScene(scene, null, acd, TeleportFlags.ViaLogin); + TestClient client = new TestClient(acd, scene); + return IntroduceClientToScene(scene, client, acd, TeleportFlags.ViaLogin); } /// @@ -610,6 +623,32 @@ namespace OpenSim.Tests.Common //part.UpdatePrimFlags(false, false, true); //part.ObjectFlags |= (uint)PrimFlags.Phantom; + scene.AddNewSceneObject(so, true); + + return so; + } + + /// + /// Add a test object + /// + /// + /// + /// The number of parts that should be in the scene object + /// + /// + /// + /// The prefix to be given to part names. This will be suffixed with "Part" + /// (e.g. mynamePart1 for the root part) + /// + /// + /// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}" + /// will be given to the root part, and incremented for each part thereafter. + /// + /// + public static SceneObjectGroup AddSceneObject(Scene scene, int parts, UUID ownerId, string partNamePrefix, int uuidTail) + { + SceneObjectGroup so = CreateSceneObject(parts, ownerId, partNamePrefix, uuidTail); + scene.AddNewSceneObject(so, false); return so; diff --git a/OpenSim/Tests/Common/Helpers/TaskInventoryHelpers.cs b/OpenSim/Tests/Common/Helpers/TaskInventoryHelpers.cs index 0a2b30a..3a3b33a 100644 --- a/OpenSim/Tests/Common/Helpers/TaskInventoryHelpers.cs +++ b/OpenSim/Tests/Common/Helpers/TaskInventoryHelpers.cs @@ -43,21 +43,40 @@ namespace OpenSim.Tests.Common /// /// Add a notecard item to the given part. /// - /// + /// + /// + /// + /// UUID or UUID stem + /// UUID or UUID stem + /// The tex to put in the notecard. + /// The item that was added + public static TaskInventoryItem AddNotecard( + IAssetService assetService, SceneObjectPart part, string itemName, string itemIDStem, string assetIDStem, string text) + { + return AddNotecard( + assetService, part, itemName, TestHelpers.ParseStem(itemIDStem), TestHelpers.ParseStem(assetIDStem), text); + } + + /// + /// Add a notecard item to the given part. + /// + /// /// /// /// /// + /// The tex to put in the notecard. /// The item that was added - public static TaskInventoryItem AddNotecard(Scene scene, SceneObjectPart part, string itemName, UUID itemID, UUID assetID) + public static TaskInventoryItem AddNotecard( + IAssetService assetService, SceneObjectPart part, string itemName, UUID itemID, UUID assetID, string text) { AssetNotecard nc = new AssetNotecard(); - nc.BodyText = "Hello World!"; + nc.BodyText = text; nc.Encode(); AssetBase ncAsset = AssetHelpers.CreateAsset(assetID, AssetType.Notecard, nc.AssetData, UUID.Zero); - scene.AssetService.Store(ncAsset); + assetService.Store(ncAsset); TaskInventoryItem ncItem = new TaskInventoryItem @@ -75,44 +94,62 @@ namespace OpenSim.Tests.Common /// TODO: Accept input for item and asset IDs to avoid mysterious script failures that try to use any of these /// functions more than once in a test. /// - /// + /// /// /// The item that was added - public static TaskInventoryItem AddScript(Scene scene, SceneObjectPart part) + public static TaskInventoryItem AddScript(IAssetService assetService, SceneObjectPart part) { - return AddScript(scene, part, "scriptItem", "default { state_entry() { llSay(0, \"Hello World\"); } }"); + return AddScript(assetService, part, "scriptItem", "default { state_entry() { llSay(0, \"Hello World\"); } }"); } /// /// Add a simple script to the given part. /// /// - /// TODO: Accept input for item and asset IDs to avoid mysterious script failures that try to use any of these - /// functions more than once in a test. + /// TODO: Accept input for item and asset IDs so that we have completely replicatable regression tests rather + /// than a random component. + /// + /// + /// + /// Name of the script to add + /// LSL script source + /// The item that was added + public static TaskInventoryItem AddScript( + IAssetService assetService, SceneObjectPart part, string scriptName, string scriptSource) + { + return AddScript(assetService, part, UUID.Random(), UUID.Random(), scriptName, scriptSource); + } + + /// + /// Add a simple script to the given part. + /// + /// + /// TODO: Accept input for item and asset IDs so that we have completely replicatable regression tests rather + /// than a random component. /// - /// + /// /// + /// Item UUID for the script + /// Asset UUID for the script /// Name of the script to add /// LSL script source /// The item that was added public static TaskInventoryItem AddScript( - Scene scene, SceneObjectPart part, string scriptName, string scriptSource) + IAssetService assetService, SceneObjectPart part, UUID itemId, UUID assetId, string scriptName, string scriptSource) { AssetScriptText ast = new AssetScriptText(); ast.Source = scriptSource; ast.Encode(); - UUID assetUuid = new UUID("00000000-0000-0000-1000-000000000000"); - UUID itemUuid = new UUID("00000000-0000-0000-1100-000000000000"); AssetBase asset - = AssetHelpers.CreateAsset(assetUuid, AssetType.LSLText, ast.AssetData, UUID.Zero); - scene.AssetService.Store(asset); + = AssetHelpers.CreateAsset(assetId, AssetType.LSLText, ast.AssetData, UUID.Zero); + assetService.Store(asset); TaskInventoryItem item = new TaskInventoryItem - { Name = scriptName, AssetID = assetUuid, ItemID = itemUuid, - Type = (int)AssetType.LSLText, InvType = (int)InventoryType.LSL }; + { Name = scriptName, AssetID = assetId, ItemID = itemId, + Type = (int)AssetType.LSLText, InvType = (int)InventoryType.LSL }; part.Inventory.AddInventoryItem(item, true); - + return item; } @@ -124,28 +161,50 @@ namespace OpenSim.Tests.Common /// functions more than once in a test. /// /// - /// + /// /// /// - /// - /// + /// + /// + /// public static TaskInventoryItem AddSceneObject( - Scene scene, SceneObjectPart sop, string itemName, UUID id, UUID userId) + IAssetService assetService, SceneObjectPart sop, string itemName, UUID itemId, SceneObjectGroup soToAdd, UUID soAssetId) { - SceneObjectGroup taskSceneObject = SceneHelpers.CreateSceneObject(1, UUID.Zero); - AssetBase taskSceneObjectAsset = AssetHelpers.CreateAsset(0x10, taskSceneObject); - scene.AssetService.Store(taskSceneObjectAsset); + AssetBase taskSceneObjectAsset = AssetHelpers.CreateAsset(soAssetId, soToAdd); + assetService.Store(taskSceneObjectAsset); TaskInventoryItem taskSceneObjectItem = new TaskInventoryItem - { Name = itemName, - AssetID = taskSceneObjectAsset.FullID, - ItemID = id, - OwnerID = userId, - Type = (int)AssetType.Object, - InvType = (int)InventoryType.Object }; + { Name = itemName, + AssetID = taskSceneObjectAsset.FullID, + ItemID = itemId, + OwnerID = soToAdd.OwnerID, + Type = (int)AssetType.Object, + InvType = (int)InventoryType.Object }; sop.Inventory.AddInventoryItem(taskSceneObjectItem, true); return taskSceneObjectItem; } + + /// + /// Add a scene object item to the given part. + /// + /// + /// TODO: Accept input for item and asset IDs to avoid mysterious script failures that try to use any of these + /// functions more than once in a test. + /// + /// + /// + /// + /// + /// + /// + public static TaskInventoryItem AddSceneObject( + IAssetService assetService, SceneObjectPart sop, string itemName, UUID itemId, UUID userId) + { + SceneObjectGroup taskSceneObject = SceneHelpers.CreateSceneObject(1, userId); + + return TaskInventoryHelpers.AddSceneObject( + assetService, sop, itemName, itemId, taskSceneObject, TestHelpers.ParseTail(0x10)); + } } } \ No newline at end of file diff --git a/OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs b/OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs index 2fbebc4..c62b58e 100644 --- a/OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs +++ b/OpenSim/Tests/Common/Helpers/UserAccountHelpers.cs @@ -27,7 +27,7 @@ using System.Collections.Generic; using OpenMetaverse; -using OpenSim.Framework.Communications; + using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; diff --git a/OpenSim/Tests/Common/Helpers/UserInventoryHelpers.cs b/OpenSim/Tests/Common/Helpers/UserInventoryHelpers.cs index 87d9410..5a36332 100644 --- a/OpenSim/Tests/Common/Helpers/UserInventoryHelpers.cs +++ b/OpenSim/Tests/Common/Helpers/UserInventoryHelpers.cs @@ -45,6 +45,9 @@ namespace OpenSim.Tests.Common /// /// Add an existing scene object as an item in the user's inventory. /// + /// + /// Will be added to the system Objects folder. + /// /// /// /// @@ -63,7 +66,29 @@ namespace OpenSim.Tests.Common } /// - /// Creates a notecard in the objects folder and specify an item id. + /// Add an existing scene object as an item in the user's inventory at the given path. + /// + /// + /// + /// + /// + /// The inventory item created. + public static InventoryItemBase AddInventoryItem( + Scene scene, SceneObjectGroup so, int inventoryIdTail, int assetIdTail, string path) + { + return AddInventoryItem( + scene, + so.Name, + TestHelpers.ParseTail(inventoryIdTail), + InventoryType.Object, + AssetHelpers.CreateAsset(TestHelpers.ParseTail(assetIdTail), so), + so.OwnerID, + path); + } + + /// + /// Adds the given item to the existing system folder for its type (e.g. an object will go in the "Objects" + /// folder). /// /// /// @@ -75,6 +100,25 @@ namespace OpenSim.Tests.Common private static InventoryItemBase AddInventoryItem( Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId) { + return AddInventoryItem( + scene, itemName, itemId, itemType, asset, userId, + scene.InventoryService.GetFolderForType(userId, (FolderType)asset.Type).Name); + } + + /// + /// Adds the given item to an inventory folder + /// + /// + /// + /// + /// + /// The serialized asset for this item + /// + /// Existing inventory path at which to add. + /// + private static InventoryItemBase AddInventoryItem( + Scene scene, string itemName, UUID itemId, InventoryType itemType, AssetBase asset, UUID userId, string path) + { scene.AssetService.Store(asset); InventoryItemBase item = new InventoryItemBase(); @@ -85,7 +129,7 @@ namespace OpenSim.Tests.Common item.AssetType = asset.Type; item.InvType = (int)itemType; - InventoryFolderBase folder = scene.InventoryService.GetFolderForType(userId, (AssetType)asset.Type); + InventoryFolderBase folder = InventoryArchiveUtils.FindFoldersByPath(scene.InventoryService, userId, path)[0]; item.Folder = folder.ID; scene.AddInventoryItem(item); @@ -156,58 +200,116 @@ namespace OpenSim.Tests.Common /// /// Create inventory folders starting from the user's root folder. /// - /// - /// Ignores any existing folders with the same name - /// /// /// /// /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER /// + /// + /// If true, then folders in the path which already the same name are + /// used. This applies to the terminal folder as well. + /// If false, then all folders in the path are created, even if there is already a folder at a particular + /// level with the same name. + /// /// /// The folder created. If the path contains multiple folders then the last one created is returned. /// Will return null if the root folder could not be found. /// public static InventoryFolderBase CreateInventoryFolder( - IInventoryService inventoryService, UUID userId, string path) + IInventoryService inventoryService, UUID userId, string path, bool useExistingFolders) + { + return CreateInventoryFolder(inventoryService, userId, UUID.Random(), path, useExistingFolders); + } + + /// + /// Create inventory folders starting from the user's root folder. + /// + /// + /// + /// + /// + /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER + /// + /// + /// If true, then folders in the path which already the same name are + /// used. This applies to the terminal folder as well. + /// If false, then all folders in the path are created, even if there is already a folder at a particular + /// level with the same name. + /// + /// + /// The folder created. If the path contains multiple folders then the last one created is returned. + /// Will return null if the root folder could not be found. + /// + public static InventoryFolderBase CreateInventoryFolder( + IInventoryService inventoryService, UUID userId, UUID folderId, string path, bool useExistingFolders) { InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); if (null == rootFolder) return null; - return CreateInventoryFolder(inventoryService, rootFolder, path); + return CreateInventoryFolder(inventoryService, folderId, rootFolder, path, useExistingFolders); } /// /// Create inventory folders starting from a given parent folder /// - /// - /// Ignores any existing folders with the same name - /// + /// + /// If any stem of the path names folders that already exist then these are not recreated. This includes the + /// final folder. + /// TODO: May need to make it an option to create duplicate folders. + /// /// + /// ID of the folder to create /// /// - /// The folders to create. Multiple folders can be specified on a path delimited by the PATH_DELIMITER + /// The folder to create. + /// + /// + /// If true, then folders in the path which already the same name are + /// used. This applies to the terminal folder as well. + /// If false, then all folders in the path are created, even if there is already a folder at a particular + /// level with the same name. /// /// /// The folder created. If the path contains multiple folders then the last one created is returned. /// public static InventoryFolderBase CreateInventoryFolder( - IInventoryService inventoryService, InventoryFolderBase parentFolder, string path) + IInventoryService inventoryService, UUID folderId, InventoryFolderBase parentFolder, string path, bool useExistingFolders) { string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None); - InventoryFolderBase newFolder - = new InventoryFolderBase( - UUID.Random(), components[0], parentFolder.Owner, (short)AssetType.Unknown, parentFolder.ID, 0); - - inventoryService.AddFolder(newFolder); + InventoryFolderBase folder = null; + + if (useExistingFolders) + folder = InventoryArchiveUtils.FindFolderByPath(inventoryService, parentFolder, components[0]); + + if (folder == null) + { +// Console.WriteLine("Creating folder {0} at {1}", components[0], parentFolder.Name); + + UUID folderIdForCreate; + + if (components.Length > 1) + folderIdForCreate = UUID.Random(); + else + folderIdForCreate = folderId; + + folder + = new InventoryFolderBase( + folderIdForCreate, components[0], parentFolder.Owner, (short)AssetType.Unknown, parentFolder.ID, 0); + + inventoryService.AddFolder(folder); + } +// else +// { +// Console.WriteLine("Found existing folder {0}", folder.Name); +// } if (components.Length > 1) - return CreateInventoryFolder(inventoryService, newFolder, components[1]); + return CreateInventoryFolder(inventoryService, folderId, folder, components[1], useExistingFolders); else - return newFolder; + return folder; } /// @@ -237,7 +339,7 @@ namespace OpenSim.Tests.Common /// An empty list if no matching folders were found public static List GetInventoryFolders(IInventoryService inventoryService, UUID userId, string path) { - return InventoryArchiveUtils.FindFolderByPath(inventoryService, userId, path); + return InventoryArchiveUtils.FindFoldersByPath(inventoryService, userId, path); } /// diff --git a/OpenSim/Tests/Common/Mock/BaseAssetRepository.cs b/OpenSim/Tests/Common/Mock/BaseAssetRepository.cs index cfefd38..cb4fb80 100644 --- a/OpenSim/Tests/Common/Mock/BaseAssetRepository.cs +++ b/OpenSim/Tests/Common/Mock/BaseAssetRepository.cs @@ -25,11 +25,12 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +using System; using System.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { public class BaseAssetRepository { @@ -37,7 +38,7 @@ namespace OpenSim.Tests.Common.Mock public AssetBase FetchAsset(UUID uuid) { - if (ExistsAsset(uuid)) + if (AssetsExist(new[] { uuid })[0]) return Assets[uuid]; else return null; @@ -53,9 +54,9 @@ namespace OpenSim.Tests.Common.Mock CreateAsset(asset); } - public bool ExistsAsset(UUID uuid) - { - return Assets.ContainsKey(uuid); + public bool[] AssetsExist(UUID[] uuids) + { + return Array.ConvertAll(uuids, id => Assets.ContainsKey(id)); } } } \ No newline at end of file diff --git a/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs b/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs index 4a15cf2..dddf75d 100644 --- a/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs +++ b/OpenSim/Tests/Common/Mock/MockAssetDataPlugin.cs @@ -31,7 +31,7 @@ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { /// /// In memory asset data plugin for test purposes. Could be another dll when properly filled out and when the diff --git a/OpenSim/Tests/Common/Mock/MockGroupsServicesConnector.cs b/OpenSim/Tests/Common/Mock/MockGroupsServicesConnector.cs index 3035cea..7f530d0 100644 --- a/OpenSim/Tests/Common/Mock/MockGroupsServicesConnector.cs +++ b/OpenSim/Tests/Common/Mock/MockGroupsServicesConnector.cs @@ -40,7 +40,7 @@ using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class MockGroupsServicesConnector : ISharedRegionModule, IGroupsServicesConnector @@ -138,33 +138,28 @@ namespace OpenSim.Tests.Common.Mock { } + private XGroup GetXGroup(UUID groupID, string name) + { + XGroup group = m_data.GetGroup(groupID); + + + if (group == null) + m_log.DebugFormat("[MOCK GROUPS SERVICES CONNECTOR]: No group found with ID {0}", groupID); + + return group; + } + public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID groupID, string groupName) { m_log.DebugFormat( "[MOCK GROUPS SERVICES CONNECTOR]: Processing GetGroupRecord() for groupID {0}, name {1}", groupID, groupName); - XGroup[] groups; - string field, val; + XGroup xg = GetXGroup(groupID, groupName); - if (groupID != UUID.Zero) - { - field = "groupID"; - val = groupID.ToString(); - } - else - { - field = "name"; - val = groupName; - } - - groups = m_data.GetGroups(field, val); - - if (groups.Length == 0) + if (xg == null) return null; - XGroup xg = groups[0]; - GroupRecord gr = new GroupRecord() { GroupID = xg.groupID, @@ -196,8 +191,25 @@ namespace OpenSim.Tests.Common.Mock { } - public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) + public void SetAgentGroupInfo(UUID requestingAgentID, UUID agentID, UUID groupID, bool acceptNotices, bool listInProfile) { + m_log.DebugFormat( + "[MOCK GROUPS SERVICES CONNECTOR]: SetAgentGroupInfo, requestingAgentID {0}, agentID {1}, groupID {2}, acceptNotices {3}, listInProfile {4}", + requestingAgentID, agentID, groupID, acceptNotices, listInProfile); + + XGroup group = GetXGroup(groupID, null); + + if (group == null) + return; + + XGroupMember xgm = null; + if (!group.members.TryGetValue(agentID, out xgm)) + return; + + xgm.acceptNotices = acceptNotices; + xgm.listInProfile = listInProfile; + + m_data.StoreGroup(group); } public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID) @@ -213,8 +225,27 @@ namespace OpenSim.Tests.Common.Mock { } - public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) + public void AddAgentToGroup(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID) { + m_log.DebugFormat( + "[MOCK GROUPS SERVICES CONNECTOR]: AddAgentToGroup, requestingAgentID {0}, agentID {1}, groupID {2}, roleID {3}", + requestingAgentID, agentID, groupID, roleID); + + XGroup group = GetXGroup(groupID, null); + + if (group == null) + return; + + XGroupMember groupMember = new XGroupMember() + { + agentID = agentID, + groupID = groupID, + roleID = roleID + }; + + group.members[agentID] = groupMember; + + m_data.StoreGroup(group); } public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) @@ -259,9 +290,31 @@ namespace OpenSim.Tests.Common.Mock return null; } - public List GetGroupMembers(UUID requestingAgentID, UUID GroupID) + public List GetGroupMembers(UUID requestingAgentID, UUID groupID) { - return null; + m_log.DebugFormat( + "[MOCK GROUPS SERVICES CONNECTOR]: GetGroupMembers, requestingAgentID {0}, groupID {1}", + requestingAgentID, groupID); + + List groupMembers = new List(); + + XGroup group = GetXGroup(groupID, null); + + if (group == null) + return groupMembers; + + foreach (XGroupMember xgm in group.members.Values) + { + GroupMembersData gmd = new GroupMembersData(); + gmd.AgentID = xgm.agentID; + gmd.IsOwner = group.founderID == gmd.AgentID; + gmd.AcceptNotices = xgm.acceptNotices; + gmd.ListInProfile = xgm.listInProfile; + + groupMembers.Add(gmd); + } + + return groupMembers; } public List GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID) @@ -269,18 +322,93 @@ namespace OpenSim.Tests.Common.Mock return null; } - public List GetGroupNotices(UUID requestingAgentID, UUID GroupID) + public List GetGroupNotices(UUID requestingAgentID, UUID groupID) { - return null; + XGroup group = GetXGroup(groupID, null); + + if (group == null) + return null; + + List notices = new List(); + + foreach (XGroupNotice notice in group.notices.Values) + { + GroupNoticeData gnd = new GroupNoticeData() + { + NoticeID = notice.noticeID, + Timestamp = notice.timestamp, + FromName = notice.fromName, + Subject = notice.subject, + HasAttachment = notice.hasAttachment, + AssetType = (byte)notice.assetType + }; + + notices.Add(gnd); + } + + return notices; } public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID) { + m_log.DebugFormat( + "[MOCK GROUPS SERVICES CONNECTOR]: GetGroupNotices, requestingAgentID {0}, noticeID {1}", + requestingAgentID, noticeID); + + // Yes, not an efficient way to do it. + Dictionary groups = m_data.GetGroups(); + + foreach (XGroup group in groups.Values) + { + if (group.notices.ContainsKey(noticeID)) + { + XGroupNotice n = group.notices[noticeID]; + + GroupNoticeInfo gni = new GroupNoticeInfo(); + gni.GroupID = n.groupID; + gni.Message = n.message; + gni.BinaryBucket = n.binaryBucket; + gni.noticeData.NoticeID = n.noticeID; + gni.noticeData.Timestamp = n.timestamp; + gni.noticeData.FromName = n.fromName; + gni.noticeData.Subject = n.subject; + gni.noticeData.HasAttachment = n.hasAttachment; + gni.noticeData.AssetType = (byte)n.assetType; + + return gni; + } + } + return null; } public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket) { + m_log.DebugFormat( + "[MOCK GROUPS SERVICES CONNECTOR]: AddGroupNotice, requestingAgentID {0}, groupID {1}, noticeID {2}, fromName {3}, subject {4}, message {5}, binaryBucket.Length {6}", + requestingAgentID, groupID, noticeID, fromName, subject, message, binaryBucket.Length); + + XGroup group = GetXGroup(groupID, null); + + if (group == null) + return; + + XGroupNotice groupNotice = new XGroupNotice() + { + groupID = groupID, + noticeID = noticeID, + fromName = fromName, + subject = subject, + message = message, + timestamp = (uint)Util.UnixTimeSinceEpoch(), + hasAttachment = false, + assetType = 0, + binaryBucket = binaryBucket + }; + + group.notices[noticeID] = groupNotice; + + m_data.StoreGroup(group); } public void ResetAgentGroupChatSessions(UUID agentID) diff --git a/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs b/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs index ed29c39..5df8e04 100644 --- a/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs +++ b/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs @@ -69,11 +69,21 @@ namespace OpenSim.Data.Null m_store.StoreTerrain(terrain, regionID); } + public void StoreTerrain(TerrainData terrain, UUID regionID) + { + m_store.StoreTerrain(terrain, regionID); + } + public double[,] LoadTerrain(UUID regionID) { return m_store.LoadTerrain(regionID); } + public TerrainData LoadTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ) + { + return m_store.LoadTerrain(regionID, pSizeX, pSizeY, pSizeZ); + } + public void StoreLandObject(ILandObject Parcel) { m_store.StoreLandObject(Parcel); @@ -154,7 +164,7 @@ namespace OpenSim.Data.Null protected Dictionary m_sceneObjectParts = new Dictionary(); protected Dictionary> m_primItems = new Dictionary>(); - protected Dictionary m_terrains = new Dictionary(); + protected Dictionary m_terrains = new Dictionary(); protected Dictionary m_landData = new Dictionary(); public void Initialise(string dbfile) @@ -299,12 +309,17 @@ namespace OpenSim.Data.Null return new List(objects.Values); } - public void StoreTerrain(double[,] ter, UUID regionID) + public void StoreTerrain(TerrainData ter, UUID regionID) { m_terrains[regionID] = ter; } - public double[,] LoadTerrain(UUID regionID) + public void StoreTerrain(double[,] ter, UUID regionID) + { + m_terrains[regionID] = new HeightmapTerrainData(ter); + } + + public TerrainData LoadTerrain(UUID regionID, int pSizeX, int pSizeY, int pSizeZ) { if (m_terrains.ContainsKey(regionID)) return m_terrains[regionID]; @@ -312,6 +327,14 @@ namespace OpenSim.Data.Null return null; } + public double[,] LoadTerrain(UUID regionID) + { + if (m_terrains.ContainsKey(regionID)) + return m_terrains[regionID].GetDoubles(); + else + return null; + } + public void RemoveLandObject(UUID globalID) { if (m_landData.ContainsKey(globalID)) 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 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.ScriptEngine.Interfaces; +using OpenSim.Region.ScriptEngine.Shared; + +namespace OpenSim.Tests.Common +{ + public class MockScriptEngine : INonSharedRegionModule, IScriptModule, IScriptEngine + { + public IConfigSource ConfigSource { get; private set; } + + public IConfig Config { get; private set; } + + private Scene m_scene; + + /// + /// Expose posted events to tests. + /// + public Dictionary> PostedEvents { get; private set; } + + /// + /// A very primitive way of hooking text cose to a posed event. + /// + /// + /// May be replaced with something that uses more original code in the future. + /// + public event Action PostEventHook; + + public void Initialise(IConfigSource source) + { + ConfigSource = source; + + // Can set later on if required + Config = new IniConfig("MockScriptEngine", ConfigSource); + + PostedEvents = new Dictionary>(); + } + + public void Close() + { + } + + public void AddRegion(Scene scene) + { + m_scene = scene; + + m_scene.StackModuleInterface(this); + } + + public void RemoveRegion(Scene scene) + { + } + + public void RegionLoaded(Scene scene) + { + } + + public string Name { get { return "Mock Script Engine"; } } + public string ScriptEngineName { get { return Name; } } + + public Type ReplaceableInterface { get { return null; } } + +#pragma warning disable 0067 + public event ScriptRemoved OnScriptRemoved; + public event ObjectRemoved OnObjectRemoved; +#pragma warning restore 0067 + + public string GetXMLState (UUID itemID) + { + throw new System.NotImplementedException (); + } + + public bool SetXMLState(UUID itemID, string xml) + { + throw new System.NotImplementedException (); + } + + public bool PostScriptEvent(UUID itemID, string name, object[] args) + { +// Console.WriteLine("Posting event {0} for {1}", name, itemID); + + return PostScriptEvent(itemID, new EventParams(name, args, null)); + } + + public bool PostScriptEvent(UUID itemID, EventParams evParams) + { + List eventsForItem; + + if (!PostedEvents.ContainsKey(itemID)) + { + eventsForItem = new List(); + PostedEvents.Add(itemID, eventsForItem); + } + else + { + eventsForItem = PostedEvents[itemID]; + } + + eventsForItem.Add(evParams); + + if (PostEventHook != null) + PostEventHook(itemID, evParams); + + return true; + } + + public bool PostObjectEvent(uint localID, EventParams evParams) + { + return PostObjectEvent(m_scene.GetSceneObjectPart(localID), evParams); + } + + public bool PostObjectEvent(UUID itemID, string name, object[] args) + { + return PostObjectEvent(m_scene.GetSceneObjectPart(itemID), new EventParams(name, args, null)); + } + + private bool PostObjectEvent(SceneObjectPart part, EventParams evParams) + { + foreach (TaskInventoryItem item in part.Inventory.GetInventoryItems(InventoryType.LSL)) + PostScriptEvent(item.ItemID, evParams); + + return true; + } + + public void SuspendScript(UUID itemID) + { + throw new System.NotImplementedException (); + } + + public void ResumeScript(UUID itemID) + { + throw new System.NotImplementedException (); + } + + public ArrayList GetScriptErrors(UUID itemID) + { + throw new System.NotImplementedException (); + } + + public bool HasScript(UUID itemID, out bool running) + { + throw new System.NotImplementedException (); + } + + public bool GetScriptState(UUID itemID) + { + throw new System.NotImplementedException (); + } + + public void SaveAllState() + { + throw new System.NotImplementedException (); + } + + public void StartProcessing() + { + throw new System.NotImplementedException (); + } + + public float GetScriptExecutionTime(List itemIDs) + { + throw new System.NotImplementedException (); + } + + public Dictionary GetObjectScriptsExecutionTimes() + { + throw new System.NotImplementedException (); + } + + public IScriptWorkItem QueueEventHandler(object parms) + { + throw new System.NotImplementedException (); + } + + public DetectParams GetDetectParams(UUID item, int number) + { + throw new System.NotImplementedException (); + } + + public void SetMinEventDelay(UUID itemID, double delay) + { + throw new System.NotImplementedException (); + } + + public int GetStartParameter(UUID itemID) + { + throw new System.NotImplementedException (); + } + + public void SetScriptState(UUID itemID, bool state) + { + throw new System.NotImplementedException (); + } + + public void SetState(UUID itemID, string newState) + { + throw new System.NotImplementedException (); + } + + public void ApiResetScript(UUID itemID) + { + throw new System.NotImplementedException (); + } + + public void ResetScript (UUID itemID) + { + throw new System.NotImplementedException (); + } + + public IScriptApi GetApi(UUID itemID, string name) + { + throw new System.NotImplementedException (); + } + + public Scene World { get { return m_scene; } } + + public IScriptModule ScriptModule { get { return this; } } + + public string ScriptEnginePath { get { throw new System.NotImplementedException (); }} + + public string ScriptClassName { get { throw new System.NotImplementedException (); } } + + public string ScriptBaseClassName { get { throw new System.NotImplementedException (); } } + + public string[] ScriptReferencedAssemblies { get { throw new System.NotImplementedException (); } } + + public ParameterInfo[] ScriptBaseClassParameters { get { throw new System.NotImplementedException (); } } + + public void ClearPostedEvents() + { + PostedEvents.Clear(); + } + + public void SleepScript(UUID itemID, int delay) + { + } + } +} diff --git a/OpenSim/Tests/Common/Mock/TestClient.cs b/OpenSim/Tests/Common/Mock/TestClient.cs index dde37ab..0e1bc8f 100644 --- a/OpenSim/Tests/Common/Mock/TestClient.cs +++ b/OpenSim/Tests/Common/Mock/TestClient.cs @@ -38,7 +38,7 @@ using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Client; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { public class TestClient : IClientAPI, IClientCore { @@ -46,12 +46,10 @@ namespace OpenSim.Tests.Common.Mock EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing"); - private TestClient TeleportSceneClient; - private Scene m_scene; - private SceneManager m_sceneManager; // Properties so that we can get at received data for test purposes + public List ReceivedKills { get; private set; } public List ReceivedOfflineNotifications { get; private set; } public List ReceivedOnlineNotifications { get; private set; } public List ReceivedFriendshipTerminations { get; private set; } @@ -60,6 +58,27 @@ namespace OpenSim.Tests.Common.Mock public List SentImagePacketPackets { get; private set; } public List SentImageNotInDatabasePackets { get; private set; } + // Test client specific events - for use by tests to implement some IClientAPI behaviour. + public event Action OnReceivedMoveAgentIntoRegion; + public event Action OnTestClientInformClientOfNeighbour; + public event TestClientOnSendRegionTeleportDelegate OnTestClientSendRegionTeleport; + + public event Action OnReceivedEntityUpdate; + + public event OnReceivedChatMessageDelegate OnReceivedChatMessage; + public event Action OnReceivedInstantMessage; + + public event Action OnReceivedSendRebakeAvatarTextures; + + public delegate void TestClientOnSendRegionTeleportDelegate( + ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, + uint locationID, uint flags, string capsURL); + + public delegate void OnReceivedChatMessageDelegate( + string message, byte type, Vector3 fromPos, string fromName, + UUID fromAgentID, UUID ownerID, byte source, byte audible); + + // disable warning: public events, part of the public API #pragma warning disable 67 @@ -103,6 +122,7 @@ namespace OpenSim.Tests.Common.Mock public event Action OnCompleteMovementToRegion; public event UpdateAgent OnPreAgentUpdate; public event UpdateAgent OnAgentUpdate; + public event UpdateAgent OnAgentCameraUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; @@ -193,6 +213,7 @@ namespace OpenSim.Tests.Common.Mock public event EstateCovenantRequest OnEstateCovenantRequest; public event EstateChangeInfo OnEstateChangeInfo; public event EstateManageTelehub OnEstateManageTelehub; + public event CachedTextureRequest OnCachedTextureRequest; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; @@ -430,33 +451,21 @@ namespace OpenSim.Tests.Common.Mock /// /// Constructor /// - /// - /// Can be used for a test where there is only one region or where there are multiple regions that are not - /// neighbours and where no teleporting takes place. In other situations, the constructor that takes in a - /// scene manager should be used. - /// - /// - /// - public TestClient(AgentCircuitData agentData, Scene scene) : this(agentData, scene, null) {} - - /// - /// Constructor - /// /// /// /// - public TestClient(AgentCircuitData agentData, Scene scene, SceneManager sceneManager) + public TestClient(AgentCircuitData agentData, Scene scene) { m_agentId = agentData.AgentID; m_firstName = agentData.firstname; m_lastName = agentData.lastname; m_circuitCode = agentData.circuitcode; m_scene = scene; - m_sceneManager = sceneManager; SessionId = agentData.SessionID; SecureSessionId = agentData.SecureSessionID; CapsSeedUrl = agentData.CapsPath; + ReceivedKills = new List(); ReceivedOfflineNotifications = new List(); ReceivedOnlineNotifications = new List(); ReceivedFriendshipTerminations = new List(); @@ -467,6 +476,34 @@ namespace OpenSim.Tests.Common.Mock } /// + /// Trigger chat coming from this connection. + /// + /// + /// + /// + public bool Chat(int channel, ChatTypeEnum type, string message) + { + ChatMessage handlerChatFromClient = OnChatFromClient; + + if (handlerChatFromClient != null) + { + OSChatMessage args = new OSChatMessage(); + args.Channel = channel; + args.From = Name; + args.Message = message; + args.Type = type; + + args.Scene = Scene; + args.Sender = this; + args.SenderUUID = AgentId; + + handlerChatFromClient(this, args); + } + + return true; + } + + /// /// Attempt a teleport to the given region. /// /// @@ -479,7 +516,20 @@ namespace OpenSim.Tests.Common.Mock public void CompleteMovement() { - OnCompleteMovementToRegion(this, true); + if (OnCompleteMovementToRegion != null) + OnCompleteMovementToRegion(this, true); + } + + /// + /// Emulate sending an IM from the viewer to the simulator. + /// + /// + public void HandleImprovedInstantMessage(GridInstantMessage im) + { + ImprovedInstantMessage handlerInstantMessage = OnInstantMessage; + + if (handlerInstantMessage != null) + handlerInstantMessage(this, im); } public virtual void ActivateGesture(UUID assetId, UUID gestureId) @@ -494,6 +544,11 @@ namespace OpenSim.Tests.Common.Mock { } + public void SendCachedTextureResponse(ISceneEntity avatar, int serial, List cachedTextures) + { + + } + public virtual void Kick(string message) { } @@ -508,22 +563,22 @@ namespace OpenSim.Tests.Common.Mock public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { - } - public virtual void SendKillObject(ulong regionHandle, List localID) + public virtual void SendKillObject(List localID) { + ReceivedKills.AddRange(localID); } public virtual void SetChildAgentThrottle(byte[] throttle) { } + public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } - public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } @@ -532,19 +587,23 @@ namespace OpenSim.Tests.Common.Mock string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, UUID ownerID, byte source, byte audible) { +// Console.WriteLine("mmm {0} {1} {2}", message, Name, AgentId); + if (OnReceivedChatMessage != null) + OnReceivedChatMessage(message, type, fromPos, fromName, fromAgentID, ownerID, source, audible); } public void SendInstantMessage(GridInstantMessage im) { - + if (OnReceivedInstantMessage != null) + OnReceivedInstantMessage(im); } - public void SendGenericMessage(string method, List message) + public void SendGenericMessage(string method, UUID invoice, List message) { } - public void SendGenericMessage(string method, List message) + public void SendGenericMessage(string method, UUID invoice, List message) { } @@ -566,13 +625,15 @@ namespace OpenSim.Tests.Common.Mock public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { + if (OnReceivedMoveAgentIntoRegion != null) + OnReceivedMoveAgentIntoRegion(regInfo, pos, look); } public virtual AgentCircuitData RequestClientInfo() { AgentCircuitData agentData = new AgentCircuitData(); agentData.AgentID = AgentId; - agentData.SessionID = UUID.Zero; + agentData.SessionID = SessionId; agentData.SecureSessionID = UUID.Zero; agentData.circuitcode = m_circuitCode; agentData.child = false; @@ -591,46 +652,29 @@ namespace OpenSim.Tests.Common.Mock public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { - m_log.DebugFormat("[TEST CLIENT]: Processing inform client of neighbour"); - - // In response to this message, we are going to make a teleport to the scene we've previous been told - // about by test code (this needs to be improved). - AgentCircuitData newAgent = RequestClientInfo(); - - // Stage 2: add the new client as a child agent to the scene - uint x, y; - Utils.LongToUInts(neighbourHandle, out x, out y); - x /= Constants.RegionSize; - y /= Constants.RegionSize; - - Scene neighbourScene; - m_sceneManager.TryGetScene(x, y, out neighbourScene); - - TeleportSceneClient = new TestClient(newAgent, neighbourScene, m_sceneManager); - neighbourScene.AddNewClient(TeleportSceneClient, PresenceType.User); + if (OnTestClientInformClientOfNeighbour != null) + OnTestClientInformClientOfNeighbour(neighbourHandle, neighbourExternalEndPoint); } - public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, - uint locationID, uint flags, string capsURL) + public virtual void SendRegionTeleport( + ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, + uint locationID, uint flags, string capsURL) { - m_log.DebugFormat("[TEST CLIENT]: Received SendRegionTeleport"); + m_log.DebugFormat( + "[TEST CLIENT]: Received SendRegionTeleport for {0} {1} on {2}", m_firstName, m_lastName, m_scene.Name); CapsSeedUrl = capsURL; - // We don't do this here so that the source region can complete processing first in a single-threaded - // regression test scenario. The test itself will have to call CompleteTeleportClientSide() after a teleport - // CompleteTeleportClientSide(); - } - - public void CompleteTeleportClientSide() - { - TeleportSceneClient.CompleteMovement(); - //TeleportTargetScene.AgentCrossing(newAgent.AgentID, new Vector3(90, 90, 90), false); + if (OnTestClientSendRegionTeleport != null) + OnTestClientSendRegionTeleport( + regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL); } public virtual void SendTeleportFailed(string reason) { - m_log.DebugFormat("[TEST CLIENT]: Teleport failed with reason {0}", reason); + m_log.DebugFormat( + "[TEST CLIENT]: Teleport failed for {0} {1} on {2} with reason {3}", + m_firstName, m_lastName, m_scene.Name, reason); } public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, @@ -660,7 +704,7 @@ namespace OpenSim.Tests.Common.Mock { } - public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) + 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) { } @@ -682,6 +726,8 @@ namespace OpenSim.Tests.Common.Mock public void SendEntityUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { + if (OnReceivedEntityUpdate != null) + OnReceivedEntityUpdate(entity, updateFlags); } public void ReprioritizeUpdates() @@ -786,11 +832,6 @@ namespace OpenSim.Tests.Common.Mock { OnRegionHandShakeReply(this); } - - if (OnCompleteMovementToRegion != null) - { - OnCompleteMovementToRegion(this, true); - } } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) @@ -884,11 +925,6 @@ namespace OpenSim.Tests.Common.Mock } - public bool AddMoney(int debit) - { - return false; - } - public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase) { } @@ -1235,6 +1271,8 @@ namespace OpenSim.Tests.Common.Mock public void SendRebakeAvatarTextures(UUID textureID) { + if (OnReceivedSendRebakeAvatarTextures != null) + OnReceivedSendRebakeAvatarTextures(textureID); } public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) @@ -1269,12 +1307,17 @@ namespace OpenSim.Tests.Common.Mock { } - public void StopFlying(ISceneEntity presence) + public void SendAgentTerseUpdate(ISceneEntity presence) { } public void SendPlacesReply(UUID queryID, UUID transactionID, PlacesReplyData[] data) { } + + public void SendPartPhysicsProprieties(ISceneEntity entity) + { + } + } } 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 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Reflection; +using System.Threading; +using log4net; +using Nini.Config; +using Mono.Addins; +using OpenMetaverse; +using OpenMetaverse.StructuredData; +using OpenSim.Framework; +using OpenSim.Framework.Servers; +using OpenSim.Region.ClientStack.Linden; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Tests.Common +{ + public class TestEventQueueGetModule : IEventQueue, INonSharedRegionModule + { + public class Event + { + public string Name { get; set; } + public object[] Args { get; set; } + + public Event(string name, object[] args) + { + name = Name; + args = Args; + } + } + + public Dictionary> Events { get; set; } + + public void Initialise(IConfigSource source) {} + + public void Close() {} + + public void AddRegion(Scene scene) + { + Events = new Dictionary>(); + scene.RegisterModuleInterface(this); + } + + public void RemoveRegion (Scene scene) {} + + public void RegionLoaded (Scene scene) {} + + public string Name { get { return "TestEventQueueGetModule"; } } + + public Type ReplaceableInterface { get { return null; } } + + private void AddEvent(UUID avatarID, string name, params object[] args) + { + Console.WriteLine("Adding event {0} for {1}", name, avatarID); + + List avEvents; + + if (!Events.ContainsKey(avatarID)) + { + avEvents = new List(); + Events[avatarID] = avEvents; + } + else + { + avEvents = Events[avatarID]; + } + + avEvents.Add(new Event(name, args)); + } + + public void ClearEvents() + { + if (Events != null) + Events.Clear(); + } + + public bool Enqueue(OSD o, UUID avatarID) + { + AddEvent(avatarID, "Enqueue", o); + return true; + } + + public void DisableSimulator(ulong handle, UUID avatarID) + { + AddEvent(avatarID, "DisableSimulator", handle); + } + + public void EnableSimulator (ulong handle, IPEndPoint endPoint, UUID avatarID, int regionSizeX, int regionSizeY) + { + AddEvent(avatarID, "EnableSimulator", handle); + } + + public void EstablishAgentCommunication (UUID avatarID, IPEndPoint endPoint, string capsPath, + ulong regionHandle, int regionSizeX, int regionSizeY) + { + AddEvent(avatarID, "EstablishAgentCommunication", endPoint, capsPath); + } + + public void TeleportFinishEvent (ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, + uint locationID, uint flags, string capsURL, UUID agentID, int regionSizeX, int regionSizeY) + { + AddEvent(agentID, "TeleportFinishEvent", regionHandle, simAccess, regionExternalEndPoint, locationID, flags, capsURL); + } + + public void CrossRegion (ulong handle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, + string capsURL, UUID avatarID, UUID sessionID, int regionSizeX, int regionSizeY) + { + AddEvent(avatarID, "CrossRegion", handle, pos, lookAt, newRegionExternalEndPoint, capsURL, sessionID); + } + + public void ChatterboxInvitation( + UUID sessionID, string sessionName, UUID fromAgent, string message, UUID toAgent, string fromName, + byte dialog, uint timeStamp, bool offline, int parentEstateID, Vector3 position, uint ttl, + UUID transactionID, bool fromGroup, byte[] binaryBucket) + { + AddEvent( + toAgent, "ChatterboxInvitation", sessionID, sessionName, fromAgent, message, toAgent, fromName, dialog, + timeStamp, offline, parentEstateID, position, ttl, transactionID, fromGroup, binaryBucket); + } + + public void ChatterBoxSessionAgentListUpdates (UUID sessionID, UUID fromAgent, UUID toAgent, bool canVoiceChat, bool isModerator, bool textMute) + { + AddEvent(toAgent, "ChatterBoxSessionAgentListUpdates", sessionID, fromAgent, canVoiceChat, isModerator, textMute); + } + + public void ParcelProperties (OpenMetaverse.Messages.Linden.ParcelPropertiesMessage parcelPropertiesMessage, UUID avatarID) + { + AddEvent(avatarID, "ParcelProperties", parcelPropertiesMessage); + } + + public void GroupMembership (OpenMetaverse.Packets.AgentGroupDataUpdatePacket groupUpdate, UUID avatarID) + { + AddEvent(avatarID, "GroupMembership", groupUpdate); + } + + public OSD ScriptRunningEvent (UUID objectID, UUID itemID, bool running, bool mono) + { + Console.WriteLine("ONE"); + throw new System.NotImplementedException (); + } + + public OSD BuildEvent(string eventName, OSD eventBody) + { + Console.WriteLine("TWO"); + throw new System.NotImplementedException (); + } + + public void partPhysicsProperties (uint localID, byte physhapetype, float density, float friction, float bounce, float gravmod, UUID avatarID) + { + AddEvent(avatarID, "partPhysicsProperties", localID, physhapetype, density, friction, bounce, gravmod); + } + } +} \ 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 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Text; +using HttpServer; +using OpenSim.Framework; + +namespace OpenSim.Tests.Common +{ + public class TestHttpClientContext: IHttpClientContext + { + /// + /// Bodies of responses from the server. + /// + public string ResponseBody + { + get { return Encoding.UTF8.GetString(m_responseStream.ToArray()); } + } + + public Byte[] ResponseBodyBytes + { + get{ return m_responseStream.ToArray(); } + } + + private MemoryStream m_responseStream = new MemoryStream(); + + public bool IsSecured { get; set; } + + public bool Secured + { + get { return IsSecured; } + set { IsSecured = value; } + } + + public TestHttpClientContext(bool secured) + { + Secured = secured; + } + + public void Disconnect(SocketError error) + { +// Console.WriteLine("TestHttpClientContext.Disconnect Received disconnect with status {0}", error); + } + + public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body) {Console.WriteLine("x");} + public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) {Console.WriteLine("xx");} + public void Respond(string body) { Console.WriteLine("xxx");} + + public void Send(byte[] buffer) + { + // Getting header data here +// Console.WriteLine("xxxx: Got {0}", Encoding.UTF8.GetString(buffer)); + } + + public void Send(byte[] buffer, int offset, int size) + { +// Util.PrintCallStack(); +// +// Console.WriteLine( +// "TestHttpClientContext.Send(byte[], int, int) got offset={0}, size={1}, buffer={2}", +// offset, size, Encoding.UTF8.GetString(buffer)); + + m_responseStream.Write(buffer, offset, size); + } + + public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType) {Console.WriteLine("xxxxxx");} + public void Close() { } + public bool EndWhenDone { get { return false;} set { return;}} + + public HTTPNetworkContext GiveMeTheNetworkStreamIKnowWhatImDoing() + { + return new HTTPNetworkContext(); + } + + public event EventHandler Disconnected = delegate { }; + /// + /// A request have been received in the context. + /// + public event EventHandler RequestReceived = delegate { }; + } +} \ 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 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Specialized; +using System.IO; +using HttpServer; +using HttpServer.FormDecoders; + +namespace OpenSim.Tests.Common +{ + public class TestHttpRequest: IHttpRequest + { + private string _uriPath; + public bool BodyIsComplete + { + get { return true; } + } + public string[] AcceptTypes + { + get {return _acceptTypes; } + } + private string[] _acceptTypes; + public Stream Body + { + get { return _body; } + set { _body = value;} + } + private Stream _body; + public ConnectionType Connection + { + get { return _connection; } + set { _connection = value; } + } + private ConnectionType _connection; + public int ContentLength + { + get { return _contentLength; } + set { _contentLength = value; } + } + private int _contentLength; + public NameValueCollection Headers + { + get { return _headers; } + } + private NameValueCollection _headers = new NameValueCollection(); + + public string HttpVersion { get; set; } + + public string Method + { + get { return _method; } + set { _method = value; } + } + private string _method = null; + public HttpInput QueryString + { + get { return _queryString; } + } + private HttpInput _queryString = null; + public Uri Uri + { + get { return _uri; } + set { _uri = value; } + } + private Uri _uri = null; + public string[] UriParts + { + get { return _uri.Segments; } + } + public HttpParam Param + { + get { return null; } + } + public HttpForm Form + { + get { return null; } + } + public bool IsAjax + { + get { return false; } + } + public RequestCookies Cookies + { + get { return null; } + } + + public TestHttpRequest() + { + HttpVersion = "HTTP/1.1"; + } + + public TestHttpRequest(string contentEncoding, string contentType, string userAgent, + string remoteAddr, string remotePort, string[] acceptTypes, + ConnectionType connectionType, int contentLength, Uri uri) : base() + { + _headers["content-encoding"] = contentEncoding; + _headers["content-type"] = contentType; + _headers["user-agent"] = userAgent; + _headers["remote_addr"] = remoteAddr; + _headers["remote_port"] = remotePort; + + _acceptTypes = acceptTypes; + _connection = connectionType; + _contentLength = contentLength; + _uri = uri; + } + + public void DecodeBody(FormDecoderProvider providers) {} + public void SetCookies(RequestCookies cookies) {} + public void AddHeader(string name, string value) + { + _headers.Add(name, value); + } + public int AddToBody(byte[] bytes, int offset, int length) + { + return 0; + } + public void Clear() {} + + public object Clone() + { + TestHttpRequest clone = new TestHttpRequest(); + clone._acceptTypes = _acceptTypes; + clone._connection = _connection; + clone._contentLength = _contentLength; + clone._uri = _uri; + clone._headers = new NameValueCollection(_headers); + + return clone; + } + public IHttpResponse CreateResponse(IHttpClientContext context) + { + return new HttpResponse(context, this); + } + /// + /// Path and query (will be merged with the host header) and put in Uri + /// + /// + public string UriPath + { + get { return _uriPath; } + set + { + _uriPath = value; + + } + } + } +} \ 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 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.IO; +using System.Net; +using System.Text; +using HttpServer; + +namespace OpenSim.Tests.Common +{ + public class TestHttpResponse: IHttpResponse + { + public Stream Body + { + get { return _body; } + + set { _body = value; } + } + private Stream _body; + + public string ProtocolVersion + { + get { return _protocolVersion; } + set { _protocolVersion = value; } + } + private string _protocolVersion; + + public bool Chunked + { + get { return _chunked; } + + set { _chunked = value; } + } + private bool _chunked; + + public ConnectionType Connection + { + get { return _connection; } + + set { _connection = value; } + } + private ConnectionType _connection; + + public Encoding Encoding + { + get { return _encoding; } + + set { _encoding = value; } + } + private Encoding _encoding; + + public int KeepAlive + { + get { return _keepAlive; } + + set { _keepAlive = value; } + } + private int _keepAlive; + + public HttpStatusCode Status + { + get { return _status; } + + set { _status = value; } + } + private HttpStatusCode _status; + + public string Reason + { + get { return _reason; } + + set { _reason = value; } + } + private string _reason; + + public long ContentLength + { + get { return _contentLength; } + + set { _contentLength = value; } + } + private long _contentLength; + + public string ContentType + { + get { return _contentType; } + + set { _contentType = value; } + } + private string _contentType; + + public bool HeadersSent + { + get { return _headersSent; } + } + private bool _headersSent; + + public bool Sent + { + get { return _sent; } + } + private bool _sent; + + public ResponseCookies Cookies + { + get { return _cookies; } + } + private ResponseCookies _cookies = null; + + public TestHttpResponse() + { + _headersSent = false; + _sent = false; + } + + public void AddHeader(string name, string value) {} + + public void Send() + { + if (!_headersSent) SendHeaders(); + if (_sent) throw new InvalidOperationException("stuff already sent"); + _sent = true; + } + + public void SendBody(byte[] buffer, int offset, int count) + { + if (!_headersSent) SendHeaders(); + _sent = true; + } + + public void SendBody(byte[] buffer) + { + if (!_headersSent) SendHeaders(); + _sent = true; + } + + public void SendHeaders() + { + if (_headersSent) throw new InvalidOperationException("headers already sent"); + _headersSent = true; + } + + public void Redirect(Uri uri) {} + public void Redirect(string url) {} + } +} \ No newline at end of file diff --git a/OpenSim/Tests/Common/Mock/TestInventoryDataPlugin.cs b/OpenSim/Tests/Common/Mock/TestInventoryDataPlugin.cs index fc44358..c97a765 100644 --- a/OpenSim/Tests/Common/Mock/TestInventoryDataPlugin.cs +++ b/OpenSim/Tests/Common/Mock/TestInventoryDataPlugin.cs @@ -33,7 +33,7 @@ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { /// /// In memory inventory data plugin for test purposes. Could be another dll when properly filled out and when the @@ -185,7 +185,7 @@ namespace OpenSim.Tests.Common.Mock public void addInventoryItem(InventoryItemBase item) { -// InventoryFolderBase folder = m_folders[item.Folder]; + InventoryFolderBase folder = m_folders[item.Folder]; // m_log.DebugFormat( // "[MOCK INV DB]: Adding inventory item {0} {1} in {2} {3}", item.Name, item.ID, folder.Name, folder.ID); 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 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using Nini.Config; +using OpenMetaverse.Packets; +using OpenSim.Framework; +using OpenSim.Region.ClientStack.LindenUDP; + +namespace OpenSim.Tests.Common +{ + /// + /// This class enables regression testing of the LLUDPServer by allowing us to intercept outgoing data. + /// + public class TestLLUDPServer : LLUDPServer + { + public List PacketsSent { get; private set; } + + public TestLLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager) + : base(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource, circuitManager) + { + PacketsSent = new List(); + } + + public override void SendAckImmediate(IPEndPoint remoteEndpoint, PacketAckPacket ack) + { + PacketsSent.Add(ack); + } + + public override void SendPacket( + LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting, UnackedPacketMethod method) + { + PacketsSent.Add(packet); + } + + public void ClientOutgoingPacketHandler(IClientAPI client, bool resendUnacked, bool sendAcks, bool sendPing) + { + m_resendUnacked = resendUnacked; + m_sendAcks = sendAcks; + m_sendPing = sendPing; + + ClientOutgoingPacketHandler(client); + } + +//// /// +//// /// The chunks of data to pass to the LLUDPServer when it calls EndReceive +//// /// +//// protected Queue m_chunksToLoad = new Queue(); +// +//// protected override void BeginReceive() +//// { +//// if (m_chunksToLoad.Count > 0 && m_chunksToLoad.Peek().BeginReceiveException) +//// { +//// ChunkSenderTuple tuple = m_chunksToLoad.Dequeue(); +//// reusedEpSender = tuple.Sender; +//// throw new SocketException(); +//// } +//// } +// +//// protected override bool EndReceive(out int numBytes, IAsyncResult result, ref EndPoint epSender) +//// { +//// numBytes = 0; +//// +//// //m_log.Debug("Queue size " + m_chunksToLoad.Count); +//// +//// if (m_chunksToLoad.Count <= 0) +//// return false; +//// +//// ChunkSenderTuple tuple = m_chunksToLoad.Dequeue(); +//// RecvBuffer = tuple.Data; +//// numBytes = tuple.Data.Length; +//// epSender = tuple.Sender; +//// +//// return true; +//// } +// +//// public override void SendPacketTo(byte[] buffer, int size, SocketFlags flags, uint circuitcode) +//// { +//// // Don't do anything just yet +//// } +// +// /// +// /// Signal that this chunk should throw an exception on Socket.BeginReceive() +// /// +// /// +// public void LoadReceiveWithBeginException(EndPoint epSender) +// { +// ChunkSenderTuple tuple = new ChunkSenderTuple(epSender); +// tuple.BeginReceiveException = true; +// m_chunksToLoad.Enqueue(tuple); +// } +// +// /// +// /// Load some data to be received by the LLUDPServer on the next receive call +// /// +// /// +// /// +// public void LoadReceive(byte[] data, EndPoint epSender) +// { +// m_chunksToLoad.Enqueue(new ChunkSenderTuple(data, epSender)); +// } +// +// /// +// /// Load a packet to be received by the LLUDPServer on the next receive call +// /// +// /// +// public void LoadReceive(Packet packet, EndPoint epSender) +// { +// LoadReceive(packet.ToBytes(), epSender); +// } +// +// /// +// /// Calls the protected asynchronous result method. This fires out all data chunks currently queued for send +// /// +// /// +// public void ReceiveData(IAsyncResult result) +// { +// // Doesn't work the same way anymore +//// while (m_chunksToLoad.Count > 0) +//// OnReceivedData(result); +// } + } + + /// + /// Record the data and sender tuple + /// + public class ChunkSenderTuple + { + public byte[] Data; + public EndPoint Sender; + public bool BeginReceiveException; + + public ChunkSenderTuple(byte[] data, EndPoint sender) + { + Data = data; + Sender = sender; + } + + public ChunkSenderTuple(EndPoint sender) + { + Sender = sender; + } + } +} diff --git a/OpenSim/Tests/Common/Mock/TestLandChannel.cs b/OpenSim/Tests/Common/Mock/TestLandChannel.cs index 4b4d52d..89ebcd5 100644 --- a/OpenSim/Tests/Common/Mock/TestLandChannel.cs +++ b/OpenSim/Tests/Common/Mock/TestLandChannel.cs @@ -32,7 +32,7 @@ using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.CoreModules.World.Land; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { /// /// Land channel for test purposes @@ -81,6 +81,11 @@ namespace OpenSim.Tests.Common.Mock return obj; } + public ILandObject GetLandObject(Vector3 position) + { + return GetLandObject(position.X, position.Y); + } + public ILandObject GetLandObject(int x, int y) { return GetNoLand(); diff --git a/OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs b/OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs index e769d30..7b1d2b5 100644 --- a/OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs +++ b/OpenSim/Tests/Common/Mock/TestOSHttpRequest.cs @@ -35,7 +35,7 @@ using System.Text; using System.Web; using OpenSim.Framework.Servers.HttpServer; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { public class TestOSHttpRequest : IOSHttpRequest { diff --git a/OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs b/OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs index e10fe82..2e17f1e 100644 --- a/OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs +++ b/OpenSim/Tests/Common/Mock/TestOSHttpResponse.cs @@ -32,7 +32,7 @@ using System.Text; using System.Web; using OpenSim.Framework.Servers.HttpServer; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { public class TestOSHttpResponse : IOSHttpResponse { diff --git a/OpenSim/Tests/Common/Mock/TestScene.cs b/OpenSim/Tests/Common/Mock/TestScene.cs index d4b5648..1a93c9f 100644 --- a/OpenSim/Tests/Common/Mock/TestScene.cs +++ b/OpenSim/Tests/Common/Mock/TestScene.cs @@ -28,23 +28,24 @@ using System; using Nini.Config; using OpenSim.Framework; -using OpenSim.Framework.Communications; + using OpenSim.Framework.Servers; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.PhysicsModules.SharedBase; +using OpenSim.Services.Interfaces; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { public class TestScene : Scene { public TestScene( - RegionInfo regInfo, AgentCircuitManager authen, - SceneCommunicationService sceneGridService, ISimulationDataService simDataService, IEstateDataService estateDataService, - bool dumpAssetsToFile, + RegionInfo regInfo, AgentCircuitManager authen, + ISimulationDataService simDataService, IEstateDataService estateDataService, IConfigSource config, string simulatorVersion) - : base(regInfo, authen, sceneGridService, simDataService, estateDataService, - dumpAssetsToFile, config, simulatorVersion) + : base(regInfo, authen, simDataService, estateDataService, + config, simulatorVersion) { } diff --git a/OpenSim/Tests/Common/Mock/TestXInventoryDataPlugin.cs b/OpenSim/Tests/Common/Mock/TestXInventoryDataPlugin.cs index ccbdf81..2b272e6 100644 --- a/OpenSim/Tests/Common/Mock/TestXInventoryDataPlugin.cs +++ b/OpenSim/Tests/Common/Mock/TestXInventoryDataPlugin.cs @@ -35,7 +35,7 @@ using OpenSim.Framework; using OpenSim.Data; using OpenSim.Data.Null; -namespace OpenSim.Tests.Common.Mock +namespace OpenSim.Tests.Common { public class TestXInventoryDataPlugin : NullGenericDataHandler, IXInventoryData { @@ -46,17 +46,33 @@ namespace OpenSim.Tests.Common.Mock public XInventoryItem[] GetItems(string[] fields, string[] vals) { +// Console.WriteLine( +// "Requesting items, fields {0}, vals {1}", string.Join(", ", fields), string.Join(", ", vals)); + List origItems = Get(fields, vals, m_allItems.Values.ToList()); - return origItems.Select(i => i.Clone()).ToArray(); + XInventoryItem[] items = origItems.Select(i => i.Clone()).ToArray(); + +// Console.WriteLine("Found {0} items", items.Length); +// Array.ForEach(items, i => Console.WriteLine("Found item {0} {1}", i.inventoryName, i.inventoryID)); + + return items; } public XInventoryFolder[] GetFolders(string[] fields, string[] vals) { +// Console.WriteLine( +// "Requesting folders, fields {0}, vals {1}", string.Join(", ", fields), string.Join(", ", vals)); + List origFolders = Get(fields, vals, m_allFolders.Values.ToList()); - return origFolders.Select(f => f.Clone()).ToArray(); + XInventoryFolder[] folders = origFolders.Select(f => f.Clone()).ToArray(); + +// Console.WriteLine("Found {0} folders", folders.Length); +// Array.ForEach(folders, f => Console.WriteLine("Found folder {0} {1}", f.folderName, f.folderID)); + + return folders; } public bool StoreFolder(XInventoryFolder folder) @@ -72,7 +88,9 @@ namespace OpenSim.Tests.Common.Mock { m_allItems[item.inventoryID] = item.Clone(); -// Console.WriteLine("Added item {0} {1}, creator {2}, owner {3}", item.inventoryName, item.inventoryID, item.creatorID, item.avatarID); +// Console.WriteLine( +// "Added item {0} {1}, folder {2}, creator {3}, owner {4}", +// item.inventoryName, item.inventoryID, item.parentFolderID, item.creatorID, item.avatarID); return true; } @@ -104,7 +122,30 @@ namespace OpenSim.Tests.Common.Mock } public bool MoveItem(string id, string newParent) { throw new NotImplementedException(); } - public bool MoveFolder(string id, string newParent) { throw new NotImplementedException(); } + + public bool MoveFolder(string id, string newParent) + { + // Don't use GetFolders() here - it takes a clone! + XInventoryFolder folder = m_allFolders[new UUID(id)]; + + if (folder == null) + return false; + + folder.parentFolderID = new UUID(newParent); + +// XInventoryFolder[] newParentFolders +// = GetFolders(new string[] { "folderID" }, new string[] { folder.parentFolderID.ToString() }); + +// Console.WriteLine( +// "Moved folder {0} {1}, to {2} {3}", +// folder.folderName, folder.folderID, newParentFolders[0].folderName, folder.parentFolderID); + + // TODO: Really need to implement folder version incrementing, though this should be common code anyway, + // not reimplemented in each db plugin. + + return true; + } + public XInventoryItem[] GetActiveGestures(UUID principalID) { throw new NotImplementedException(); } public int GetAssetPermissions(UUID principalID, UUID assetID) { throw new NotImplementedException(); } } diff --git a/OpenSim/Tests/Common/OpenSimTestCase.cs b/OpenSim/Tests/Common/OpenSimTestCase.cs index 8c40923..9fea348 100644 --- a/OpenSim/Tests/Common/OpenSimTestCase.cs +++ b/OpenSim/Tests/Common/OpenSimTestCase.cs @@ -27,6 +27,8 @@ using System; using NUnit.Framework; +using OpenSim.Framework; +using OpenSim.Framework.Servers; namespace OpenSim.Tests.Common { @@ -36,11 +38,18 @@ namespace OpenSim.Tests.Common [SetUp] public virtual void SetUp() { -// TestHelpers.InMethod(); + //TestHelpers.InMethod(); // Disable logging for each test so that one where logging is enabled doesn't cause all subsequent tests // to have logging on if it failed with an exception. TestHelpers.DisableLogging(); + + // This is an unfortunate bit of clean up we have to do because MainServer manages things through static + // variables and the VM is not restarted between tests. + if (MainServer.Instance != null) + { + MainServer.RemoveHttpServer(MainServer.Instance.Port); +// MainServer.Instance = null; + } } } -} - +} \ No newline at end of file diff --git a/OpenSim/Tests/Common/TestHelpers.cs b/OpenSim/Tests/Common/TestHelpers.cs index 57da802..6bf23f8 100644 --- a/OpenSim/Tests/Common/TestHelpers.cs +++ b/OpenSim/Tests/Common/TestHelpers.cs @@ -114,6 +114,25 @@ namespace OpenSim.Tests.Common } /// + /// Parse a UUID stem into a full UUID. + /// + /// + /// The fragment will come at the start of the UUID. The rest will be 0s + /// + /// + /// + /// A UUID fragment that will be parsed into a full UUID. Therefore, it can only contain + /// cahracters which are valid in a UUID, except for "-" which is currently only allowed if a full UUID is + /// given as the 'fragment'. + /// + public static UUID ParseStem(string stem) + { + string rawUuid = stem.PadRight(32, '0'); + + return UUID.Parse(rawUuid); + } + + /// /// Parse tail section into full UUID. /// /// @@ -122,5 +141,24 @@ namespace OpenSim.Tests.Common { return new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", tail)); } + + /// + /// Parse a UUID tail section into a full UUID. + /// + /// + /// The fragment will come at the end of the UUID. The rest will be 0s + /// + /// + /// + /// A UUID fragment that will be parsed into a full UUID. Therefore, it can only contain + /// cahracters which are valid in a UUID, except for "-" which is currently only allowed if a full UUID is + /// given as the 'fragment'. + /// + public static UUID ParseTail(string stem) + { + string rawUuid = stem.PadLeft(32, '0'); + + return UUID.Parse(rawUuid); + } } } -- cgit v1.1