initial commit

This commit is contained in:
Jo 2025-01-07 02:06:59 +01:00
parent 6715289efe
commit 788c3389af
37645 changed files with 2526849 additions and 80 deletions

View file

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using UnityEditor.AddressableAssets.HostingServices;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;
namespace UnityEditor.AddressableAssets.Tests.HostingServices
{
public abstract class AbstractTestHostingService : IHostingService
{
public string DescriptiveName { get; set; }
public int InstanceId { get; set; }
public List<string> HostingServiceContentRoots { get; protected set; }
public Dictionary<string, string> ProfileVariables { get; protected set; }
public bool IsHostingServiceRunning { get; protected set; }
public ILogger Logger { get; set; }
protected AbstractTestHostingService()
{
HostingServiceContentRoots = new List<string>();
ProfileVariables = new Dictionary<string, string>();
}
public virtual void StartHostingService()
{
}
public virtual void StopHostingService()
{
}
public virtual void CloseHostingService()
{
}
public virtual void OnBeforeSerialize(KeyDataStore dataStore)
{
}
public virtual void OnAfterDeserialize(KeyDataStore dataStore)
{
}
public string EvaluateProfileString(string key)
{
return null;
}
public virtual void OnGUI()
{
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 322ae10a4b62a437c901e1f23093ac3a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,177 @@
using System;
using System.IO;
using NUnit.Framework;
using UnityEditor.AddressableAssets.HostingServices;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.AddressableAssets.Settings.GroupSchemas;
using UnityEngine;
namespace UnityEditor.AddressableAssets.Tests.HostingServices
{
[TestFixtureSource("HostingServices")]
public class HostingServiceInterfaceTests
{
protected const string k_TestConfigName = "AddressableAssetSettings.HostingServiceInterfaceTests";
protected const string k_TestConfigFolder = "Assets/AddressableAssetsData_HostingServiceInterfaceTests";
// ReSharper disable once UnusedMember.Local
static IHostingService[] HostingServices
{
get
{
return new[]
{
new HttpHostingService() as IHostingService
};
}
}
readonly IHostingService m_Service;
public HostingServiceInterfaceTests(IHostingService svc)
{
m_Service = svc;
}
[OneTimeTearDown]
public void Cleanup()
{
if (Directory.Exists(k_TestConfigFolder))
AssetDatabase.DeleteAsset(k_TestConfigFolder);
EditorBuildSettings.RemoveConfigObject(k_TestConfigName);
}
IHostingService GetManagedService(out AddressableAssetSettings settings)
{
var m = new HostingServicesManager();
settings = AddressableAssetSettings.Create(k_TestConfigFolder, k_TestConfigName, false, false);
settings.HostingServicesManager = m;
var group = settings.CreateGroup("testGroup", false, false, false, null);
group.AddSchema<BundledAssetGroupSchema>();
settings.groups.Add(group);
m.Initialize(settings);
return m.AddHostingService(m_Service.GetType(), "test");
}
// HostingServiceContentRoots
[Test]
public void HostingServiceContentRootsShould_ReturnListOfContentRoots()
{
AddressableAssetSettings s;
var svc = GetManagedService(out s);
Assert.IsNotEmpty(s.groups);
Assert.IsNotEmpty(svc.HostingServiceContentRoots);
var schema = s.groups[0].GetSchema<BundledAssetGroupSchema>();
Assert.Contains(schema.HostingServicesContentRoot, svc.HostingServiceContentRoots);
}
// ProfileVariables
[Test]
public void ProfileVariablesShould_ReturnProfileVariableKeyValuePairs()
{
var vars = m_Service.ProfileVariables;
Assert.IsNotEmpty(vars);
}
// IsHostingServiceRunning, StartHostingService, and StopHostingService
[Test]
public void IsHostingServiceRunning_StartHostingService_StopHostingService()
{
AddressableAssetSettings s;
var svc = GetManagedService(out s);
Assert.IsFalse(svc.IsHostingServiceRunning);
svc.StartHostingService();
Assert.IsTrue(svc.IsHostingServiceRunning);
svc.StopHostingService();
Assert.IsFalse(svc.IsHostingServiceRunning);
}
// OnBeforeSerialize
[Test]
public void OnBeforeSerializeShould_PersistExpectedDataToKeyDataStore()
{
var data = new KeyDataStore();
m_Service.DescriptiveName = "Testing 123";
m_Service.InstanceId = 123;
m_Service.HostingServiceContentRoots.Clear();
m_Service.HostingServiceContentRoots.AddRange(new[] {"/test123", "/test456"});
m_Service.OnBeforeSerialize(data);
Assert.AreEqual("Testing 123", data.GetData("DescriptiveName", string.Empty));
Assert.AreEqual(123, data.GetData("InstanceId", 0));
Assert.AreEqual("/test123;/test456", data.GetData("ContentRoot", string.Empty));
}
// OnAfterDeserialize
[Test]
public void OnAfterDeserializeShould_RestoreExpectedDataFromKeyDataStore()
{
var data = new KeyDataStore();
data.SetData("DescriptiveName", "Testing 123");
data.SetData("InstanceId", 123);
data.SetData("ContentRoot", "/test123;/test456");
m_Service.OnAfterDeserialize(data);
Assert.AreEqual("Testing 123", m_Service.DescriptiveName);
Assert.AreEqual(123, m_Service.InstanceId);
Assert.Contains("/test123", m_Service.HostingServiceContentRoots);
Assert.Contains("/test456", m_Service.HostingServiceContentRoots);
}
// EvaluateProfileString
[Test]
public void EvaluateProfileStringShould_CorrectlyReplaceKeyValues()
{
var vars = m_Service.ProfileVariables;
vars.Add("foo", "bar");
var val = m_Service.EvaluateProfileString("foo");
Assert.AreEqual("bar", val);
}
[Test]
public void EvaluateProfileStringShould_ReturnNullForNonMatchingKey()
{
var val = m_Service.EvaluateProfileString("foo2");
Assert.IsNull(val);
}
// RegisterLogger
[Test]
public void LoggerShould_UseTheProvidedLogger()
{
var l = new Logger(Debug.unityLogger.logHandler);
m_Service.Logger = l;
Assert.AreEqual(l, m_Service.Logger);
}
[Test]
public void RegisterLoggerShould_UseTheDebugUnityLoggerWhenParamIsNull()
{
m_Service.Logger = null;
Assert.AreEqual(Debug.unityLogger, m_Service.Logger);
}
// DescriptiveName
[Test]
public void DescriptiveNameShould_AllowGetAndSetOfDescriptiveName()
{
m_Service.DescriptiveName = "test";
Assert.AreEqual("test", m_Service.DescriptiveName);
}
// InstanceId
[Test]
public void InstanceIdShould_AllowGetAndSetOfInstanceId()
{
m_Service.InstanceId = 999;
Assert.AreEqual(999, m_Service.InstanceId);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b599dbeafb09d4db69110c404ab9552f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,773 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using NUnit.Framework;
using UnityEditor.AddressableAssets.Build.DataBuilders;
using UnityEditor.AddressableAssets.HostingServices;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.AddressableAssets.Settings.GroupSchemas;
using UnityEngine;
using UnityEngine.TestTools;
namespace UnityEditor.AddressableAssets.Tests.HostingServices
{
public class HostingServicesManagerTests
{
const string k_TestConfigName = "AddressableAssetSettings.HostingServicesManagerTests";
const string k_TestConfigFolder = "Assets/AddressableAssetsData_HostingServicesManagerTests";
HostingServicesManager m_Manager;
AddressableAssetSettings m_Settings;
[OneTimeSetUp]
public void OneTimeSetUp()
{
// calling EditorSceneManager.NewScene from other tests will call HostingServicesManager.OnDisable and save the keys
HostingServicesManager.EraseSessionStateKeys();
}
[SetUp]
public void Setup()
{
m_Manager = new HostingServicesManager();
m_Settings = AddressableAssetSettings.Create(k_TestConfigFolder, k_TestConfigName, false, false);
m_Settings.HostingServicesManager = m_Manager;
var group = m_Settings.CreateGroup("testGroup", false, false, false, null);
group.AddSchema<BundledAssetGroupSchema>();
m_Settings.groups.Add(group);
}
[TearDown]
public void TearDown()
{
Assert.AreEqual(0, SessionState.GetInt(HostingServicesManager.k_GlobalProfileVariablesCountKey, 0));
var services = m_Manager.HostingServices.ToArray();
foreach (var svc in services)
{
m_Manager.RemoveHostingService(svc);
}
if (Directory.Exists(k_TestConfigFolder))
AssetDatabase.DeleteAsset(k_TestConfigFolder);
EditorBuildSettings.RemoveConfigObject(k_TestConfigName);
}
// GlobalProfileVariables
[Test]
public void GlobalProfileVariablesShould_ReturnDictionaryOfKeyValuePairs()
{
var vars = m_Manager.GlobalProfileVariables;
Assert.NotNull(vars);
}
[Test]
public void GlobalProfileVariablesShould_ContainPrivateIpAddressKey()
{
m_Manager.Initialize(m_Settings);
var vars = m_Manager.GlobalProfileVariables;
Assert.NotNull(vars);
const string key = HostingServicesManager.KPrivateIpAddressKey;
Assert.Contains(key, vars.Keys);
Assert.NotNull(vars[key]);
}
// IsInitialized
[Test]
public void IsInitializedShould_BecomeTrueAfterInitializeCall()
{
Assert.IsFalse(m_Manager.IsInitialized);
m_Manager.Initialize(m_Settings);
Assert.IsTrue(m_Manager.IsInitialized);
}
// HostingServices
[Test]
public void HostingServicesShould_ReturnListOfManagedServices()
{
m_Manager.Initialize(m_Settings);
Assert.NotNull(m_Manager.HostingServices);
Assert.IsEmpty(m_Manager.HostingServices);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.IsTrue(m_Manager.HostingServices.Contains(svc));
}
// RegisteredServiceTypes
[Test]
public void RegisteredServiceTypesShould_AlwaysContainBuiltinServiceTypes()
{
Assert.NotNull(m_Manager.RegisteredServiceTypes);
Assert.Contains(typeof(HttpHostingService), m_Manager.RegisteredServiceTypes);
}
[Test]
public void RegisteredServiceTypesShould_NotContainDuplicates()
{
m_Manager.Initialize(m_Settings);
m_Manager.AddHostingService(typeof(TestHostingService), "test1");
m_Manager.AddHostingService(typeof(TestHostingService), "test2");
Assert.IsTrue(m_Manager.RegisteredServiceTypes.Length == 1);
}
// NextInstanceId
[Test]
public void NextInstanceIdShould_IncrementAfterServiceIsAdded()
{
m_Manager.Initialize(m_Settings);
Assert.IsTrue(m_Manager.NextInstanceId == 0);
m_Manager.AddHostingService(typeof(TestHostingService), "test1");
Assert.IsTrue(m_Manager.NextInstanceId == 1);
}
// Initialize
[Test]
public void InitializeShould_AssignTheGivenSettingsObject()
{
Assert.Null(m_Manager.Settings);
m_Manager.Initialize(m_Settings);
Assert.IsTrue(m_Manager.IsInitialized);
Assert.NotNull(m_Manager.Settings);
Assert.AreSame(m_Manager.Settings, m_Settings);
}
[Test]
public void InitializeShould_SetGlobalProfileVariables()
{
Assert.IsTrue(m_Manager.GlobalProfileVariables.Count == 0);
m_Manager.Initialize(m_Settings);
Assert.IsTrue(m_Manager.IsInitialized);
Assert.IsTrue(m_Manager.GlobalProfileVariables.Count > 0);
}
[Test]
public void InitializeShould_OnlyInitializeOnce()
{
var so = ScriptableObject.CreateInstance<AddressableAssetSettings>();
m_Manager.Initialize(m_Settings);
Assert.IsTrue(m_Manager.IsInitialized);
m_Manager.Initialize(so);
Assert.AreSame(m_Manager.Settings, m_Settings);
Assert.AreNotSame(m_Manager.Settings, so);
}
// StopAllService
[Test]
public void StopAllServicesShould_StopAllRunningServices()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
svc.HostingServiceContentRoots.Add("/");
Assert.IsFalse(svc.IsHostingServiceRunning);
svc.StartHostingService();
Assert.IsTrue(svc.IsHostingServiceRunning);
m_Manager.StopAllServices();
Assert.IsFalse(svc.IsHostingServiceRunning);
}
// StartAllServices
[Test]
public void StartAllServicesShould_StartAllStoppedServices()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
svc.HostingServiceContentRoots.Add("/");
Assert.IsFalse(svc.IsHostingServiceRunning);
m_Manager.StartAllServices();
Assert.IsTrue(svc.IsHostingServiceRunning);
}
// AddHostingService
[Test]
public void AddHostingServiceShould_ThrowIfTypeDoesNotImplementInterface()
{
Assert.Throws<ArgumentException>(() => { m_Manager.AddHostingService(typeof(object), "test"); });
}
[Test]
public void AddHostingServiceShould_ThrowIfTypeIsAbstract()
{
Assert.Throws<MissingMethodException>(() => { m_Manager.AddHostingService(typeof(AbstractTestHostingService), "test"); });
}
[Test]
public void AddHostingServiceShould_AddTypeToRegisteredServiceTypes()
{
m_Manager.Initialize(m_Settings);
Assert.NotNull(m_Manager.RegisteredServiceTypes);
m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.Contains(typeof(TestHostingService), m_Manager.RegisteredServiceTypes);
}
[Test]
public void AddHostingServiceShould_RegisterLoggerForService()
{
m_Manager.Initialize(m_Settings);
m_Manager.AddHostingService(typeof(TestHostingService), "test");
}
[Test]
public void AddHostingServiceShould_SetDescriptiveNameOnService()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.AreEqual(svc.DescriptiveName, "test");
}
[Test]
public void AddHostingServiceShould_SetNextInstanceIdOnService()
{
m_Manager.Initialize(m_Settings);
m_Manager.AddHostingService(typeof(TestHostingService), "test");
m_Manager.AddHostingService(typeof(TestHostingService), "test");
var id = m_Manager.NextInstanceId;
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.AreEqual(id, svc.InstanceId);
}
[Test]
public void AddHostingServiceShould_SetContentRootsOnService()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.IsNotEmpty(svc.HostingServiceContentRoots);
}
[Test]
public void AddHostingServiceShould_PostModificationEventToSettings()
{
var wait = new ManualResetEvent(false);
m_Settings.OnModification = null;
m_Settings.OnModification += (s, evt, obj) =>
{
if (evt == AddressableAssetSettings.ModificationEvent.HostingServicesManagerModified)
wait.Set();
};
m_Manager.Initialize(m_Settings);
m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.IsTrue(wait.WaitOne(100));
}
[Test]
public void AddHostingServiceShould_ReturnServiceInstance()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.NotNull(svc);
}
[Test]
public void AddHostingServiceShould_RegisterStringEvalFuncs()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.IsTrue(ProfileStringEvalDelegateIsRegistered(m_Settings, svc));
}
// RemoveHostingService
[Test]
public void RemoveHostingServiceShould_StopRunningService()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.IsFalse(svc.IsHostingServiceRunning);
svc.StartHostingService();
Assert.IsTrue(svc.IsHostingServiceRunning);
m_Manager.RemoveHostingService(svc);
Assert.IsFalse(svc.IsHostingServiceRunning);
}
[Test]
public void RemoveHostingServiceShould_UnregisterStringEvalFuncs()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.IsTrue(ProfileStringEvalDelegateIsRegistered(m_Settings, svc));
m_Manager.RemoveHostingService(svc);
Assert.IsFalse(ProfileStringEvalDelegateIsRegistered(m_Settings, svc));
}
[Test]
public void RemoveHostingServiceShould_PostModificationEventToSettings()
{
var wait = new ManualResetEvent(false);
m_Settings.OnModification = null;
m_Settings.OnModification += (s, evt, obj) =>
{
if (evt == AddressableAssetSettings.ModificationEvent.HostingServicesManagerModified)
wait.Set();
};
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
m_Manager.RemoveHostingService(svc);
Assert.IsTrue(wait.WaitOne(100));
}
[Test]
public void OnAwakeShould_RefreshGlobalProfileVariables()
{
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Clear();
m_Manager.OnAwake();
Assert.GreaterOrEqual(m_Manager.GlobalProfileVariables.Count, 1);
}
// OnEnable
[Test]
public void OnEnableShould_RegisterForSettingsModificationEvents()
{
var len = m_Settings.OnModification.GetInvocationList().Length;
m_Manager.Initialize(m_Settings);
m_Manager.OnEnable();
Assert.Greater(m_Settings.OnModification.GetInvocationList().Length, len);
}
[Test]
public void OnEnableShould_RegisterProfileStringEvalFuncsForServices()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
m_Settings.profileSettings.onProfileStringEvaluation = null;
m_Manager.OnEnable();
Assert.IsTrue(ProfileStringEvalDelegateIsRegistered(m_Settings, svc));
}
[Test]
public void OnEnableShould_RegisterLoggerWithServices()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test") as TestHostingService;
Assert.NotNull(svc);
svc.Logger = null;
Assert.Null(svc.Logger);
m_Manager.OnEnable();
Assert.NotNull(svc.Logger);
}
[Test]
public void OnEnableShould_RegisterProfileStringEvalFuncForManager()
{
m_Manager.Initialize(m_Settings);
m_Manager.OnEnable();
Assert.IsTrue(ProfileStringEvalDelegateIsRegistered(m_Settings, m_Manager));
}
[Test]
public void OnEnableShould_LoadSessionStateKeys()
{
string ipAddressKey = m_Manager.GetPrivateIpAddressKey();
string ipAddressVal = "123.1.2.3";
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Clear();
m_Manager.GlobalProfileVariables.Add(ipAddressKey, ipAddressVal);
m_Manager.SaveSessionStateKeys();
m_Manager.GlobalProfileVariables.Clear();
m_Manager.OnEnable();
Assert.AreEqual(1, m_Manager.GlobalProfileVariables.Count);
Assert.IsTrue(m_Manager.GlobalProfileVariables.ContainsKey(ipAddressKey));
Assert.AreEqual(ipAddressVal, m_Manager.GlobalProfileVariables[ipAddressKey]);
HostingServicesManager.EraseSessionStateKeys();
}
// OnDisable
[Test]
public void OnDisableShould_DeRegisterForSettingsModificationEvents()
{
var len = m_Settings.OnModification.GetInvocationList().Length;
m_Manager.Initialize(m_Settings);
m_Manager.OnEnable();
m_Manager.OnEnable();
m_Manager.OnEnable();
Assert.Greater(m_Settings.OnModification.GetInvocationList().Length, len);
m_Manager.OnDisable();
Assert.AreEqual(len, m_Settings.OnModification.GetInvocationList().Length);
HostingServicesManager.EraseSessionStateKeys();
}
[Test]
public void OnEnableShould_UnregisterProfileStringEvalFuncForManager()
{
m_Manager.Initialize(m_Settings);
m_Manager.OnEnable();
Assert.IsTrue(ProfileStringEvalDelegateIsRegistered(m_Settings, m_Manager));
m_Manager.OnDisable();
Assert.IsFalse(ProfileStringEvalDelegateIsRegistered(m_Settings, m_Manager));
HostingServicesManager.EraseSessionStateKeys();
}
[Test]
public void OnDisableShould_RegisterNullLoggerForServices()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test") as TestHostingService;
Assert.IsNotNull(svc);
m_Manager.Initialize(m_Settings);
m_Manager.OnEnable();
Assert.IsNotNull(svc.Logger);
m_Manager.OnDisable();
Assert.IsNull(svc.Logger);
HostingServicesManager.EraseSessionStateKeys();
}
[Test]
public void OnDisableShould_DeRegisterProfileStringEvalFuncsForServices()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test") as TestHostingService;
Assert.IsNotNull(svc);
m_Manager.Initialize(m_Settings);
m_Manager.OnEnable();
Assert.IsTrue(ProfileStringEvalDelegateIsRegistered(m_Settings, svc));
m_Manager.OnDisable();
Assert.IsFalse(ProfileStringEvalDelegateIsRegistered(m_Settings, svc));
HostingServicesManager.EraseSessionStateKeys();
}
[Test]
public void OnDisableShould_StopAllServices()
{
m_Manager.Initialize(m_Settings);
for (int i = 0; i < 3; i++)
{
var svc = m_Manager.AddHostingService(typeof(HttpHostingService), $"test_{i}") as HttpHostingService;
Assert.IsNotNull(svc);
svc.StartHostingService();
Assert.IsTrue(svc.IsHostingServiceRunning);
}
m_Manager.OnDisable();
foreach (var svc in m_Manager.HostingServices)
Assert.IsFalse(svc.IsHostingServiceRunning);
HostingServicesManager.EraseSessionStateKeys();
}
[Test]
public void OnEnableShould_RestoreServicesThatWherePreviouslyEnabled()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(HttpHostingService), "test") as HttpHostingService;
Assert.IsNotNull(svc);
svc.WasEnabled = true;
Assert.IsFalse(svc.IsHostingServiceRunning);
m_Manager.OnEnable();
Assert.IsTrue(svc.IsHostingServiceRunning);
}
[Test]
public void OnDomainReload_HttpServicePortShouldntChange()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(HttpHostingService), "test") as HttpHostingService;
Assert.IsNotNull(svc);
svc.WasEnabled = true;
m_Manager.OnEnable();
var expectedPort = svc.HostingServicePort;
Assert.IsTrue(svc.IsHostingServiceRunning);
for (int i = 1; i <= 5; i++)
{
m_Manager.OnDisable();
Assert.IsFalse(svc.IsHostingServiceRunning, $"Service '{svc.DescriptiveName}' was still running after manager.OnDisable() (iteration {i}");
m_Manager.OnEnable();
Assert.IsTrue(svc.IsHostingServiceRunning, $"Service '{svc.DescriptiveName}' not running after manager.OnEnable() (iteration {i}");
}
Assert.AreEqual(expectedPort, svc.HostingServicePort);
HostingServicesManager.EraseSessionStateKeys();
}
[Test]
public void OnDisableShould_SaveSessionStateKeys()
{
string ipAddressKey = m_Manager.GetPrivateIpAddressKey(0);
string ipAddressVal = "123.1.2.3";
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Clear();
m_Manager.GlobalProfileVariables.Add(ipAddressKey, ipAddressVal);
m_Manager.OnDisable();
m_Manager.GlobalProfileVariables.Clear();
m_Manager.LoadSessionStateKeysIfExists();
Assert.AreEqual(1, m_Manager.GlobalProfileVariables.Count);
Assert.IsTrue(m_Manager.GlobalProfileVariables.ContainsKey(ipAddressKey));
Assert.AreEqual(ipAddressVal, m_Manager.GlobalProfileVariables[ipAddressKey]);
HostingServicesManager.EraseSessionStateKeys();
}
// RegisterLogger
[Test]
public void LoggerShould_SetLoggerForManagerAndManagedServices()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test") as TestHostingService;
Assert.IsNotNull(svc);
m_Manager.Initialize(m_Settings);
var logger = new Logger(Debug.unityLogger.logHandler);
Assert.AreNotEqual(logger, svc.Logger);
Assert.AreNotEqual(logger, m_Manager.Logger);
m_Manager.Logger = logger;
Assert.AreEqual(logger, svc.Logger);
Assert.AreEqual(logger, m_Manager.Logger);
}
[Test]
public void LoggerShould_SetDebugUnityLoggerIfNull()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test") as TestHostingService;
Assert.IsNotNull(svc);
m_Manager.Initialize(m_Settings);
var logger = new Logger(Debug.unityLogger.logHandler);
m_Manager.Logger = logger;
Assert.AreNotEqual(Debug.unityLogger, svc.Logger);
Assert.AreNotEqual(Debug.unityLogger, m_Manager.Logger);
m_Manager.Logger = null;
Assert.AreEqual(Debug.unityLogger, svc.Logger);
Assert.AreEqual(Debug.unityLogger, m_Manager.Logger);
}
// RefreshGLobalProfileVariables
[Test]
public void RefreshGlobalProfileVariablesShould_AddOrUpdatePrivateIpAddressVar()
{
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Clear();
Assert.IsEmpty(m_Manager.GlobalProfileVariables);
m_Manager.RefreshGlobalProfileVariables();
Assert.IsNotEmpty(m_Manager.GlobalProfileVariables);
}
[Test]
public void RefreshGlobalProfileVariablesShould_RemoveUnknownVars()
{
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Add("test", "test");
Assert.IsTrue(m_Manager.GlobalProfileVariables.ContainsKey("test"));
m_Manager.RefreshGlobalProfileVariables();
Assert.IsFalse(m_Manager.GlobalProfileVariables.ContainsKey("test"));
}
[Test]
public void RefreshGlobalProfileVariables_WithValidPingTimeout_DoesNotLogError()
{
int pingTimeoutInMilliseconds = m_Manager.PingTimeoutInMilliseconds;
try
{
m_Manager.Initialize(m_Settings);
m_Manager.PingTimeoutInMilliseconds = 5500;
m_Manager.RefreshGlobalProfileVariables();
LogAssert.NoUnexpectedReceived();
}
finally
{
m_Manager.PingTimeoutInMilliseconds = pingTimeoutInMilliseconds;
}
}
[Test]
public void RefreshGlobalProfileVariables_WithInvalidPingTimeout_LogsError()
{
int pingTimeoutInMilliseconds = m_Manager.PingTimeoutInMilliseconds;
try
{
m_Manager.Initialize(m_Settings);
m_Manager.PingTimeoutInMilliseconds = -1;
m_Manager.RefreshGlobalProfileVariables();
LogAssert.Expect(LogType.Error, "Cannot filter IP addresses. Timeout must be a non-negative integer.");
}
finally
{
m_Manager.PingTimeoutInMilliseconds = pingTimeoutInMilliseconds;
}
}
// BatchMode
[Test]
public void BatchModeShould_InitializeManagerWithDefaultSettings()
{
Assert.IsFalse(m_Manager.IsInitialized);
HostingServicesManager.BatchMode(m_Settings);
Assert.IsTrue(m_Manager.IsInitialized);
}
[Test]
public void BatchModeShould_StartAllServices()
{
m_Manager.Initialize(m_Settings);
var svc = m_Manager.AddHostingService(typeof(TestHostingService), "test");
Assert.IsFalse(svc.IsHostingServiceRunning);
HostingServicesManager.BatchMode(m_Settings);
Assert.IsTrue(svc.IsHostingServiceRunning);
}
static bool ProfileStringEvalDelegateIsRegistered(AddressableAssetSettings s, IHostingService svc)
{
var del = new AddressableAssetProfileSettings.ProfileStringEvaluationDelegate(svc.EvaluateProfileString);
var list = s.profileSettings.onProfileStringEvaluation.GetInvocationList();
return list.Contains(del);
}
static bool ProfileStringEvalDelegateIsRegistered(AddressableAssetSettings s, HostingServicesManager m)
{
var del = new AddressableAssetProfileSettings.ProfileStringEvaluationDelegate(m.EvaluateGlobalProfileVariableKey);
var list = s.profileSettings.onProfileStringEvaluation.GetInvocationList();
return list.Contains(del);
}
static SerializedData Serialize(HostingServicesManager m)
{
FieldInfo infosField = typeof(HostingServicesManager).GetField("m_HostingServiceInfos", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(infosField);
FieldInfo typeRefField = typeof(HostingServicesManager).GetField("m_RegisteredServiceTypeRefs", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(typeRefField);
return new SerializedData()
{
Infos = (List<HostingServicesManager.HostingServiceInfo>)infosField.GetValue(m),
TypeRefs = (List<string>)typeRefField.GetValue(m)
};
}
static void Deserialize(HostingServicesManager m, SerializedData data)
{
FieldInfo infosField = typeof(HostingServicesManager).GetField("m_HostingServiceInfos", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(infosField);
FieldInfo typeRefField = typeof(HostingServicesManager).GetField("m_RegisteredServiceTypeRefs", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(typeRefField);
infosField.SetValue(m, data.Infos);
typeRefField.SetValue(m, data.TypeRefs);
}
class SerializedData
{
public List<HostingServicesManager.HostingServiceInfo> Infos;
public List<string> TypeRefs;
}
[Test]
public void CanSaveAndLoadSessionStateKeys()
{
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Clear();
var customIps = new Dictionary<string, string>()
{
{m_Manager.GetPrivateIpAddressKey(0), "111.1.1.1"},
{m_Manager.GetPrivateIpAddressKey(1), "222.2.2.2"},
{m_Manager.GetPrivateIpAddressKey(2), "333.3.3.3"},
};
foreach (KeyValuePair<string, string> pair in customIps)
{
m_Manager.GlobalProfileVariables.Add(pair.Key, pair.Value);
}
m_Manager.SaveSessionStateKeys();
m_Manager.GlobalProfileVariables.Clear();
m_Manager.LoadSessionStateKeysIfExists();
Assert.AreEqual(customIps.Count, m_Manager.GlobalProfileVariables.Count);
foreach (KeyValuePair<string, string> pair in customIps)
{
Assert.IsTrue(m_Manager.GlobalProfileVariables.ContainsKey(pair.Key));
Assert.AreEqual(pair.Value, m_Manager.GlobalProfileVariables[pair.Key]);
}
HostingServicesManager.EraseSessionStateKeys();
}
[Test]
public void LoadSessionStateKeys_ExcludesMissingKeys()
{
string ipAddressKey = m_Manager.GetPrivateIpAddressKey(1);
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Clear();
m_Manager.GlobalProfileVariables.Add(m_Manager.GetPrivateIpAddressKey(0), "111.1.1.1");
m_Manager.GlobalProfileVariables.Add(ipAddressKey, "222.2.2.2");
m_Manager.GlobalProfileVariables.Add(m_Manager.GetPrivateIpAddressKey(2), "333.3.3.3");
m_Manager.SaveSessionStateKeys();
m_Manager.GlobalProfileVariables.Clear();
SessionState.EraseString(HostingServicesManager.GetSessionStateKey(1));
m_Manager.LoadSessionStateKeysIfExists();
Assert.AreEqual(2, m_Manager.GlobalProfileVariables.Count);
Assert.IsFalse(m_Manager.GlobalProfileVariables.ContainsKey(ipAddressKey));
HostingServicesManager.EraseSessionStateKeys();
}
[Test]
public void CanEraseSessionStateKeys()
{
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Clear();
m_Manager.GlobalProfileVariables.Add(m_Manager.GetPrivateIpAddressKey(0), "111.1.1.1");
m_Manager.GlobalProfileVariables.Add(m_Manager.GetPrivateIpAddressKey(1), "222.2.2.2");
m_Manager.GlobalProfileVariables.Add(m_Manager.GetPrivateIpAddressKey(2), "333.3.3.3");
m_Manager.SaveSessionStateKeys();
HostingServicesManager.EraseSessionStateKeys();
Assert.AreEqual(string.Empty, SessionState.GetString(HostingServicesManager.GetSessionStateKey(0), string.Empty));
Assert.AreEqual(string.Empty, SessionState.GetString(HostingServicesManager.GetSessionStateKey(1), string.Empty));
Assert.AreEqual(string.Empty, SessionState.GetString(HostingServicesManager.GetSessionStateKey(2), string.Empty));
}
[Test]
public void SaveSessionStateKeys_ErasesOldSessionStateKeys()
{
string ipAddressKey = m_Manager.GetPrivateIpAddressKey(0);
string ipAddressVal = "444.4.4.4";
m_Manager.Initialize(m_Settings);
m_Manager.GlobalProfileVariables.Clear();
m_Manager.GlobalProfileVariables.Add(ipAddressKey, "111.1.1.1");
m_Manager.GlobalProfileVariables.Add(m_Manager.GetPrivateIpAddressKey(1), "222.2.2.2");
m_Manager.GlobalProfileVariables.Add(m_Manager.GetPrivateIpAddressKey(2), "333.3.3.3");
m_Manager.SaveSessionStateKeys();
m_Manager.GlobalProfileVariables.Clear();
m_Manager.GlobalProfileVariables.Add(ipAddressKey, ipAddressVal);
m_Manager.SaveSessionStateKeys();
Assert.AreEqual(ipAddressVal, SessionState.GetString(HostingServicesManager.GetSessionStateKey(0), string.Empty));
Assert.AreEqual(string.Empty, SessionState.GetString(HostingServicesManager.GetSessionStateKey(1), string.Empty));
Assert.AreEqual(string.Empty, SessionState.GetString(HostingServicesManager.GetSessionStateKey(2), string.Empty));
HostingServicesManager.EraseSessionStateKeys();
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f8b45d496263c4f4da1cdd5c22c51cc8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,99 @@
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEditor.AddressableAssets.GUI;
namespace UnityEditor.AddressableAssets.Tests.HostingServices
{
public class HostingServicesWindowUtilitiesTests
{
[Test]
public void DictsAreEqual_ReturnsTrueOnSameValueSameRef()
{
var originalDict = new Dictionary<string, string>();
originalDict.Add("a", "1");
originalDict.Add("b", "2");
originalDict.Add("c", "3");
var copyDict = originalDict;
Assert.IsTrue(HostingServicesWindow.DictsAreEqual(originalDict, copyDict), "Copy of dictionary should be equal to original, but isn't.");
}
[Test]
public void DictsAreEqual_ReturnsTrueOnSameValuesDifRef()
{
var dict1 = new Dictionary<string, string>();
dict1.Add("a", "1");
dict1.Add("b", "2");
dict1.Add("c", "3");
var dict2 = new Dictionary<string, string>();
dict2.Add("a", "1");
dict2.Add("b", "2");
dict2.Add("c", "3");
Assert.IsTrue(HostingServicesWindow.DictsAreEqual(dict1, dict2), "Two identically created dictionaries should be equal, but aren't.");
}
[Test]
public void DictsAreEqual_ReturnsFalseOnSameKeyDifVal()
{
var dict1 = new Dictionary<string, string>();
dict1.Add("a", "x");
dict1.Add("b", "y");
dict1.Add("c", "z");
var dict2 = new Dictionary<string, string>();
dict2.Add("a", "1");
dict2.Add("b", "2");
dict2.Add("c", "3");
Assert.IsFalse(HostingServicesWindow.DictsAreEqual(dict1, dict2), "Same keys with different values should not be considered equal.");
}
[Test]
public void DictsAreEqual_ReturnsFalseOnSameValDifKey()
{
var dict1 = new Dictionary<string, string>();
dict1.Add("x", "1");
dict1.Add("y", "2");
dict1.Add("z", "3");
var dict2 = new Dictionary<string, string>();
dict2.Add("a", "1");
dict2.Add("b", "2");
dict2.Add("c", "3");
Assert.IsFalse(HostingServicesWindow.DictsAreEqual(dict1, dict2), "Same values with different keys should not be considered equal.");
}
[Test]
public void DictsAreEqual_ReturnsFalseOnSubset()
{
var dict1 = new Dictionary<string, string>();
dict1.Add("a", "1");
dict1.Add("b", "2");
var dict2 = new Dictionary<string, string>();
dict2.Add("a", "1");
dict2.Add("b", "2");
dict2.Add("c", "3");
Assert.IsFalse(HostingServicesWindow.DictsAreEqual(dict1, dict2), "Subset should not be considered equal (smaller first case)");
Assert.IsFalse(HostingServicesWindow.DictsAreEqual(dict2, dict1), "Subset should not be considered equal (larger first case)");
}
[Test]
public void DictsAreEqual_ReturnsFalseOnTriviallyUnequal()
{
var dict1 = new Dictionary<string, string>();
dict1.Add("a", "1");
var dict2 = new Dictionary<string, string>();
dict2.Add("b", "2");
Assert.IsFalse(HostingServicesWindow.DictsAreEqual(dict1, dict2), "Should return false on trivially false case");
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c63ec1e574af01940b50bc1959310719
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,387 @@
using System;
using System.IO;
using System.Net;
using NUnit.Framework;
using UnityEditor.AddressableAssets.HostingServices;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;
using UnityEngine.TestTools;
namespace UnityEditor.AddressableAssets.Tests.HostingServices
{
using Random = System.Random;
public class HttpHostingServiceTests
{
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri uri)
{
var w = base.GetWebRequest(uri);
Debug.Assert(w != null);
w.Timeout = 2000;
return w;
}
}
HttpHostingService m_Service;
string m_ContentRoot;
readonly WebClient m_Client;
public HttpHostingServiceTests()
{
m_Client = new MyWebClient();
}
static byte[] GetRandomBytes(int size)
{
var rand = new Random();
var buf = new byte[size];
rand.NextBytes(buf);
return buf;
}
[OneTimeSetUp]
public void SetUp()
{
m_Service = new HttpHostingService();
var dirName = Path.GetRandomFileName();
m_ContentRoot = Path.Combine(Path.GetTempPath(), dirName);
Assert.IsNotEmpty(m_ContentRoot);
Directory.CreateDirectory(m_ContentRoot);
m_Service.HostingServiceContentRoots.Add(m_ContentRoot);
}
[TearDown]
public void Cleanup()
{
m_Service.StopHostingService();
}
[OneTimeTearDown]
public void TearDown()
{
if (!string.IsNullOrEmpty(m_ContentRoot) && Directory.Exists(m_ContentRoot))
Directory.Delete(m_ContentRoot, true);
}
[TestCase("subdir", "subdir1")] //"subdir3")]
[TestCase("subdír☠", "subdirãúñ", TestName = "ShouldServeFilesWSpecialCharacters")] //"subdirü",
public void ShouldServeRequestedFiles(string subdir1, string subdir2) // string subdir3)
{
var fileNames = new[]
{
Path.GetRandomFileName(),
Path.Combine(subdir1, Path.GetRandomFileName()),
Path.Combine(subdir2, Path.GetRandomFileName())
};
foreach (var fileName in fileNames)
{
var filePath = Path.Combine(m_ContentRoot, fileName);
var bytes = GetRandomBytes(1024);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.WriteAllBytes(filePath, bytes);
m_Service.StartHostingService();
Assert.IsTrue(m_Service.IsHostingServiceRunning);
var url = string.Format("http://127.0.0.1:{0}/{1}", m_Service.HostingServicePort, fileName);
try
{
var data = m_Client.DownloadData(url);
Assert.AreEqual(data.Length, bytes.Length);
for (var i = 0; i < data.Length; i++)
if (bytes[i] != data[i])
Assert.Fail("Data does not match {0} != {1}", bytes[i], data[i]);
}
catch (Exception e)
{
Assert.Fail(e.Message);
}
}
}
private class MockHttpContext : HttpHostingService.IHttpContext
{
public Uri Url { get; set; }
public string ContentType { get; set; }
public long ContentLength { get; set; }
public Stream OutputStream { get; set; }
public Uri GetRequestUrl()
{
return Url;
}
public void SetResponseContentType(string contentType)
{
ContentType = contentType;
}
public void SetResponseContentLength(long contentLength)
{
ContentLength = contentLength;
}
public Stream GetResponseOutputStream()
{
return OutputStream;
}
}
[Test]
public void FileUploadOperationSplitsDownload()
{
string subdir1 = "subdir";
string subdir2 = "subdir1"; // Remove comment when Mono limit Fixed
string subdir3 = "subdir3";
var fileNames = new[]
{
Path.GetRandomFileName(),
Path.Combine(subdir1, Path.GetRandomFileName()),
Path.Combine(subdir2, Path.Combine(subdir3, Path.GetRandomFileName())),
Path.Combine(subdir3, Path.GetRandomFileName()),
};
foreach (var fileName in fileNames)
{
var filePath = Path.Combine(m_ContentRoot, fileName);
var bytes = GetRandomBytes(1024);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.WriteAllBytes(filePath, bytes);
// we execute every 250ms so you can divide upload speed by 4
// to see how much each update will process
var uploadSpeed = 2048;
var cleanupCalled = false;
Action cleanup = () => { cleanupCalled = true; };
var context = new MockHttpContext();
using (MemoryStream outputStream = new MemoryStream(1024))
{
context.OutputStream = outputStream;
context.Url = new Uri("http://127.0.0.1:55555");
var op = new HttpHostingService.FileUploadOperation(context, filePath, uploadSpeed, cleanup);
op.Update(null);
Assert.AreEqual(512, context.OutputStream.Length);
op.Update(null);
}
Assert.AreEqual(1024, context.ContentLength);
Assert.AreEqual("application/octet-stream", context.ContentType);
Assert.IsTrue(cleanupCalled);
}
}
[Test]
public void FileUploadOperationCallsCleanupOnError()
{
string subdir1 = "subdir";
var fileName = Path.Combine(subdir1, Path.GetRandomFileName());
var filePath = Path.Combine(m_ContentRoot, fileName);
// we intentionally do not initialize a test file
var uploadSpeed = 2048;
var exceptionThrown = false;
var cleanupCalled = false;
Action cleanup = () => { cleanupCalled = true; };
var context = new MockHttpContext();
try
{
var _ = new HttpHostingService.FileUploadOperation(context, filePath, uploadSpeed, cleanup);
}
catch (Exception e)
{
exceptionThrown = true;
}
LogAssert.Expect(LogType.Exception, $"DirectoryNotFoundException: Could not find a part of the path \"{filePath}\".");
Assert.IsTrue(cleanupCalled);
Assert.IsTrue(exceptionThrown);
}
[Test]
public void FileUploadOperationHandlesError()
{
var fileName = Path.GetRandomFileName();
var filePath = Path.Combine(m_ContentRoot, fileName);
var bytes = GetRandomBytes(1024);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.WriteAllBytes(filePath, bytes);
// we execute every 250ms so you can divide upload speed by 4
// to see how much each update will process
var uploadSpeed = 2048;
var cleanupCalled = false;
var exceptionCaught = false;
Action cleanup = () => { cleanupCalled = true; };
var context = new MockHttpContext();
using (MemoryStream outputStream = new MemoryStream(1024))
{
try
{
context.OutputStream = outputStream;
// close the output stream to trigger an exception on writes
outputStream.Close();
context.Url = new Uri("http://127.0.0.1:55555");
var op = new HttpHostingService.FileUploadOperation(context, filePath, uploadSpeed, cleanup);
op.Update(null);
}
catch (Exception e)
{
exceptionCaught = true;
}
}
Assert.IsTrue(cleanupCalled);
Assert.IsTrue(exceptionCaught);
}
[Test]
public void HttpServiceCompletesWithUploadSpeedWhenExpected()
{
string subdir1 = "subdir";
string subdir2 = "subdir1";
string subdir3 = "subdir3";
var fileNames = new[]
{
Path.GetRandomFileName(),
Path.Combine(subdir1, Path.GetRandomFileName()),
Path.Combine(subdir2, Path.Combine(subdir3, Path.GetRandomFileName())),
Path.Combine(subdir3, Path.GetRandomFileName()),
};
m_Service.StartHostingService();
try
{
foreach (var fileName in fileNames)
{
var filePath = Path.Combine(m_ContentRoot, fileName);
var bytes = GetRandomBytes(1024);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
File.WriteAllBytes(filePath, bytes);
m_Service.UploadSpeed = 2048;
Assert.IsTrue(m_Service.IsHostingServiceRunning);
var url = string.Format("http://127.0.0.1:{0}/{1}", m_Service.HostingServicePort, fileName);
try
{
var downloadedBytes = m_Client.DownloadData(new Uri(url));
Assert.AreEqual(1024, downloadedBytes.Length);
}
catch (Exception e)
{
Assert.Fail(e.Message);
}
}
}
finally
{
m_Service.StopHostingService();
}
}
[Test]
public void ShouldRespondWithStatus404IfFileDoesNotExist()
{
m_Service.StartHostingService();
Assert.IsTrue(m_Service.IsHostingServiceRunning);
var url = string.Format("http://127.0.0.1:{0}/{1}", m_Service.HostingServicePort, "foo");
try
{
m_Client.DownloadData(url);
}
catch (WebException e)
{
var response = (HttpWebResponse)e.Response;
Assert.AreEqual(response.StatusCode, HttpStatusCode.NotFound);
}
catch (Exception)
{
Assert.Fail();
}
}
// StartHostingService
[Test]
public void StartHostingServiceShould_AssignPortIfUnassigned()
{
m_Service.StartHostingService();
Assert.Greater(m_Service.HostingServicePort, 0);
}
// OnBeforeSerialize
[Test]
public void OnBeforeSerializeShould_PersistExpectedDataToKeyDataStore()
{
m_Service.StartHostingService();
var port = m_Service.HostingServicePort;
var data = new KeyDataStore();
m_Service.OnBeforeSerialize(data);
Assert.AreEqual(port, data.GetData("HostingServicePort", 0));
}
[Test]
public void OnBeforeSerializeShould_WasEnableCorrectToKeyDataStore()
{
m_Service.StartHostingService();
var data = new KeyDataStore();
m_Service.OnDisable();
m_Service.OnBeforeSerialize(data);
Assert.IsTrue(data.GetData("IsEnabled", false), "Hosting server was started before shutting down. IsEnabled expected to be true");
}
// OnAfterDeserialize
[Test]
public void OnAfterDeserializeShould_RestoreExpectedDataFromKeyDataStore()
{
var data = new KeyDataStore();
data.SetData("HostingServicePort", 1234);
m_Service.OnAfterDeserialize(data);
Assert.AreEqual(1234, m_Service.HostingServicePort);
}
// ResetListenPort
[Test]
public void ResetListenPortShould_AssignTheGivenPort()
{
m_Service.ResetListenPort(1234);
Assert.AreEqual(1234, m_Service.HostingServicePort);
}
[Test]
public void ResetListenPortShould_AssignRandomPortIfZero()
{
var oldPort = m_Service.HostingServicePort;
m_Service.ResetListenPort();
m_Service.StartHostingService();
Assert.Greater(m_Service.HostingServicePort, 0);
Assert.AreNotEqual(m_Service.HostingServicePort, oldPort);
}
[Test]
public void ResetListenPortShouldNot_StartServiceIfItIsNotRunning()
{
m_Service.StopHostingService();
m_Service.ResetListenPort();
Assert.IsFalse(m_Service.IsHostingServiceRunning);
}
[Test]
public void ResetListenPortShould_RestartServiceIfRunning()
{
m_Service.StartHostingService();
m_Service.ResetListenPort();
Assert.IsTrue(m_Service.IsHostingServiceRunning);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c03bc07c7a3d844849931ab6ebeb4adf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using UnityEditor.AddressableAssets.HostingServices;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;
namespace UnityEditor.AddressableAssets.Tests.HostingServices
{
class TestHostingService : AbstractTestHostingService
{
public TestHostingService()
{
HostingServiceContentRoots = new List<string>();
ProfileVariables = new Dictionary<string, string>();
}
public override void StartHostingService()
{
IsHostingServiceRunning = true;
}
public override void StopHostingService()
{
IsHostingServiceRunning = false;
}
public override void OnBeforeSerialize(KeyDataStore dataStore)
{
dataStore.SetData(BaseHostingService.k_InstanceIdKey, InstanceId);
}
public override void OnAfterDeserialize(KeyDataStore dataStore)
{
InstanceId = dataStore.GetData(BaseHostingService.k_InstanceIdKey, -1);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4adbd11117ba14195be497c6ee4bbe8f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: