Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix to do dispatch agent if mapped scene is not active when launching autopilot #77

Merged
merged 4 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions Runtime/AgentDispatcher.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// Copyright (c) 2023 DeNA Co., Ltd.
// Copyright (c) 2023-2024 DeNA Co., Ltd.
// This software is released under the MIT License.

using System;
using Cysharp.Threading.Tasks;
using DeNA.Anjin.Agents;
using DeNA.Anjin.Settings;
using DeNA.Anjin.Utilities;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;

Expand All @@ -20,7 +20,9 @@ public interface IAgentDispatcher : IDisposable
/// Agent dispatch by current scene
/// </summary>
/// <param name="scene">Current scene</param>
void DispatchByScene(Scene scene);
/// <param name="fallback">Use fallback agent if true</param>
/// <returns>True: Agent dispatched</returns>
bool DispatchByScene(Scene scene, bool fallback = true);
}

/// <inheritdoc/>
Expand Down Expand Up @@ -55,7 +57,7 @@ private void DispatchByScene(Scene next, LoadSceneMode mode)
}

/// <inheritdoc/>
public void DispatchByScene(Scene scene)
public bool DispatchByScene(Scene scene, bool fallback = true)
{
AbstractAgent agent = null;

Expand All @@ -70,7 +72,7 @@ public void DispatchByScene(Scene scene)

if (!agent)
{
if (_settings.fallbackAgent)
if (_settings.fallbackAgent && fallback)
{
_logger.Log($"Use fallback agent. scene: {scene.path}");
agent = _settings.fallbackAgent;
Expand All @@ -92,6 +94,8 @@ public void DispatchByScene(Scene scene)
// Note: The ObserverAgent is not made to DontDestroyOnLoad, to start every time.
// Because it is a source of bugs to force the implementation of DontDestroyOnLoad to the descendants of the Composite.
}

return agent != null; // Returns Agent dispatched or not.
}

private void DispatchAgent(AbstractAgent agent)
Expand Down
28 changes: 24 additions & 4 deletions Runtime/Autopilot.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) 2023 DeNA Co., Ltd.
// Copyright (c) 2023-2024 DeNA Co., Ltd.
// This software is released under the MIT License.

using System;
Expand All @@ -12,6 +12,10 @@
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.SceneManagement;
using AssertionException = NUnit.Framework.AssertionException;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace DeNA.Anjin
{
Expand Down Expand Up @@ -54,7 +58,11 @@ private void Start()
_logMessageHandler = new LogMessageHandler(_settings, _settings.reporter);

_dispatcher = new AgentDispatcher(_settings, _logger, _randomFactory);
_dispatcher.DispatchByScene(SceneManager.GetActiveScene());
var dispatched = _dispatcher.DispatchByScene(SceneManager.GetActiveScene(), false);
if (!dispatched)
{
DispatchByLoadedScenes(); // Try dispatch by loaded (not active) scenes.
}

if (_settings.lifespanSec > 0)
{
Expand All @@ -70,6 +78,18 @@ private void Start()
_logger.Log("Launched autopilot");
}

private void DispatchByLoadedScenes()
{
for (var i = 0; i < SceneManager.sceneCount; i++)
{
var fallback = i == SceneManager.sceneCount - 1; // Use fallback agent only in the last scene.
if (_dispatcher.DispatchByScene(SceneManager.GetSceneAt(i), fallback))
{
break;
}
}
}

/// <summary>
/// Returns an logger that autopilot uses. You can change a logger by overriding this method.
/// Default logger is that write to console.
Expand Down Expand Up @@ -154,7 +174,7 @@ public async UniTask TerminateAsync(ExitCode exitCode, string logString = null,
#if UNITY_INCLUDE_TESTS
if (_state.launchFrom == LaunchType.PlayModeTests && exitCode != ExitCode.Normally)
{
throw new NUnit.Framework.AssertionException($"Autopilot failed with exit code {exitCode}");
throw new AssertionException($"Autopilot failed with exit code {exitCode}");
}
#endif
return; // Only terminate autopilot run if starting from play mode.
Expand All @@ -167,7 +187,7 @@ public async UniTask TerminateAsync(ExitCode exitCode, string logString = null,
// XXX: Avoid a problem that Editor stay playing despite isPlaying get assigned false.
// SEE: https://github.com/DeNA/Anjin/issues/20
await UniTask.DelayFrame(1, cancellationToken: token);
UnityEditor.EditorApplication.isPlaying = false;
EditorApplication.isPlaying = false;
// Call Launcher.OnChangePlayModeState() so terminates Unity editor, when launch from CLI.
#else
_logger.Log($"Exit Unity-editor by autopilot, exit code={exitCode}");
Expand Down
52 changes: 20 additions & 32 deletions Tests/Runtime/AgentDispatcherTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,18 @@

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using DeNA.Anjin.Agents;
using DeNA.Anjin.Settings;
using DeNA.Anjin.TestDoubles;
using DeNA.Anjin.Utilities;
using NUnit.Framework;
using TestHelper.Attributes;
using TestHelper.RuntimeInternals;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
#if UNITY_EDITOR
using UnityEditor.SceneManagement;
#endif

#pragma warning disable CS0618 // Type or member is obsolete

namespace DeNA.Anjin
{
Expand All @@ -27,15 +24,6 @@ public class AgentDispatcherTest
{
private IAgentDispatcher _dispatcher;

[SetUp]
public void SetUp()
{
foreach (var agent in Object.FindObjectsOfType<AbstractAgent>())
{
Object.Destroy(agent);
}
}

[TearDown]
public void TearDown()
{
Expand All @@ -49,7 +37,7 @@ private static AutopilotSettings CreateAutopilotSettings()
return testSettings;
}

private static SpyAliveCountAgent CreateSpyAliveCountAgent(string name = nameof(DoNothingAgent))
private static SpyAliveCountAgent CreateSpyAliveCountAgent(string name = nameof(SpyAliveCountAgent))
{
var agent = ScriptableObject.CreateInstance<SpyAliveCountAgent>();
agent.name = name;
Expand All @@ -67,20 +55,14 @@ private void SetUpDispatcher(AutopilotSettings settings)
private const string TestScenePath = "Packages/com.dena.anjin/Tests/TestScenes/Buttons.unity";
private const string TestScenePath2 = "Packages/com.dena.anjin/Tests/TestScenes/Error.unity";

private static async UniTask<Scene> LoadTestSceneAsync(string path, LoadSceneMode mode = LoadSceneMode.Single)
private static string GetSceneName(string path)
{
Scene scene = default;
#if UNITY_EDITOR
scene = EditorSceneManager.LoadSceneInPlayMode(path, new LoadSceneParameters(mode));
while (!scene.isLoaded)
{
await Task.Yield();
}
#endif
return scene;
var pattern = new Regex(@"([^/]+)\.unity$");
return pattern.Match(path).Groups[1].Value;
}

[Test]
[CreateScene]
public async Task DispatchByScene_DispatchAgentBySceneAgentMaps()
{
const string AgentName = "Mapped Agent";
Expand All @@ -91,56 +73,60 @@ public async Task DispatchByScene_DispatchAgentBySceneAgentMaps()
});
SetUpDispatcher(settings);

await LoadTestSceneAsync(TestScenePath);
await SceneManagerHelper.LoadSceneAsync(TestScenePath);

var gameObject = GameObject.Find(AgentName);
Assert.That(gameObject, Is.Not.Null);
Assert.That(SpyAliveCountAgent.AliveInstances, Is.EqualTo(1));
}

[Test]
[CreateScene]
public async Task DispatchByScene_DispatchFallbackAgent()
{
const string AgentName = "Fallback Agent";
var settings = CreateAutopilotSettings();
settings.fallbackAgent = CreateSpyAliveCountAgent(AgentName);
SetUpDispatcher(settings);

await LoadTestSceneAsync(TestScenePath);
await SceneManagerHelper.LoadSceneAsync(TestScenePath);

var gameObject = GameObject.Find(AgentName);
Assert.That(gameObject, Is.Not.Null);
Assert.That(SpyAliveCountAgent.AliveInstances, Is.EqualTo(1));
}

[Test]
[CreateScene]
public async Task DispatchByScene_NoSceneAgentMapsAndFallbackAgent_AgentIsNotDispatch()
{
var settings = CreateAutopilotSettings();
SetUpDispatcher(settings);

await LoadTestSceneAsync(TestScenePath);
await SceneManagerHelper.LoadSceneAsync(TestScenePath);

LogAssert.Expect(LogType.Warning, "Agent not found by scene: Buttons");
Assert.That(SpyAliveCountAgent.AliveInstances, Is.EqualTo(0));
}

[Test]
[CreateScene]
public async Task DispatchByScene_DispatchObserverAgent()
{
const string AgentName = "Observer Agent";
var settings = CreateAutopilotSettings();
settings.observerAgent = CreateSpyAliveCountAgent(AgentName);
SetUpDispatcher(settings);

await LoadTestSceneAsync(TestScenePath);
await SceneManagerHelper.LoadSceneAsync(TestScenePath);

var gameObject = GameObject.Find(AgentName);
Assert.That(gameObject, Is.Not.Null);
Assert.That(SpyAliveCountAgent.AliveInstances, Is.EqualTo(1));
}

[Test]
[CreateScene]
public async Task DispatchByScene_ReActivateScene_NotCreateDuplicateAgents()
{
const string AgentName = "Mapped Agent";
Expand All @@ -151,10 +137,12 @@ public async Task DispatchByScene_ReActivateScene_NotCreateDuplicateAgents()
});
SetUpDispatcher(settings);

var scene = await LoadTestSceneAsync(TestScenePath);
await SceneManagerHelper.LoadSceneAsync(TestScenePath);
var scene = SceneManager.GetSceneByName(GetSceneName(TestScenePath));
Assume.That(SpyAliveCountAgent.AliveInstances, Is.EqualTo(1));

var additiveScene = await LoadTestSceneAsync(TestScenePath2, LoadSceneMode.Additive);
await SceneManagerHelper.LoadSceneAsync(TestScenePath2, LoadSceneMode.Additive);
var additiveScene = SceneManager.GetSceneByName(GetSceneName((TestScenePath2)));
SceneManager.SetActiveScene(additiveScene);

SceneManager.SetActiveScene(scene); // Re-activate
Expand Down
51 changes: 51 additions & 0 deletions Tests/Runtime/AutopilotTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using DeNA.Anjin.Reporters;
using DeNA.Anjin.Settings;
using DeNA.Anjin.TestDoubles;
using NUnit.Framework;
using TestHelper.RuntimeInternals;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;

namespace DeNA.Anjin
Expand Down Expand Up @@ -44,6 +47,54 @@ public async Task Start_LoggerSpecified_UsingSpecifiedLogger()
LogAssert.NoUnexpectedReceived(); // not write to console
}

[Test]
public async Task Start_MappedSceneIsNotActiveButLoaded_DispatchAgent()
{
const string MappedScenePath = "Packages/com.dena.anjin/Tests/TestScenes/Buttons.unity";
const string ActiveScenePath = "Packages/com.dena.anjin/Tests/TestScenes/Empty.unity";

var spyMappedAgent = ScriptableObject.CreateInstance<SpyAgent>();
var spyFallbackAgent = ScriptableObject.CreateInstance<SpyAgent>();

var autopilotSettings = ScriptableObject.CreateInstance<AutopilotSettings>();
autopilotSettings.sceneAgentMaps = new List<SceneAgentMap>
{
new SceneAgentMap { scenePath = MappedScenePath, agent = spyMappedAgent }
};
autopilotSettings.fallbackAgent = spyFallbackAgent;
autopilotSettings.lifespanSec = 1;

await SceneManagerHelper.LoadSceneAsync(ActiveScenePath);
await SceneManagerHelper.LoadSceneAsync(MappedScenePath, LoadSceneMode.Additive);
Assume.That(SceneManager.GetActiveScene().path, Is.EqualTo(ActiveScenePath), "Mapped scene is not active");

await LauncherFromTest.AutopilotAsync(autopilotSettings);

Assert.That(spyMappedAgent.CompleteCount, Is.EqualTo(1), "Mapped Agent dispatched");
Assert.That(spyFallbackAgent.CompleteCount, Is.EqualTo(0), "Fallback Agent is not dispatched");
}

[Test]
public async Task Start_NoMappedSceneInLoadedScenes_DispatchFallbackAgent()
{
const string AdditiveScenePath = "Packages/com.dena.anjin/Tests/TestScenes/Buttons.unity";
const string ActiveScenePath = "Packages/com.dena.anjin/Tests/TestScenes/Empty.unity";

var spyFallbackAgent = ScriptableObject.CreateInstance<SpyAgent>();

var autopilotSettings = ScriptableObject.CreateInstance<AutopilotSettings>();
autopilotSettings.sceneAgentMaps = new List<SceneAgentMap>();
autopilotSettings.fallbackAgent = spyFallbackAgent;
autopilotSettings.lifespanSec = 1;

await SceneManagerHelper.LoadSceneAsync(ActiveScenePath);
await SceneManagerHelper.LoadSceneAsync(AdditiveScenePath, LoadSceneMode.Additive);

await LauncherFromTest.AutopilotAsync(autopilotSettings);

Assert.That(spyFallbackAgent.CompleteCount, Is.EqualTo(1));
}

[Test]
public void ConvertSlackReporterFromObsoleteSlackSettings_HasSlackSettings_GenerateSlackReporter()
{
Expand Down
Loading