repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
namespace AmazonGameLiftPlugin.Core.Shared.ProcessManagement
{
public class ExecutableNotFoundException : Exception
{
public ExecutableNotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
}
}
| 15 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Diagnostics;
namespace AmazonGameLiftPlugin.Core.Shared.ProcessManagement
{
public interface IProcessWrapper
{
string GetProcessOutput(ProcessStartInfo startInfo);
(int, string) GetProcessIdAndStandardOutput(ProcessStartInfo startInfo);
int Start(ProcessStartInfo processStartInfo);
void Kill(int processId);
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.ComponentModel;
using System.Diagnostics;
namespace AmazonGameLiftPlugin.Core.Shared.ProcessManagement
{
public class ProcessWrapper : IProcessWrapper
{
public int Start(ProcessStartInfo processStartInfo)
{
var process = Process.Start(processStartInfo);
return process.Id;
}
public (int, string) GetProcessIdAndStandardOutput(ProcessStartInfo startInfo)
{
var process = Process.Start(startInfo);
return (process.Id, process.StandardOutput.ReadLine());
}
public string GetProcessOutput(ProcessStartInfo startInfo)
{
try
{
return Process.Start(startInfo)?.StandardError?.ReadToEnd();
}
catch (Win32Exception ex)
{
if (ex.Message.Equals("The system cannot find the file specified"))
{
throw new ExecutableNotFoundException("Executable not found", ex);
}
else
{
throw;
}
}
}
public void Kill(int processId)
{
var process = Process.GetProcessById(processId);
process.Kill();
}
}
}
| 51 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.S3;
using Amazon.S3.Model;
namespace AmazonGameLiftPlugin.Core.Shared.S3Bucket
{
public class AmazonS3Wrapper : IAmazonS3Wrapper
{
private readonly IAmazonS3 _amazonS3Client;
public AmazonS3Wrapper(IAmazonS3 amazonS3Client)
{
_amazonS3Client = amazonS3Client;
}
public AmazonS3Wrapper(string accessKey, string secretKey, string region)
{
_amazonS3Client = new AmazonS3Client(accessKey, secretKey, AwsRegionMapper.GetRegionEndpoint(region));
}
public ListBucketsResponse ListBuckets()
=> _amazonS3Client.ListBuckets();
public GetBucketLocationResponse GetBucketLocation(GetBucketLocationRequest request)
=> _amazonS3Client.GetBucketLocation(request);
public PutBucketResponse PutBucket(string bucketName)
=> _amazonS3Client.PutBucket(bucketName);
public PutBucketEncryptionResponse PutBucketEncryption(PutBucketEncryptionRequest request)
=> _amazonS3Client.PutBucketEncryption(request);
public PutBucketVersioningResponse PutBucketVersioning(PutBucketVersioningRequest request)
=> _amazonS3Client.PutBucketVersioning(request);
public PutBucketLoggingResponse PutBucketLogging(PutBucketLoggingRequest request)
=> _amazonS3Client.PutBucketLogging(request);
public PutACLResponse PutACL(PutACLRequest request)
=> _amazonS3Client.PutACL(request);
public GetACLResponse GetACL(GetACLRequest request)
=> _amazonS3Client.GetACL(request);
public PutBucketResponse PutBucket(PutBucketRequest request)
=> _amazonS3Client.PutBucket(request);
public PutLifecycleConfigurationResponse PutLifecycleConfiguration(PutLifecycleConfigurationRequest request)
=> _amazonS3Client.PutLifecycleConfiguration(request);
public GetLifecycleConfigurationResponse GetLifecycleConfiguration(string bucketName)
=> _amazonS3Client.GetLifecycleConfiguration(bucketName);
public bool DoesBucketExist(string bucketName)
=> _amazonS3Client.DoesS3BucketExist(bucketName);
public PutObjectResponse PutObject(PutObjectRequest request)
=> _amazonS3Client.PutObject(request);
public string GetRegionEndpoint()
{
return _amazonS3Client.Config.RegionEndpoint.SystemName;
}
}
}
| 68 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.S3;
using Amazon.S3.Model;
namespace AmazonGameLiftPlugin.Core.Shared.S3Bucket
{
public interface IAmazonS3Wrapper
{
PutBucketResponse PutBucket(string bucketName);
ListBucketsResponse ListBuckets();
GetBucketLocationResponse GetBucketLocation(GetBucketLocationRequest request);
PutBucketResponse PutBucket(PutBucketRequest request);
PutBucketEncryptionResponse PutBucketEncryption(PutBucketEncryptionRequest request);
PutBucketVersioningResponse PutBucketVersioning(PutBucketVersioningRequest request);
PutBucketLoggingResponse PutBucketLogging(PutBucketLoggingRequest request);
PutACLResponse PutACL(PutACLRequest request);
GetACLResponse GetACL(GetACLRequest request);
bool DoesBucketExist(string bucketName);
GetLifecycleConfigurationResponse GetLifecycleConfiguration(string bucketName);
PutLifecycleConfigurationResponse PutLifecycleConfiguration(PutLifecycleConfigurationRequest request);
PutObjectResponse PutObject(PutObjectRequest request);
string GetRegionEndpoint();
}
}
| 40 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using System.IO;
using YamlDotNet.RepresentationModel;
namespace AmazonGameLiftPlugin.Core.Shared.SettingsStore
{
public interface IStreamWrapper
{
void Save(TextWriter output, bool assignAnchors);
void Load(TextReader input);
IList<YamlDocument> GetDocuments();
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using System.IO;
using YamlDotNet.RepresentationModel;
namespace AmazonGameLiftPlugin.Core.Shared.SettingsStore
{
public class YamlStreamWrapper : IStreamWrapper
{
private readonly YamlStream _yamlStream;
public YamlStreamWrapper(YamlStream yamlStream = default)
{
_yamlStream = yamlStream ?? new YamlStream();
}
public void Save(TextWriter output, bool assignAnchors) => _yamlStream.Save(output, assignAnchors);
public void Load(TextReader input) => _yamlStream.Load(input);
public IList<YamlDocument> GetDocuments() => _yamlStream.Documents;
}
}
| 26 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement
{
public class AmazonCognitoIdentityWrapper : IAmazonCognitoIdentityWrapper
{
private readonly IAmazonCognitoIdentityProvider _amazonCognitoIdentityProvider;
public AmazonCognitoIdentityWrapper(string region)
{
_amazonCognitoIdentityProvider = new AmazonCognitoIdentityProviderClient(
string.Empty, string.Empty, AwsRegionMapper.GetRegionEndpoint(region)
);
}
public Models.ConfirmSignUpResponse ConfirmSignUp(Models.ConfirmSignUpRequest request)
{
ConfirmSignUpResponse response = _amazonCognitoIdentityProvider.ConfirmSignUp(new ConfirmSignUpRequest
{
ClientId = request.ClientId,
ConfirmationCode = request.ConfirmationCode,
Username = request.Username
});
return new Models.ConfirmSignUpResponse();
}
public InitiateAuthResponse InitiateAuth(InitiateAuthRequest request)
{
return _amazonCognitoIdentityProvider.InitiateAuth(request);
}
public Models.SignUpResponse SignUp(Models.SignUpRequest request)
{
SignUpResponse response = _amazonCognitoIdentityProvider.SignUp(new SignUpRequest
{
ClientId = request.ClientId,
Username = request.Username,
Password = request.Password
});
return new Models.SignUpResponse();
}
public GlobalSignOutResponse SignOut(GlobalSignOutRequest request)
{
return _amazonCognitoIdentityProvider.GlobalSignOut(request);
}
}
}
| 55 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.CognitoIdentityProvider.Model;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement
{
public interface IAmazonCognitoIdentityWrapper
{
Models.SignUpResponse SignUp(Models.SignUpRequest request);
Models.ConfirmSignUpResponse ConfirmSignUp(Models.ConfirmSignUpRequest request);
InitiateAuthResponse InitiateAuth(InitiateAuthRequest request);
GlobalSignOutResponse SignOut(GlobalSignOutRequest request);
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.UserIdentityManagement.Models;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement
{
public interface IUserIdentity
{
SignUpResponse SignUp(SignUpRequest request);
ConfirmSignUpResponse ConfirmSignUp(ConfirmSignUpRequest request);
SignInResponse SignIn(SignInRequest request);
SignOutResponse SignOut(SignOutRequest request);
RefreshTokenResponse RefreshToken(RefreshTokenRequest request);
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.Shared.Logging;
using AmazonGameLiftPlugin.Core.UserIdentityManagement.Models;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement
{
public class UserIdentity : IUserIdentity
{
private readonly IAmazonCognitoIdentityWrapper _amazonCognitoIdentityWrapper;
public UserIdentity(IAmazonCognitoIdentityWrapper amazonCognitoIdentityWrapper)
{
_amazonCognitoIdentityWrapper = amazonCognitoIdentityWrapper;
}
public Models.ConfirmSignUpResponse ConfirmSignUp(Models.ConfirmSignUpRequest request)
{
try
{
Models.ConfirmSignUpResponse response =
_amazonCognitoIdentityWrapper.ConfirmSignUp(new Models.ConfirmSignUpRequest
{
ClientId = request.ClientId,
Username = request.Username,
ConfirmationCode = request.ConfirmationCode
});
return Response.Ok(new Models.ConfirmSignUpResponse());
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new Models.ConfirmSignUpResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
public Models.SignUpResponse SignUp(Models.SignUpRequest request)
{
try
{
Models.SignUpResponse response =
_amazonCognitoIdentityWrapper.SignUp(new Models.SignUpRequest
{
ClientId = request.ClientId,
Username = request.Username,
Password = request.Password
});
return Response.Ok(response);
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new Models.SignUpResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
public SignInResponse SignIn(SignInRequest request)
{
try
{
InitiateAuthResponse response =
_amazonCognitoIdentityWrapper.InitiateAuth(new InitiateAuthRequest
{
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
ClientId = request.ClientId,
AuthParameters = new Dictionary<string, string>
{
{ "USERNAME",request.Username },
{ "PASSWORD",request.Password }
}
});
AuthenticationResultType authDetails =
response.AuthenticationResult;
return Response.Ok(new SignInResponse
{
AccessToken = authDetails.AccessToken,
IdToken = authDetails.IdToken,
RefreshToken = authDetails.RefreshToken
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
string errorCode = ex is UserNotConfirmedException ?
ErrorCode.UserNotConfirmed :
ErrorCode.UnknownError;
return Response.Fail(new SignInResponse
{
ErrorCode = errorCode,
ErrorMessage = ex.Message
});
}
}
public SignOutResponse SignOut(SignOutRequest request)
{
try
{
GlobalSignOutResponse response =
_amazonCognitoIdentityWrapper.SignOut(new GlobalSignOutRequest
{
AccessToken = request.AccessToken
});
return Response.Ok(new SignOutResponse());
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new SignOutResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
public RefreshTokenResponse RefreshToken(RefreshTokenRequest request)
{
try
{
InitiateAuthResponse response =
_amazonCognitoIdentityWrapper.InitiateAuth(new InitiateAuthRequest
{
ClientId = request.ClientId,
AuthFlow = AuthFlowType.REFRESH_TOKEN,
AuthParameters = new Dictionary<string, string>
{
{ "REFRESH_TOKEN", request.RefreshToken }
}
});
return Response.Ok(new RefreshTokenResponse
{
IdToken = response.AuthenticationResult.IdToken
});
}
catch (Exception ex)
{
Logger.LogError(ex, ex.Message);
return Response.Fail(new RefreshTokenResponse
{
ErrorCode = ErrorCode.UnknownError,
ErrorMessage = ex.Message
});
}
}
}
}
| 174 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement.Models
{
public class ConfirmSignUpRequest
{
public string ClientId { get; set; }
public string Username { get; set; }
public string ConfirmationCode { get; set; }
}
public class ConfirmSignUpResponse : Response
{
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement.Models
{
public class RefreshTokenRequest
{
public string RefreshToken { get; set; }
public string ClientId { get; set; }
}
public class RefreshTokenResponse : Response
{
public string IdToken { get; set; }
}
}
| 19 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement.Models
{
public class SignInRequest
{
public string ClientId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
public class SignInResponse : Response
{
public string AccessToken { get; set; }
public string IdToken { get; set; }
public string RefreshToken { get; set; }
}
}
| 22 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement.Models
{
public class SignOutRequest
{
public string AccessToken { get; set; }
}
public class SignOutResponse : Response
{
}
}
| 17 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Core.UserIdentityManagement.Models
{
public class SignUpRequest
{
public string Username { get; set; }
public string Password { get; set; }
public string ClientId { get; set; }
}
public class SignUpResponse : Response
{
}
}
| 25 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.Shared;
using JetBrains.Annotations;
using UnityEngine;
namespace AmazonGameLift.Custom
{
[UsedImplicitly]
public sealed class Deployer : DeployerBase
{
public override string DisplayName => "Custom Scenario";
public override string Description =>
"This is a custom deployment scenario for you to edit!";
public override string HelpUrl => "";
public override string ScenarioFolder => "Assets/Editor/Custom Scenario";
public override bool HasGameServer => false;
public override int PreferredUiOrder => 99;
protected override Task<DeploymentResponse> Deploy(DeploymentRequest request)
{
Debug.Log($"Scenario lambdas path: {request.LambdaFolderPath}");
return Task.FromResult(Response.Fail(new DeploymentResponse { ErrorCode = Editor.ErrorCode.OperationCancelled }));
}
}
}
| 35 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
public static class ClientServerSwitchMenu
{
private const string BootstrapScenePath = "Assets/Scenes/BootstrapScene.unity";
private const string GameScenePath = "Assets/Scenes/GameScene.unity";
private const string UnityServerDefine = "UNITY_SERVER";
private const string MissingWindowsModuleError = "Please install Windows build module via UnityHub first. See: https://docs.unity3d.com/Manual/GettingStartedAddingEditorComponents.html";
#if UNITY_EDITOR_OSX
[MenuItem("GameLift/Apply MacOS Sample Client Build Settings", priority = 9203)]
public static void ConfigureMacOsClient()
{
#if UNITY_2021_3_OR_NEWER
EditorUserBuildSettings.standaloneBuildSubtarget = StandaloneBuildSubtarget.Player;
#else
EditorUserBuildSettings.enableHeadlessMode = false;
#endif
EditorUserBuildSettings.SwitchActiveBuildTarget( BuildTargetGroup.Standalone, BuildTarget.StandaloneOSX );
Switch(RemoveServer);
LogSuccessMessage("Sample Client", "MacOS");
}
[MenuItem("GameLift/Apply MacOS Sample Server Build Settings", priority = 9102)]
public static void ConfigureMacOsServer()
{
#if UNITY_2021_3_OR_NEWER
EditorUserBuildSettings.standaloneBuildSubtarget = StandaloneBuildSubtarget.Server;
#else
EditorUserBuildSettings.enableHeadlessMode = true;
#endif
EditorUserBuildSettings.SwitchActiveBuildTarget( BuildTargetGroup.Standalone, BuildTarget.StandaloneOSX );
Switch(AddServer);
LogSuccessMessage("Sample Server", "MacOS");
}
#endif
[MenuItem("GameLift/Apply Windows Sample Client Build Settings", priority = 9202)]
public static void RunClient()
{
if (!BuildPipeline.IsBuildTargetSupported(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64))
{
Debug.LogError(MissingWindowsModuleError);
return;
}
EditorUserBuildSettings.SwitchActiveBuildTarget( BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64 );
#if UNITY_2021_3_OR_NEWER
EditorUserBuildSettings.standaloneBuildSubtarget = StandaloneBuildSubtarget.Player;
#else
EditorUserBuildSettings.enableHeadlessMode = false;
#endif
Switch(RemoveServer);
LogSuccessMessage("Sample Client", "Windows");
}
[MenuItem("GameLift/Apply Windows Sample Server Build Settings", priority = 9101)]
public static void RunServer()
{
if (!BuildPipeline.IsBuildTargetSupported(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64))
{
Debug.LogError(MissingWindowsModuleError);
return;
}
EditorUserBuildSettings.SwitchActiveBuildTarget( BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64 );
#if UNITY_2021_3_OR_NEWER
EditorUserBuildSettings.standaloneBuildSubtarget = StandaloneBuildSubtarget.Server;
#else
EditorUserBuildSettings.enableHeadlessMode = true;
#endif
Switch(AddServer);
LogSuccessMessage("Sample Server", "Windows");
}
private static void LogSuccessMessage(string name, string platform) {
Debug.Log($"{name} has been successfully configured for {platform}. Please go to BuildSettings to build the project.");
}
private static void Switch(Func<string, string> updateDefines)
{
EditorBuildSettings.scenes = new[]
{
new EditorBuildSettingsScene(BootstrapScenePath, enabled: true),
new EditorBuildSettingsScene(GameScenePath, enabled: true),
};
EditorSceneManager.OpenScene(BootstrapScenePath);
string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
defines = updateDefines(defines);
PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, defines);
#if !UNITY_2019_4_OR_NEWER
bool ok = EditorUtility.DisplayDialog("Unity restart required",
"Restart Unity to finish the configuration?",
"Yes",
"No");
if (ok)
{
EditorApplication.OpenProject(Directory.GetCurrentDirectory());
}
#endif
}
private static string AddServer(string defines)
{
if (defines.Contains(UnityServerDefine + ";") || defines.EndsWith(UnityServerDefine))
{
return defines;
}
return defines + ";" + UnityServerDefine;
}
private static string RemoveServer(string defines)
{
int index = defines.IndexOf(UnityServerDefine);
if (index < 0)
{
return defines;
}
return defines.Remove(index, UnityServerDefine.Length);
}
}
| 133 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLift.Runtime;
using UnityEditor;
public static class GameLiftClientSettingsMenu
{
[MenuItem("GameLift/Go To Client Connection Settings", priority = 9201)]
public static void Run()
{
GameLiftClientSettings settings = AssetDatabase.LoadAssetAtPath<GameLiftClientSettings>("Assets/Settings/GameLiftClientSettings.asset");
if (settings)
{
Selection.activeObject = settings;
EditorGUIUtility.PingObject(settings);
}
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
public static class UnityPackageExporter
{
public static void Export()
{
var exportedPackageAssetList = Directory.EnumerateDirectories("Assets")
.Except(new string[]
{
"Assets\\Editor",
"Assets\\Tests",
})
.ToList();
Debug.Log("Exporting Sample Game...");
exportedPackageAssetList.AddRange(Directory.EnumerateFiles("Assets"));
exportedPackageAssetList.Add("Assets\\Editor\\Scripts\\GameLiftClientSettingsMenu.cs");
exportedPackageAssetList.Add("Assets\\Editor\\Scripts\\ClientServerSwitchMenu.cs");
string outputFolder = @"..";
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
string outputPath = Path.Combine(outputFolder, "SampleGame.unitypackage");
AssetDatabase.ExportPackage(exportedPackageAssetList.ToArray(), outputPath,
ExportPackageOptions.Recurse | ExportPackageOptions.IncludeDependencies);
Debug.Log("Sample Game exported to " + outputPath);
}
}
| 43 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
[System.Serializable]
public class Chord
{
private bool _chordChanged = false;
public bool[] Keys = new bool[9];
public void Reset()
{
for (int keyIdx = 0; keyIdx < Keys.Length; keyIdx++)
{
Keys[keyIdx] = false;
}
_chordChanged = false;
}
public void Set(int keyIdx)
{
Keys[keyIdx] = true;
_chordChanged = true;
}
public bool IsChanged()
{
return _chordChanged;
}
public string Serialize()
{
return JsonUtility.ToJson(this);
}
public void Deserialize(string json)
{
if (!string.IsNullOrEmpty(json))
{
JsonUtility.FromJsonOverwrite(json, this);
}
}
public static Chord CreateFromSerial(string json)
{
var temp = new Chord();
temp.Deserialize(json);
return temp;
}
}
| 54 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if !UNITY_SERVER
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.UserIdentityManagement.Models;
using UnityEngine.SceneManagement;
#endif
using UnityEngine;
using AmazonGameLift.Runtime;
public sealed class ClientBootstrap : MonoBehaviour
{
[SerializeField]
private GameLift _gameLift;
#pragma warning disable CS0414
[SerializeField]
private string _gameSceneName = "GameScene";
#pragma warning restore CS0414
[SerializeField]
private Canvas _mainCanvas;
[SerializeField]
private SignInScreen _signInScreenPrefab;
[SerializeField]
private SignUpScreen _signUpScreenPrefab;
[SerializeField]
private ConfirmationCodeScreen _confirmationScreenPrefab;
[SerializeField]
private ConfirmationSuccessScreen _confirmationSuccessScreenPrefab;
[SerializeField]
private GameLiftClientSettings _gameLiftSettings;
#if !UNITY_SERVER
private readonly Logger _logger = Logger.SharedInstance;
private SignInScreen _signInScreen;
private SignUpScreen _signUpScreen;
private ConfirmationCodeScreen _confirmationScreen;
private ConfirmationSuccessScreen _confirmationSuccessScreen;
private void Awake()
{
// prevent the game going to sleep when the window loses focus
Application.runInBackground = true;
// Just 60 frames per second is enough
Application.targetFrameRate = 60;
Screen.SetResolution(1024, 768, FullScreenMode.Windowed);
}
private void Start()
{
ShowSignIn();
}
private void ShowSignIn()
{
_signInScreen = _signInScreen != null ? _signInScreen : Instantiate(_signInScreenPrefab, _mainCanvas.transform);
_signInScreen.SetSubmitAction(SignIn);
_signInScreen.SetShowSignUpAction(() =>
{
_signInScreen.Hide();
ShowSignUp();
});
if (_gameLiftSettings.IsLocalTest)
{
_signInScreen.SetHint("You are currently running in Local mode. You may enter any email/password to successfully login");
}
_signInScreen.Show();
}
private void ShowSignUp()
{
_signUpScreen = _signUpScreen != null ? _signUpScreen : Instantiate(_signUpScreenPrefab, _mainCanvas.transform);
_signUpScreen.SetSubmitAction(SignUp);
_signUpScreen.Show();
}
private void ShowConfirmSignUp(string email)
{
_confirmationScreen = _confirmationScreen != null ? _confirmationScreen : Instantiate(_confirmationScreenPrefab, _mainCanvas.transform);
_confirmationScreen.SetSubmitAction(code => ConfirmSignUp(email, code));
_confirmationScreen.Show();
}
private void SignIn(string email, string password)
{
_logger.Write("Singing in...");
_signInScreen.SetInteractable(false);
_signInScreen.SetResultText(string.Empty);
SignInResponse response = _gameLift.SignIn(email, password);
_signInScreen.SetInteractable(true);
if (!response.Success && response.ErrorCode != ErrorCode.UserNotConfirmed)
{
_logger.Write($"Sign-in error {response.ErrorCode}: {response.ErrorMessage}", LogType.Error);
_signInScreen.SetResultText(response.ErrorMessage ?? Strings.ErrorUnknown);
return;
}
_signInScreen.Hide();
if (!response.Success && response.ErrorCode == ErrorCode.UserNotConfirmed)
{
ShowConfirmSignUp(email);
return;
}
_logger.Write("Singed in.");
_signInScreen.SetInteractable(false);
StartGame();
}
private void SignUp(string email, string password)
{
_logger.Write("Singing up...");
_signUpScreen.SetInteractable(false);
_signUpScreen.SetResultText(string.Empty);
SignUpResponse response = _gameLift.SignUp(email, password);
_signUpScreen.SetInteractable(true);
if (!response.Success)
{
_logger.Write($"Sign-up error {response.ErrorCode}: {response.ErrorMessage}", LogType.Error);
_signUpScreen.SetResultText(response.ErrorMessage ?? Strings.ErrorUnknown);
return;
}
_signUpScreen.Hide();
ShowConfirmSignUp(email);
}
private void ConfirmSignUp(string email, string code)
{
_logger.Write("Sending the confirmation code...");
_confirmationScreen.SetInteractable(false);
_confirmationScreen.SetResultText(string.Empty);
ConfirmSignUpResponse response = _gameLift.ConfirmSignUp(email, code);
_confirmationScreen.SetInteractable(true);
if (!response.Success)
{
_logger.Write($"Confirmation error {response.ErrorCode}: {response.ErrorMessage}", LogType.Error);
_confirmationScreen.SetResultText(response.ErrorMessage ?? Strings.ErrorUnknown);
return;
}
_logger.Write("Confirmation success!");
_confirmationScreen.Hide();
ShowConfirmationSuccess();
}
private void ShowConfirmationSuccess()
{
_confirmationSuccessScreen = _confirmationSuccessScreen != null
? _confirmationSuccessScreen
: Instantiate(_confirmationSuccessScreenPrefab, _mainCanvas.transform);
_confirmationSuccessScreen.SetSubmitAction(ConfirmSuccess);
_confirmationSuccessScreen.Show();
_confirmationSuccessScreen.SetResultText("Your account is confirmed.");
}
private void ConfirmSuccess()
{
_confirmationSuccessScreen.Hide();
ShowSignIn();
}
private void StartGame()
{
SceneManager.LoadSceneAsync(_gameSceneName);
}
#endif
}
| 182 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
[System.Serializable]
public class ConnectionInfo
{
[SerializeField]
private string _ipAddress;
[SerializeField]
private int _port;
[SerializeField]
private string _playerSessionId;
public string IpAddress
{
get { return _ipAddress; }
set { _ipAddress = value; }
}
public int Port
{
get { return _port; }
set { _port = value; }
}
public string PlayerSessionId
{
get { return _playerSessionId; }
set { _playerSessionId = value; }
}
public string Serialize()
{
return JsonUtility.ToJson(this);
}
public static ConnectionInfo CreateFromSerial(string json)
{
var temp = new ConnectionInfo();
temp.Deserialize(json);
return temp;
}
public override string ToString()
{
return string.Format("ConnectionInfo (IpAddress: {0}, Port: {1}, PlayerSessionId: {2})", IpAddress, Port, PlayerSessionId);
}
private void Deserialize(string json)
{
if (!string.IsNullOrEmpty(json))
{
JsonUtility.FromJsonOverwrite(json, this);
}
}
}
| 57 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using AmazonGameLift.Runtime;
#if !UNITY_SERVER
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.UserIdentityManagement.Models;
#endif
using UnityEngine;
using UnityEngine.Events;
public class GameLift : MonoBehaviour
{
[Serializable]
public sealed class GameLiftConnectionChangedEvent : UnityEvent<bool> { }
public GameLiftConnectionChangedEvent ConnectionChangedEvent;
[SerializeField]
private GameLiftClientSettings _gameLiftSettings;
private readonly Logger _logger = Logger.SharedInstance;
#if UNITY_SERVER
private GameLiftServer _server;
#else
private GameLiftClient _client;
#endif
public int ServerPort { get; private set; }
public bool IsConnected { get; set;}
private bool MyRemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool isOk = true;
// If there are errors in the certificate chain, look at each error to determine the cause.
if (sslPolicyErrors != SslPolicyErrors.None)
{
for (int i = 0; i < chain.ChainStatus.Length; i++)
{
if (chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown)
{
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
bool chainIsValid = chain.Build((X509Certificate2)certificate);
if (!chainIsValid)
{
isOk = false;
}
}
}
}
return isOk;
}
private void Awake()
{
_logger.Write(":) GAMELIFT AWAKE");
// Allow Unity to validate HTTPS SSL certificates; http://stackoverflow.com/questions/4926676
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
ConnectionChangedEvent.AddListener(value => IsConnected = value);
#if UNITY_SERVER
_logger.Write(":) I AM SERVER");
_server = new GameLiftServer(this, _logger);
#else
_logger.Write(":) I AM CLIENT");
var coreApi = new LoggingGameLiftCoreApi(_gameLiftSettings.GetConfiguration());
_client = new GameLiftClient(coreApi, new Delay(), _logger);
#endif
}
private void OnDestroy()
{
#if !UNITY_SERVER
_client.Dispose();
#endif
}
#if UNITY_SERVER
public void StartServer(int port, string logFilePath = null)
{
_logger.Write($":) GAMELIFT StartServer at port {port}.");
ServerPort = port;
_server.Start(port, logFilePath);
}
public void TerminateGameSession(bool processEnding)
{
_server.TerminateGameSession(processEnding);
}
// we received a force terminate request. Notify clients and gracefully exit.
public void TerminateServer()
{
Application.Quit();
}
public bool AcceptPlayerSession(string playerSessionId)
{
return _server.AcceptPlayerSession(playerSessionId);
}
public bool RemovePlayerSession(string playerSessionId)
{
return _server.RemovePlayerSession(playerSessionId);
}
#else
#if UNITY_EDITOR
public void OverrideClient(GameLiftClient value)
{
_client = value ?? throw new ArgumentNullException(nameof(value));
}
#endif
public SignUpResponse SignUp(string email, string password)
{
return _client.Core.SignUp(email, password);
}
public ConfirmSignUpResponse ConfirmSignUp(string email, string confirmationCode)
{
return _client.Core.ConfirmSignUp(email, confirmationCode);
}
public SignInResponse SignIn(string email, string password)
{
SignInResponse response = _client.Core.SignIn(email, password);
if (!response.Success)
{
return response;
}
_client.ClientCredentials = new ClientCredentials
{
AccessToken = response.AccessToken,
IdToken = response.IdToken,
RefreshToken = response.RefreshToken
};
return response;
}
public SignOutResponse SignOut()
{
return _client.SignOut();
}
public void SetCredentials(ClientCredentials credentials)
{
_client.ClientCredentials = credentials;
}
public async Task<(bool success, ConnectionInfo connection)> GetConnectionInfo(CancellationToken cancellationToken = default)
{
_logger.Write("CLIENT GetConnectionInfo()");
(bool success, ConnectionInfo connectionInfo) response = await _client.GetConnectionInfo(cancellationToken);
_logger.Write($"CLIENT CONNECT INFO: {response.connectionInfo}");
ConnectionChangedEvent?.Invoke(response.success);
return response;
}
#endif
}
| 174 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using UnityEngine;
public class GameLog
{
private readonly GameLogic _logic;
private readonly Logger _logger;
public GameLog(GameLogic logic, Logger logger)
{
_logic = logic ?? throw new ArgumentNullException(nameof(logic));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public void WriteLine(string line, LogType logType = LogType.Log)
{
#if UNITY_SERVER
string me = "SERVER";
#else
string me = "CLIENT " + (_logic.PlayerIdx);
#endif
_logger.Write($"{me}: Frame: {_logic.Frame} {line}", logType);
}
}
| 28 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if !UNITY_SERVER
using System.Threading;
using System.Threading.Tasks;
#endif
using UnityEngine;
public class GameLogic : MonoBehaviour
{
[SerializeField]
private Canvas _mainCanvas;
[SerializeField]
private StartGameScreen _startGameScreenPrefab;
private readonly Logger _logger = Logger.SharedInstance;
private Input _input;
private Simulation _simulation;
#if UNITY_SERVER
private NetworkServer _server;
#else
private NetworkClient _client;
private bool _startConnection;
private bool _connected;
private CancellationTokenSource _connectionCancellationTokenSource;
#endif
public Render Render { get; private set; }
public Status Status { get; private set; }
public GameLog Log { get; private set; }
public GameLift GameLift { get; private set; }
public ulong Frame
{
set => _simulation.Frame = value;
get => _simulation.Frame;
}
public int PlayerIdx => _simulation.PlayerIdx;
public bool Playing => _simulation.Playing;
public bool Authoritative =>
#if UNITY_SERVER
true;
#else
_client.Authoritative;
#endif
public bool GameliftStatus
{
get => Status.GameliftStatus;
private set => Status.GameliftStatus = value;
}
#if !UNITY_SERVER
public bool ClientConnected
{
get => _connected;
set
{
_connected = value;
Status.Connected = value;
}
}
#endif
private void Awake()
{
_logger.Write(":) GAMELOGIC AWAKE");
// Get pointers to scripts on other objects
var gameliftObj = GameObject.Find("/GameLiftStatic");
Debug.Assert(gameliftObj != null);
GameLift = gameliftObj.GetComponent<GameLift>();
if (GameLift == null)
{
_logger.Write(":| GAMELIFT CODE NOT AVAILABLE ON GAMELIFTSTATIC OBJECT", LogType.Error);
return;
}
GameLift.ConnectionChangedEvent.AddListener(value => GameliftStatus = value);
}
private async void Start()
{
_logger.Write(":) GAMELOGIC START");
// create owned objects
Log = new GameLog(this, _logger);
_input = new Input(this);
Status = new Status(this);
_simulation = new Simulation(this);
Render = new Render();
#if UNITY_SERVER
_server = new NetworkServer(this, GameLift.ServerPort);
// if running server, GameLift is already initialized before GameLogic.Start is called
GameliftStatus = GameLift.IsConnected;
_logger.Write(":) LISTENING ON PORT " + GameLift.ServerPort);
#else
_client = new NetworkClient(this);
_connectionCancellationTokenSource = new CancellationTokenSource();
if (GameLift == null)
{
return;
}
try
{
await Connect(_connectionCancellationTokenSource.Token);
}
catch (TaskCanceledException)
{
Log.WriteLine("Connection was cancelled.");
return;
}
#endif
// Start Game
_input.Start();
Status.Start();
_simulation.ResetBoard();
_simulation.ResetScores();
#if UNITY_SERVER
// if I am the server, I will send my state to all the clients so they have the same board and RNG state as I do
_server.TransmitState();
#endif
Log.WriteLine("HELLO WORLD!");
Render.SetMessage("HELLO WORLD!");
ResetMessage(60);
RenderBoard();
}
private void Update()
{
#if UNITY_SERVER
_input.Update();
Attract();
Frame++;
_server.Update();
#else
if (!ClientConnected)
{
return;
}
_input.Update();
Attract();
Frame++;
_client.Update();
#endif
}
private void OnApplicationQuit()
{
Log.WriteLine("Application received quit signal");
#if UNITY_SERVER
_server.Disconnect();
#else
_connectionCancellationTokenSource.Cancel();
_connectionCancellationTokenSource.Dispose();
_client.Disconnect();
#endif
}
#if !UNITY_SERVER
private async Task Connect(CancellationToken cancellationToken)
{
StartGameScreen startGameScreen = Instantiate(_startGameScreenPrefab, _mainCanvas.transform);
startGameScreen.SetSubmitAction(StartConnection);
startGameScreen.Show();
while (!ClientConnected)
{
while (!_startConnection)
{
// similar to yield return null
await Task.Yield();
}
_startConnection = false;
startGameScreen.SetInteractable(false);
startGameScreen.SetResultText(string.Empty);
(bool success, ConnectionInfo connectionInfo) = await GameLift.GetConnectionInfo(cancellationToken);
if (success)
{
GameliftStatus = connectionInfo.IpAddress != NetworkClient.LocalHost;
ClientConnected = _client.TryConnect(connectionInfo);
}
if (!ClientConnected)
{
startGameScreen.SetInteractable(true);
startGameScreen.SetResultText(Strings.ErrorStartingGame);
}
}
startGameScreen.Hide();
}
private void StartConnection()
{
_startConnection = true;
}
#endif
private void Attract()
{
if (!Playing && Authoritative && Frame % 60 == 0)
{
// randomize the board
_simulation.ResetBoard();
#if UNITY_SERVER
// if I am the server, I will send my state to all the clients so they have the same board and RNG state as I do
_server.TransmitState();
#endif
RenderBoard();
}
}
public void InputEvent(int playerIdx, Chord inputChord)
{
#if !UNITY_SERVER
_client.TransmitInput(playerIdx, inputChord);
#endif
if (_simulation.SimulateOnInput(playerIdx, inputChord))
{
RenderBoard();
#if UNITY_SERVER
_server.TransmitState();
#endif
}
}
public void ShowHighlight(int keyIdx)
{
Render.ShowHighlight(keyIdx);
}
public void HideHighlight(int keyIdx)
{
Render.HideHighlight(keyIdx);
}
public void RenderBoard()
{
Render.RenderBoard(_simulation, Status);
}
public void ResetScore(int playerIdx)
{
_simulation.ResetScore(playerIdx);
}
public void ZeroScore(int playerIdx)
{
_simulation.ZeroScore(playerIdx);
}
// Is the specified player in the current game?
public bool IsConnected(int playerIdx)
{
#if UNITY_SERVER
return _server.IsConnected(playerIdx);
#else
if (playerIdx == 0)
{
return true;
}
return false;
#endif
}
// We pressed RETURN and we are ready to start the game
public void Ready()
{
#if !UNITY_SERVER
if (Authoritative)
{
StartGame(); // single player start
RenderBoard();
}
else
{
_client.Ready();
}
#endif
}
public void StartGame()
{
_simulation.ResetBoard();
_simulation.ResetScores();
_simulation.Playing = true;
Log.WriteLine("GO");
Render.SetMessage("GO");
FlashMessage(4, 4);
#if UNITY_SERVER
_server.TransmitState();
#endif
RenderBoard();
}
public void End()
{
#if !UNITY_SERVER
if (Authoritative)
{
EndGame(); // single player end
}
else
{
_client.End();
}
#endif
}
public void EndGame()
{
_simulation.Playing = false;
Log.WriteLine("GAME OVER");
Render.SetMessage("GAME OVER");
FlashMessage(10, 1);
#if UNITY_SERVER
_server.TransmitState();
#endif
}
public string GetState(int playerIdx)
{
return _simulation.Serialize(playerIdx);
}
public void SetState(string state)
{
bool priorPlayingState = _simulation.Deserialize(state);
if (priorPlayingState == false && _simulation.Playing == true)
{
StartGame();
}
if (priorPlayingState == true && _simulation.Playing == false)
{
EndGame();
}
RenderBoard();
}
public void TransmitLog()
{
#if UNITY_SERVER
_server.TransmitLog("THIS IS A TEST");
#endif
}
public void ResetMessage(int timeSeconds)
{
StartCoroutine(Render.ResetMessage(timeSeconds));
}
public void FlashMessage(int timeSeconds, int rate)
{
StartCoroutine(Render.FlashMessage(timeSeconds, rate));
}
}
| 380 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
[DisallowMultipleComponent]
public sealed class Global : MonoBehaviour
{
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
}
| 14 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System.Collections.Generic;
using UnityEngine;
public class Input
{
// record what keys are in the current move that we are making
private readonly Chord _chord = new Chord();
private readonly GameLogic _gl;
private readonly Dictionary<KeyCode, int> _keys = new Dictionary<KeyCode, int>
{
{KeyCode.Keypad1, 0},
{KeyCode.Keypad2, 1},
{KeyCode.Keypad3, 2},
{KeyCode.Keypad4, 3},
{KeyCode.Keypad5, 4},
{KeyCode.Keypad6, 5},
{KeyCode.Keypad7, 6},
{KeyCode.Keypad8, 7},
{KeyCode.Keypad9, 8},
{KeyCode.N, 0},
{KeyCode.M, 1},
{KeyCode.Comma, 2},
{KeyCode.H, 3},
{KeyCode.J, 4},
{KeyCode.K, 5},
{KeyCode.Y, 6},
{KeyCode.U, 7},
{KeyCode.I, 8}
};
public Input(GameLogic gl)
{
_gl = gl;
}
public void Start()
{
_chord.Reset();
for (int keyIdx = 0; keyIdx < 9; keyIdx++)
{
_gl.HideHighlight(keyIdx);
}
}
public void Update()
{
if (_gl.Playing)
{
// quit?
if (UnityEngine.Input.GetKeyUp(KeyCode.Escape))
{
_gl.End();
return;
}
// game move
bool released = true;
foreach (KeyValuePair<KeyCode, int> kv in _keys)
{
if (UnityEngine.Input.GetKey(kv.Key))
{
_chord.Set(kv.Value);
_gl.ShowHighlight(kv.Value);
released = false;
}
}
if (released)
{
if (_chord.IsChanged())
{
// all keys are released, chord is complete
_gl.InputEvent(_gl.PlayerIdx, _chord);
Start();
}
}
}
else
{
if (UnityEngine.Input.GetKeyUp(KeyCode.Return))
{
_gl.Ready();
return;
}
}
}
}
| 94 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class Logger
{
private static Logger s_instance;
private readonly int _processId;
public static Logger SharedInstance => s_instance ?? (s_instance = new Logger());
protected internal Logger()
{
_processId = Process.GetCurrentProcess().Id;
}
public virtual void Write(string message, LogType logType = LogType.Log)
{
if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
string formatted = Format(message, logType);
switch (logType)
{
case LogType.Error:
Debug.LogError(formatted);
break;
case LogType.Assert:
Debug.LogAssertion(formatted);
break;
case LogType.Warning:
Debug.LogWarning(formatted);
break;
case LogType.Log:
Debug.Log(formatted);
break;
default:
throw new ArgumentOutOfRangeException(nameof(logType));
}
}
private string Format(string message, LogType logType)
{
DateTime utcNow = DateTime.UtcNow;
return $"{utcNow:s}{utcNow:ff} PID:{_processId} {logType} {message}";
}
}
| 54 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
public static class NetworkProtocol
{
public static string[] Receive(TcpClient client)
{
NetworkStream stream = client.GetStream();
var messages = new List<string>();
while (stream.DataAvailable)
{
byte[] bufferLength = new byte[4];
stream.Read(bufferLength, 0, bufferLength.Length);
int msgSize = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bufferLength, 0));
byte[] readBuffer = new byte[msgSize];
stream.Read(readBuffer, 0, readBuffer.Length);
string msgStr = Encoding.ASCII.GetString(readBuffer, 0, readBuffer.Length);
messages.Add(msgStr);
}
return messages.ToArray();
}
public static void Send(TcpClient client, string msgStr)
{
if (client == null)
{
return;
}
NetworkStream stream = client.GetStream();
byte[] writeBuffer = Encoding.ASCII.GetBytes(msgStr);
int msgSize = writeBuffer.Length;
byte[] bufferLength = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(msgSize));
stream.Write(bufferLength, 0, bufferLength.Length);
stream.Write(writeBuffer, 0, msgSize);
}
}
| 46 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using JetBrains.Annotations;
using UnityEngine;
[DisallowMultipleComponent]
public sealed class QuitGame : MonoBehaviour
{
[UsedImplicitly]
public void Run()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class Render
{
private readonly GameObject[] _buttons = new GameObject[9];
private readonly GameObject[] _highlights = new GameObject[9];
private readonly Material[] _materials = new Material[8];
private readonly Text _scoreText;
private readonly Text _statusText;
private readonly Text _msgText;
public Render()
{
for (int butNum = 1; butNum <= _buttons.Length; butNum++)
{
_buttons[butNum - 1] = GameObject.Find("/Button" + butNum); // array index is one less than the keypad number it correlates to
Debug.Assert(_buttons[butNum - 1] != null); // test our button was found (debug only)
}
for (int hlNum = 1; hlNum <= _highlights.Length; hlNum++)
{
_highlights[hlNum - 1] = GameObject.Find("/Highlight" + hlNum); // array index is one less than the keypad number it correlates to
Debug.Assert(_highlights[hlNum - 1] != null); // test our highlight was found (debug only)
}
// Materials are not all active so we have to load them
for (int matNum = 1; matNum <= _materials.Length; matNum++)
{
_materials[matNum - 1] = Resources.Load("Materials/Color" + matNum.ToString().PadLeft(3, '0'), typeof(Material)) as Material;
Debug.Assert(_materials[matNum - 1] != null);
}
var score = GameObject.Find("/Canvas/Score");
_scoreText = score.GetComponent<Text>();
var status = GameObject.Find("/Canvas/Status");
_statusText = status.GetComponent<Text>();
var msg = GameObject.Find("/Canvas/MainMessage");
_msgText = msg.GetComponent<Text>();
}
public void ShowHighlight(int keyNum)
{
_highlights[keyNum].SetActive(true);
}
public void HideHighlight(int keyNum)
{
_highlights[keyNum].SetActive(false);
}
public void SetButtonColor(int butNum, int matNum)
{
Debug.Assert(butNum < _buttons.Length);
Debug.Assert(matNum < _materials.Length);
Renderer rend = _buttons[butNum].GetComponent<Renderer>();
rend.material = _materials[matNum];
}
private void SetScoreText(int[] scores)
{
_scoreText.text = "1UP " + (scores[0] < 0 ? "---" : scores[0].ToString().PadLeft(3, '0'));
_scoreText.text += " 2UP " + (scores[1] < 0 ? "---" : scores[1].ToString().PadLeft(3, '0'));
_scoreText.text += " 3UP " + (scores[2] < 0 ? "---" : scores[2].ToString().PadLeft(3, '0'));
_scoreText.text += " 4UP " + (scores[3] < 0 ? "---" : scores[3].ToString().PadLeft(3, '0'));
}
public void RenderBoard(Simulation state, Status _)
{
for (int bcNum = 0; bcNum < state.BoardColors.Length; bcNum++)
{
SetButtonColor(bcNum, state.BoardColors[bcNum]);
}
SetScoreText(state.Scores);
}
public void SetStatusText(string text)
{
_statusText.text = text;
}
public void SetMessage(string msg)
{
_msgText.text = msg;
}
internal IEnumerator ResetMessage(int time)
{
string text = _msgText.text;
yield return new WaitForSeconds(time);
if (_msgText.text == text)
{
SetMessage("");
}
}
internal IEnumerator FlashMessage(int time, int rate)
{
string text = _msgText.text;
for (int i = 0; i < time * rate; i++)
{
SetMessage(text);
yield return new WaitForSeconds(0.5f / rate);
if (_msgText.text != text)
{
break;
}
SetMessage("");
yield return new WaitForSeconds(0.5f / rate);
if (_msgText.text != "")
{
break;
}
}
}
}
| 127 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if UNITY_SERVER
using System;
using UnityEngine.SceneManagement;
#endif
using UnityEngine;
public sealed class ServerBootstrap : MonoBehaviour
{
#pragma warning disable CS0414
[SerializeField]
private GameLift _gameLift;
[SerializeField]
private string _gameSceneName = "GameScene";
#pragma warning restore CS0414
#if UNITY_SERVER
private void Awake()
{
// prevent the game going to sleep when the window loses focus
Application.runInBackground = true;
// Just 60 frames per second is enough
Application.targetFrameRate = 60;
}
private void Start()
{
string logFilePath = ReadLogFilePathFromCmd();
int? port = ReadPortFromCmd();
_gameLift.StartServer(port ?? 33430, logFilePath);
StartGame();
}
private void StartGame()
{
SceneManager.LoadSceneAsync(_gameSceneName);
}
private int? ReadPortFromCmd()
{
string[] args = Environment.GetCommandLineArgs();
for (int i = 0; i < args.Length - 1; i++)
{
if (args[i] != "-port")
{
continue;
}
if (!int.TryParse(args[i + 1], out int value))
{
continue;
}
if (value < 1000 || value >= 65536)
{
continue;
}
return value;
}
return null;
}
private string ReadLogFilePathFromCmd()
{
string[] args = Environment.GetCommandLineArgs();
for (int i = 0; i < args.Length - 2; i++)
{
if (args[i] != "-logFile")
{
continue;
}
return args[i + 1];
}
return null;
}
#endif
}
| 87 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
// Logic to initialize the board, receive the chords, determine matches, record scores, repopulate
// the board after a match, send the board for rendering, and send or receive the state of the class from the network code.
[System.Serializable]
public class Simulation
{
private readonly GameLogic _gl;
public Random.State RngState;
public int PlayerIdx;
public int[] BoardColors = new int[9];
public int[] Scores = new int[4];
public bool Playing;
public ulong Frame;
public Simulation(GameLogic gl)
{
_gl = gl;
}
public void ResetBoard()
{
if (_gl.Authoritative)
{
PlayerIdx = 0;
for (int bcNum = 0; bcNum < BoardColors.Length; bcNum++)
{
BoardColors[bcNum] = Random.Range(0, 7);
}
}
}
public void ResetScores()
{
if (_gl.Authoritative)
{
for (int scNum = 0; scNum < Scores.Length; scNum++)
{
Scores[scNum] = _gl.IsConnected(scNum) ? 0 : -1;
}
}
}
public void ResetScore(int playerIdx)
{
Scores[playerIdx] = -1;
}
public void ZeroScore(int playerIdx)
{
Scores[playerIdx] = 0;
}
public bool SimulateOnInput(int playerIdx, Chord inputChord)
{
_gl.Log.WriteLine("SimulateOnInput()");
Debug.Assert(inputChord.Keys.Length == BoardColors.Length);
// test for a match
bool match = false;
int matchColor = -1; // don't know yet
for (int bcNum = 0; bcNum < BoardColors.Length; bcNum++)
{
if (inputChord.Keys[bcNum])
{
if (matchColor == -1)
{
matchColor = BoardColors[bcNum];
}
else
{
if (BoardColors[bcNum] == matchColor)
{
match = true;
}
else
{
match = false;
break;
}
}
}
}
if (match)
{
// yes, a match!
for (int bcNum = 0; bcNum < BoardColors.Length; bcNum++)
{
if (inputChord.Keys[bcNum])
{
BoardColors[bcNum] = Random.Range(0, 7);
Scores[playerIdx]++;
}
}
}
return match;
}
public string Serialize(int playerIdx)
{
PlayerIdx = playerIdx;
RngState = Random.state;
return JsonUtility.ToJson(this);
}
public bool Deserialize(string json)
{
bool priorPlayingState = Playing;
if (!string.IsNullOrEmpty(json))
{
JsonUtility.FromJsonOverwrite(json, this);
Random.state = RngState;
_gl.Status.PlayerIdx = PlayerIdx;
}
return priorPlayingState;
}
}
| 127 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
public class Status
{
private readonly GameLogic _gl;
private bool _gameliftStatus = false;
private int _numConnected = 0;
private int _playerIdx = 0;
private bool _connected = false;
public Status(GameLogic gl)
{
_gl = gl;
}
public void Start()
{
SetStatusText();
}
public bool GameliftStatus
{
set
{
if (_gameliftStatus == value)
{
return;
}
_gameliftStatus = value;
SetStatusText();
}
get => _gameliftStatus;
}
public int NumConnected
{
set
{
if (_numConnected == value)
{
return;
}
_numConnected = value;
SetStatusText();
}
}
public int PlayerIdx
{
set
{
if (_playerIdx == value)
{
return;
}
_playerIdx = value;
SetStatusText();
}
}
public bool Connected
{
set
{
if (_connected == value)
{
return;
}
_connected = value;
SetStatusText();
}
}
public void SetStatusText()
{
string glt = _gameliftStatus ? "GAMELIFT | " : "LOCAL | ";
#if UNITY_SERVER
string svr = "SERVER | ";
string con = _numConnected + " CONNECTED";
#else
string svr = "CLIENT | ";
string con = _connected ? "CONNECTED " + (_playerIdx + 1) + "UP" : "DISCONNECTED";
#endif
_gl.Render.SetStatusText(svr + glt + con);
}
}
| 93 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
public static class Strings
{
public const string ErrorUnknown = "An error occured. Please try again later.";
public const string ErrorStartingGame = "Failed to find a game. Please try again later.";
}
| 9 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
[Serializable]
public struct ClientCredentials
{
public string AccessToken;
public string IdToken;
public string RefreshToken;
}
| 13 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if !UNITY_SERVER
using System.Threading;
using System.Threading.Tasks;
public class Delay
{
public virtual Task Wait(int delayMs, CancellationToken cancellationToken = default)
{
return Task.Delay(delayMs, cancellationToken);
}
}
#endif
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if !UNITY_SERVER
using System;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLift.Runtime;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.Latency.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.UserIdentityManagement.Models;
public sealed class GameLiftClient : IDisposable
{
private const int MaxConnectionRetryCount = 7;
private const int InitialConnectionDelayMs = 15000;
private const int ConnectionRetryDelayMs = 5000;
private readonly Delay _delay;
private readonly Logger _logger;
private ClientCredentials _clientCredentials;
public GameLiftCoreApi Core { get; }
public ClientCredentials ClientCredentials { get => _clientCredentials; set => _clientCredentials = value; }
public GameLiftClient(GameLiftCoreApi coreApi, Delay delay, Logger logger)
{
Core = coreApi ?? throw new ArgumentNullException(nameof(coreApi));
_delay = delay ?? throw new ArgumentNullException(nameof(delay));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public SignOutResponse SignOut()
{
SignOutResponse signOutResponse = Core.SignOut(ClientCredentials.AccessToken);
_logger.Write("Client signed out.");
return signOutResponse;
}
public async Task<(bool success, ConnectionInfo connectionInfo)> GetConnectionInfo(CancellationToken cancellationToken = default)
{
string ip = null;
int port = -1;
string playerSessionId = null;
GetLatenciesResponse latenciesResponse = await Core.GetLatencies(Core.ListAvailableRegions());
StartGameResponse startGameResponse = await Core.StartGame(ClientCredentials.IdToken, ClientCredentials.RefreshToken, latenciesResponse.RegionLatencies);
if (!startGameResponse.Success && startGameResponse.ErrorCode != ErrorCode.ConflictError)
{
return (success: false, new ConnectionInfo { IpAddress = ip, Port = port, PlayerSessionId = playerSessionId });
}
_clientCredentials.IdToken = startGameResponse.IdToken;
await _delay.Wait(InitialConnectionDelayMs, cancellationToken);
int retry = 0;
int delay = ConnectionRetryDelayMs;
while (retry < MaxConnectionRetryCount && !cancellationToken.IsCancellationRequested)
{
GetGameConnectionResponse connection = await Core.GetGameConnection(ClientCredentials.IdToken, ClientCredentials.RefreshToken);
if (!connection.Success)
{
return (success: false, new ConnectionInfo { IpAddress = ip, Port = port, PlayerSessionId = playerSessionId });
}
_clientCredentials.IdToken = connection.IdToken;
if (connection.Ready)
{
ip = connection.DnsName ?? connection.IpAddress;
port = int.Parse(connection.Port);
playerSessionId = connection.PlayerSessionId;
return (success: true, new ConnectionInfo { IpAddress = ip, Port = port, PlayerSessionId = playerSessionId });
}
await _delay.Wait(delay, cancellationToken);
retry++;
delay *= 2;
}
cancellationToken.ThrowIfCancellationRequested();
return (success: false, new ConnectionInfo { IpAddress = ip, Port = port, PlayerSessionId = playerSessionId });
}
public void Dispose()
{
SignOut();
}
}
#endif
| 96 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if !UNITY_SERVER
using System.Collections.Generic;
using System.Threading.Tasks;
using AmazonGameLift.Runtime;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.Latency.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.UserIdentityManagement.Models;
public sealed class LoggingGameLiftCoreApi : GameLiftCoreApi
{
private readonly Logger _logger = Logger.SharedInstance;
public LoggingGameLiftCoreApi(GameLiftConfiguration configuration) : base(configuration)
{
}
public override async Task<GetLatenciesResponse> GetLatencies(string[] regions)
{
GetLatenciesResponse response = await base.GetLatencies(regions);
_logger.Write($"{nameof(GameLiftCoreApi)}.{nameof(GetLatencies)} {FormatResponse(response)}");
return response;
}
public override async Task<StartGameResponse> StartGame(string idToken, string refreshToken, Dictionary<string, long> latencies)
{
StartGameResponse startGameResponse = await base.StartGame(idToken, refreshToken, latencies);
_logger.Write($"{nameof(GameLiftCoreApi)}.{nameof(StartGame)} {FormatResponse(startGameResponse)}");
return startGameResponse;
}
public override async Task<GetGameConnectionResponse> GetGameConnection(string idToken, string refreshToken)
{
GetGameConnectionResponse getGameConnectionResponse = await base.GetGameConnection(idToken, refreshToken);
_logger.Write($"{nameof(GameLiftCoreApi)}.{nameof(GetGameConnection)} ready={getGameConnectionResponse.Ready} {FormatResponse(getGameConnectionResponse)}");
return getGameConnectionResponse;
}
public override SignOutResponse SignOut(string accessToken)
{
SignOutResponse signOutResponse = base.SignOut(accessToken);
_logger.Write($"{nameof(GameLiftCoreApi)}.{nameof(SignOut)} {FormatResponse(signOutResponse)}");
return signOutResponse;
}
private string FormatResponse(Response response)
{
return $"success={response.Success}, error={response.ErrorCode}, message={response.ErrorMessage}";
}
}
#endif
| 57 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if !UNITY_SERVER
using System;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class NetworkClient
{
public const string LocalHost = "localhost";
private readonly GameLogic _gl;
private TcpClient _client = null;
public bool Authoritative => _client == null;
public NetworkClient(GameLogic gl)
{
_gl = gl;
}
public void Update()
{
if (_client == null)
{
return;
}
string[] messages = NetworkProtocol.Receive(_client);
foreach (string msgStr in messages)
{
_gl.Log.WriteLine("Msg rcvd: " + msgStr);
HandleMessage(msgStr);
}
}
public bool TryConnect(ConnectionInfo connectionInfo)
{
try
{
_client = new TcpClient(connectionInfo.IpAddress, connectionInfo.Port);
string msgStr = "CONNECT:" + connectionInfo.Serialize();
NetworkProtocol.Send(_client, msgStr);
return true;
}
catch (ArgumentNullException e)
{
_client = null;
_gl.Log.WriteLine(":( CONNECT TO SERVER " + connectionInfo.IpAddress + " FAILED: " + e);
return false;
}
catch (SocketException e) // server not available
{
_client = null;
if (connectionInfo.IpAddress == LocalHost)
{
_gl.Log.WriteLine(":) CONNECT TO LOCAL SERVER FAILED: PROBABLY NO LOCAL SERVER RUNNING, TRYING GAMELIFT");
}
else
{
_gl.Log.WriteLine(":( CONNECT TO SERVER " + connectionInfo.IpAddress + "FAILED: " + e + " (ARE YOU ON THE *AMAZON*INTERNAL*NETWORK*?)");
}
return false;
}
}
public void Ready()
{
if (_client == null)
{
return;
}
string msgStr = "READY:";
try
{
NetworkProtocol.Send(_client, msgStr);
}
catch (SocketException e)
{
HandleDisconnect();
_gl.Log.WriteLine("Ready failed: Disconnected" + e);
}
}
public void TransmitInput(int playerIdx, Chord chord)
{
if (_client == null)
{
return;
}
string msgStr = "INPUT:" + chord.Serialize();
try
{
NetworkProtocol.Send(_client, msgStr);
}
catch (SocketException e)
{
HandleDisconnect();
_gl.Log.WriteLine("TransmitInput failed: Disconnected" + e);
}
}
public void End()
{
if (_client == null)
{
return;
}
string msgStr = "END:";
try
{
NetworkProtocol.Send(_client, msgStr);
}
catch (SocketException e)
{
HandleDisconnect();
_gl.Log.WriteLine("End failed: Disconnected" + e);
}
}
public void Disconnect()
{
if (_client == null)
{
return;
}
string msgStr = "DISCONNECT:";
try
{
NetworkProtocol.Send(_client, msgStr);
}
finally
{
HandleDisconnect();
}
}
private void HandleMessage(string msgStr)
{
// parse message and pass json string to relevant handler for deserialization
//gl.log.WriteLine("Msg rcvd:" + msgStr);
string delimiter = ":";
string json = msgStr.Substring(msgStr.IndexOf(delimiter) + delimiter.Length);
if (msgStr[0] == 'S')
{
HandleState(json);
}
if (msgStr[0] == 'L')
{
HandleLog(json);
}
if (msgStr[0] == 'R')
{
HandleReject();
}
if (msgStr[0] == 'D')
{
HandleDisconnect();
}
}
private void HandleState(string msgStr)
{
_gl.SetState(msgStr);
}
private void HandleLog(string msgStr)
{
_gl.Log.WriteLine(msgStr);
}
private void HandleReject()
{
_gl.Log.WriteLine(":( CONNECT TO SERVER REJECTED: game already full");
NetworkStream stream = _client.GetStream();
stream.Close();
_client.Close();
_client = null;
_gl.ClientConnected = false;
}
private void HandleDisconnect()
{
_gl.EndGame();
if (_client.Connected)
{
NetworkStream stream = _client.GetStream();
stream.Close();
}
_client.Close();
_client = null;
_gl.ClientConnected = false;
}
}
#endif
| 218 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if UNITY_SERVER
using System;
using System.Collections.Generic;
using Aws.GameLift;
using Aws.GameLift.Server;
using UnityEngine;
public class GameLiftServer
{
private readonly GameLift _gl;
private readonly Logger _logger;
private bool _gameLiftRequestedTermination = false;
private int _port;
private bool _isConnected;
private string _logFilePath;
public GameLiftServer(GameLift gl, Logger logger)
{
_gl = gl ?? throw new ArgumentNullException(nameof(gl));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
// The port must be in the range of open ports for the fleet
public void Start(int port, string logFilePath = null)
{
_logFilePath = logFilePath;
_port = port;
string sdkVersion = GameLiftServerAPI.GetSdkVersion().Result;
_logger.Write(":) SDK VERSION: " + sdkVersion);
try
{
GenericOutcome initOutcome = GameLiftServerAPI.InitSDK();
if (initOutcome.Success)
{
_logger.Write(":) SERVER IS IN A GAMELIFT FLEET");
ProcessReady();
}
else
{
SetConnected(false);
_logger.Write(":( SERVER NOT IN A FLEET. GameLiftServerAPI.InitSDK() returned " + Environment.NewLine + initOutcome.Error.ErrorMessage);
}
}
catch (Exception e)
{
_logger.Write(":( SERVER NOT IN A FLEET. GameLiftServerAPI.InitSDK() exception " + Environment.NewLine + e.Message);
}
}
public void TerminateGameSession(bool processEnding)
{
if (_gameLiftRequestedTermination)
{
// don't terminate game session if gamelift initiated process termination, just exit.
Environment.Exit(0);
}
try
{
GenericOutcome outcome = GameLiftServerAPI.TerminateGameSession();
if (outcome.Success)
{
_logger.Write(":) GAME SESSION TERMINATED");
if (processEnding)
{
ProcessEnding();
}
else
{
ProcessReady();
}
}
else
{
_logger.Write(":( GAME SESSION TERMINATION FAILED. TerminateGameSession() returned " + outcome.Error.ToString());
}
}
catch (Exception e)
{
_logger.Write(":( GAME SESSION TERMINATION FAILED. TerminateGameSession() exception " + Environment.NewLine + e.Message);
}
}
public bool AcceptPlayerSession(string playerSessionId)
{
try
{
GenericOutcome outcome = GameLiftServerAPI.AcceptPlayerSession(playerSessionId);
if (outcome.Success)
{
_logger.Write(":) Accepted Player Session: " + playerSessionId);
return true;
}
else
{
_logger.Write(":( ACCEPT PLAYER SESSION FAILED. AcceptPlayerSession() returned " + outcome.Error.ToString());
return false;
}
}
catch (Exception e)
{
_logger.Write(":( ACCEPT PLAYER SESSION FAILED. AcceptPlayerSession() exception " + Environment.NewLine + e.Message);
return false;
}
}
public bool RemovePlayerSession(string playerSessionId)
{
try
{
GenericOutcome outcome = GameLiftServerAPI.RemovePlayerSession(playerSessionId);
if (outcome.Success)
{
_logger.Write(":) Removed Player Session: " + playerSessionId);
return true;
}
else
{
_logger.Write(":( REMOVE PLAYER SESSION FAILED. RemovePlayerSession() returned " + outcome.Error.ToString());
return false;
}
}
catch (Exception e)
{
_logger.Write(":( REMOVE PLAYER SESSION FAILED. RemovePlayerSession() exception " + Environment.NewLine + e.Message);
return false;
}
}
private void ProcessReady()
{
try
{
ProcessParameters processParams = CreateProcessParameters();
GenericOutcome processReadyOutcome = GameLiftServerAPI.ProcessReady(processParams);
SetConnected(processReadyOutcome.Success);
if (processReadyOutcome.Success)
{
_logger.Write(":) PROCESSREADY SUCCESS.");
}
else
{
_logger.Write(":( PROCESSREADY FAILED. ProcessReady() returned " + processReadyOutcome.Error.ToString());
}
}
catch (Exception e)
{
_logger.Write(":( PROCESSREADY FAILED. ProcessReady() exception " + Environment.NewLine + e.Message);
}
}
private ProcessParameters CreateProcessParameters()
{
var logParameters = new LogParameters();
if (_logFilePath != null)
{
logParameters.LogPaths = new List<string> { _logFilePath };
}
return new ProcessParameters(
onStartGameSession: gameSession =>
{
_logger.Write(":) GAMELIFT SESSION REQUESTED"); //And then do stuff with it maybe.
try
{
GenericOutcome outcome = GameLiftServerAPI.ActivateGameSession();
if (outcome.Success)
{
_logger.Write(":) GAME SESSION ACTIVATED");
}
else
{
_logger.Write(":( GAME SESSION ACTIVATION FAILED. ActivateGameSession() returned " + outcome.Error.ToString());
}
}
catch (Exception e)
{
_logger.Write(":( GAME SESSION ACTIVATION FAILED. ActivateGameSession() exception " + Environment.NewLine + e.Message);
}
},
onProcessTerminate: () =>
{
_logger.Write(":| GAMELIFT PROCESS TERMINATION REQUESTED (OK BYE)");
_gameLiftRequestedTermination = true;
_gl.TerminateServer();
},
onHealthCheck: () =>
{
_logger.Write(":) GAMELIFT HEALTH CHECK REQUESTED (HEALTHY)");
return true;
},
_port, // tell the GameLift service which port to connect to this process on.
// unless we manage this there can only be one process per server.
logParameters);
}
private void ProcessEnding()
{
try
{
GenericOutcome outcome = GameLiftServerAPI.ProcessEnding();
if (outcome.Success)
{
_logger.Write(":) PROCESSENDING");
}
else
{
_logger.Write(":( PROCESSENDING FAILED. ProcessEnding() returned " + outcome.Error.ToString());
}
}
catch (Exception e)
{
_logger.Write(":( PROCESSENDING FAILED. ProcessEnding() exception " + Environment.NewLine + e.Message);
}
}
private void SetConnected(bool value)
{
if (_isConnected == value)
{
return;
}
_isConnected = value;
_gl.ConnectionChangedEvent?.Invoke(value);
}
}
#endif
| 245 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
#if UNITY_SERVER
using System;
using System.Net;
using System.Net.Sockets;
public class NetworkServer
{
private readonly GameLogic _gl;
private readonly TcpListener _listener;
private readonly TcpClient[] _clients = { null, null, null, null };
private readonly bool[] _ready = { false, false, false, false };
private readonly string[] _playerSessionIds = { null, null, null, null };
public NetworkServer(GameLogic gl, int port)
{
_gl = gl;
_listener = new TcpListener(IPAddress.Any, port);
_listener.Start();
}
public void Update()
{
// Are there any new connections pending?
if (_listener.Pending())
{
TcpClient client = _listener.AcceptTcpClient();
for (int x = 0; x < 4; x++)
{
if (_clients[x] == null)
{
_clients[x] = client;
UpdateNumConnected();
_gl.Log.WriteLine("Connection accepted: playerIdx " + x + " joined");
return;
}
}
// game already full, reject the connection
_gl.Log.WriteLine("Connection rejected: game already full.");
try
{
NetworkProtocol.Send(client, "REJECTED: game already full");
}
catch (SocketException) { }
}
// Have we received an input event message from any client?
for (int x = 0; x < 4; x++)
{
if (_clients[x] == null)
{
continue;
}
string[] messages = NetworkProtocol.Receive(_clients[x]);
foreach (string msgStr in messages)
{
_gl.Log.WriteLine("Msg rcvd from playerIdx " + x + " Msg: " + msgStr);
HandleMessage(x, msgStr);
}
}
}
public void Disconnect()
{
// warn clients
TransmitMessage("DISCONNECT:");
// disconnect connections
for (int x = 0; x < 4; x++)
{
HandleDisconnect(x);
}
// end listener
_listener.Stop();
// warn GameLift
if (_gl.GameLift != null && _gl.GameLift.IsConnected)
{
_gl.GameLift.TerminateGameSession(true);
}
// process is terminating so no other state cleanup required
}
public void TransmitLog(string msgStr)
{
TransmitMessage("LOG:" + msgStr);
}
public void TransmitState()
{
// update the state of all players
for (int x = 0; x < 4; x++)
{
string msgStr = "STATE:" + _gl.GetState(x);
Send(msgStr, x, nameof(TransmitState));
}
}
private void TransmitMessage(string msgStr)
{
// send the same message to all players
for (int x = 0; x < 4; x++)
{
Send(msgStr, x, nameof(TransmitMessage));
}
}
private void Send(string message, int playerIndex, string operationName)
{
try
{
NetworkProtocol.Send(_clients[playerIndex], message);
}
catch (Exception e) when (e is SocketException || e is InvalidOperationException)
{
HandleDisconnect(playerIndex);
_gl.Log.WriteLine($"{operationName} failed: Disconnected. " + e);
}
}
private void HandleMessage(int playerIdx, string msgStr)
{
// parse message and pass json string to relevant handler for deserialization
_gl.Log.WriteLine("Msg rcvd from player " + playerIdx + ":" + msgStr);
string delimiter = ":";
string json = msgStr.Substring(msgStr.IndexOf(delimiter) + delimiter.Length);
if (msgStr[0] == 'C')
{
HandleConnect(playerIdx, json);
}
if (msgStr[0] == 'R')
{
HandleReady(playerIdx);
}
if (msgStr[0] == 'I')
{
HandleInput(playerIdx, json);
}
if (msgStr[0] == 'E')
{
HandleEnd();
}
if (msgStr[0] == 'D')
{
HandleDisconnect(playerIdx);
}
}
private void HandleConnect(int playerIdx, string json)
{
_gl.Log.WriteLine("CONNECT: player index " + playerIdx);
_gl.ZeroScore(playerIdx);
var connectionInfo = ConnectionInfo.CreateFromSerial(json);
if (!ValidateConnectionRequest(connectionInfo))
{
HandleConnectionValidationFailure(playerIdx);
} else
{
_playerSessionIds[playerIdx] = connectionInfo.PlayerSessionId;
TransmitState();
}
}
private void HandleReady(int playerIdx)
{
// start the game once all connected clients have requested to start (RETURN key)
_gl.Log.WriteLine("READY:");
_ready[playerIdx] = true;
for (int x = 0; x < 4; x++)
{
if (_clients[x] != null && _ready[x] == false)
{
return; // a client is not ready
}
}
_gl.StartGame();
}
private void HandleInput(int playerIdx, string json)
{
// simulate the input then respond to all players with the current state
_gl.Log.WriteLine("INPUT:" + json);
var inputChord = Chord.CreateFromSerial(json);
_gl.InputEvent(playerIdx, inputChord);
}
private void HandleEnd()
{
// end the game at the request of any client (ESC key)
_gl.Log.WriteLine("END:");
for (int x = 0; x < 4; x++)
{
_ready[x] = false; // all clients end now.
}
_gl.EndGame();
if (_gl.GameLift != null && _gl.GameLift.IsConnected)
{
_gl.GameLift.TerminateGameSession(false);
}
}
private void HandleDisconnect(int playerIdx)
{
DisconnectPlayer(playerIdx);
// if that was the last client to leave, then end the game.
for (int x = 0; x < 4; x++)
{
if (_clients[x] != null)
{
return; // a client is still attached
}
}
HandleEnd();
}
private void DisconnectPlayer(int playerIdx)
{
_gl.Log.WriteLine("DISCONNECT: Player " + playerIdx);
// Tell GameLift the player has disconnected
if (_playerSessionIds[playerIdx] != null)
{
_gl.GameLift.RemovePlayerSession(_playerSessionIds[playerIdx]);
_playerSessionIds[playerIdx] = null;
}
// remove the client and close the connection
TcpClient client = _clients[playerIdx];
if (client != null)
{
NetworkStream stream = client.GetStream();
stream.Close();
client.Close();
_clients[playerIdx] = null;
}
// clean up the game state
_gl.ResetScore(playerIdx);
UpdateNumConnected();
}
public bool IsConnected(int playerIdx)
{
return _clients[playerIdx] != null;
}
private void UpdateNumConnected()
{
int count = 0;
for (int x = 0; x < 4; x++)
{
if (_clients[x] != null)
{
count++;
}
}
_gl.Status.NumConnected = count;
}
private bool ValidateConnectionRequest(ConnectionInfo connectionInfo)
{
_gl.Log.WriteLine("Received Connection Request: " + connectionInfo);
// Consider the Connection Validated if the GameLift AcceptPlayerSession call suceeds
return _gl.GameLift.AcceptPlayerSession(connectionInfo.PlayerSessionId);
}
private void HandleConnectionValidationFailure(int playerIdx)
{
// Tell Client to Disconnect
Send("DISCONNECT", playerIdx, nameof(HandleConnectionValidationFailure));
_gl.Log.WriteLine("Connection Validation Failed for player " + playerIdx
+ ". Verify the provided PlayerSessionId is correct.");
HandleDisconnect(playerIdx);
}
}
#endif
| 302 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using AmazonGameLift.Runtime;
using UnityEngine;
using UnityEngine.UI;
[DisallowMultipleComponent]
public sealed class ClientSettingsView : MonoBehaviour
{
[SerializeField]
private Text _text;
[SerializeField]
private GameLiftClientSettings _gameLiftSettings;
#if !UNITY_SERVER
private void Start()
{
string message = $"Local Testing Mode: {_gameLiftSettings.IsLocalTest}\n";
if (_gameLiftSettings.IsLocalTest)
{
message += $"GameLift Local URL: {_gameLiftSettings.LocalUrl}\n" +
$"GameLift Local Port: {_gameLiftSettings.LocalPort}\n";
}
else
{
message += $"AWS Region: {_gameLiftSettings.AwsRegion}\n" +
$"Cognito User Pool Client ID: {_gameLiftSettings.UserPoolClientId}\n" +
$"API Gateway URL: {_gameLiftSettings.ApiGatewayUrl}\n";
}
_text.text = message;
}
#endif
}
| 38 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
using UnityEngine.UI;
public sealed class ConfirmationCodeScreen : FormScreen<ConfirmationCodeScreen.SubmitDelegate>
{
public delegate void SubmitDelegate(string code);
[SerializeField]
private InputField _codeField;
internal override bool CheckCanSubmit()
{
return !string.IsNullOrEmpty(_codeField.text);
}
protected override void Submit(SubmitDelegate onSubmit)
{
onSubmit(_codeField.text);
}
protected override void Clear()
{
base.Clear();
_codeField.text = string.Empty;
}
}
| 30 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
public sealed class ConfirmationSuccessScreen : FormScreen<ConfirmationSuccessScreen.SubmitDelegate>
{
public delegate void SubmitDelegate();
internal override bool CheckCanSubmit()
{
return true;
}
protected override void Submit(SubmitDelegate onSubmit)
{
onSubmit();
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.UI;
public abstract class FormScreen<TSubmitDelegate> : GameScreen
{
[SerializeField]
private GameObject _spinner;
[SerializeField]
private Button _submitButton;
[SerializeField]
private Text _submitResultText;
[CanBeNull]
private TSubmitDelegate _onSubmit;
protected override void Awake()
{
base.Awake();
_submitResultText.text = string.Empty;
_submitButton.interactable = false;
}
public void SetSubmitAction(TSubmitDelegate onSubmit)
{
_onSubmit = onSubmit;
}
public void SetResultText(string message)
{
_submitResultText.text = message;
}
[UsedImplicitly]
public void Validate()
{
_submitButton.interactable = CheckCanSubmit();
}
[UsedImplicitly]
public void Submit()
{
if (!CheckCanSubmit() || _onSubmit == null)
{
return;
}
Submit(_onSubmit);
}
internal abstract bool CheckCanSubmit();
protected abstract void Submit(TSubmitDelegate onSubmit);
protected override void OnInteractable(bool value)
{
base.OnInteractable(value);
if (_spinner)
{
_spinner.SetActive(!value);
}
}
protected override void OnShown()
{
base.OnShown();
Clear();
Validate();
}
protected override void OnHiding()
{
base.OnHiding();
Clear();
}
protected virtual void Clear()
{
SetResultText(string.Empty);
}
}
| 88 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
using UnityEngine.EventSystems;
[DisallowMultipleComponent]
public abstract class GameScreen : UIBehaviour
{
[SerializeField]
private CanvasGroup _rootCanvasGroup;
protected override void Awake()
{
base.Awake();
Hide();
}
public void Show()
{
if (!this)
{
return;
}
gameObject.SetActive(true);
SetInteractable(true);
OnShown();
}
public void Hide()
{
if (!this)
{
return;
}
OnHiding();
gameObject.SetActive(false);
}
public void SetInteractable(bool value)
{
if (!this)
{
return;
}
_rootCanvasGroup.interactable = value;
OnInteractable(value);
}
protected virtual void OnInteractable(bool value) { }
protected virtual void OnShown() { }
protected virtual void OnHiding() { }
}
| 59 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.UI;
public sealed class SignInScreen : FormScreen<SignInScreen.SubmitDelegate>
{
public delegate void SubmitDelegate(string email, string password);
[SerializeField]
private InputField _emailField;
[SerializeField]
private InputField _passwordField;
[SerializeField]
private Text _hintText;
[CanBeNull]
private Action _onShowSignUp;
[UsedImplicitly]
public void ShowSignUp()
{
_onShowSignUp?.Invoke();
}
internal override bool CheckCanSubmit()
{
return !string.IsNullOrEmpty(_emailField.text)
&& !string.IsNullOrEmpty(_passwordField.text);
}
internal void SetShowSignUpAction(Action onShowSignUp)
{
_onShowSignUp = onShowSignUp;
}
internal void SetHint(string hint)
{
_hintText.text = hint;
}
protected override void Submit(SubmitDelegate onSubmit)
{
onSubmit(_emailField.text, _passwordField.text);
}
protected override void Clear()
{
base.Clear();
_emailField.text = string.Empty;
_passwordField.text = string.Empty;
}
}
| 59 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
using UnityEngine.UI;
public sealed class SignUpScreen : FormScreen<SignUpScreen.SubmitDelegate>
{
public delegate void SubmitDelegate(string email, string password);
[SerializeField]
private InputField _emailField;
[SerializeField]
private InputField _passwordField;
[SerializeField]
private int _minPasswordLength = 8;
internal override bool CheckCanSubmit()
{
return !string.IsNullOrEmpty(_emailField.text)
&& !string.IsNullOrEmpty(_passwordField.text)
&& _passwordField.text.Length >= _minPasswordLength;
}
protected override void Submit(SubmitDelegate onSubmit)
{
onSubmit(_emailField.text, _passwordField.text);
}
protected override void Clear()
{
base.Clear();
_emailField.text = string.Empty;
_passwordField.text = string.Empty;
}
}
| 39 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
public sealed class StartGameScreen : FormScreen<StartGameScreen.SubmitDelegate>
{
public delegate void SubmitDelegate();
internal override bool CheckCanSubmit()
{
return true;
}
protected override void Submit(SubmitDelegate onSubmit)
{
onSubmit();
}
}
| 18 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading.Tasks;
using NUnit.Framework;
namespace SampleTests.Unit
{
public static class AssertAsync
{
public delegate Task AsyncTestDelegate();
// https://forum.unity.com/threads/can-i-replace-upgrade-unitys-nunit.488580/
public static TActual ThrowsAsync<TActual>(AsyncTestDelegate code, string message = "", params object[] args) where TActual : Exception
{
return Assert.Throws<TActual>(() =>
{
try
{
code.Invoke().Wait(); // Will wrap any exceptions in an AggregateException
}
catch (AggregateException e)
{
if (e.InnerException is null)
{
throw;
}
throw e.InnerException; // Throw the unwrapped exception
}
}, message, args);
}
}
}
| 36 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections;
using System.Threading.Tasks;
namespace SampleTests.Unit
{
public static class CoroutineTaskExtensions
{
public static IEnumerator AsCoroutine(this Task task)
{
if (task is null)
{
throw new ArgumentNullException(nameof(task));
}
while (!task.IsCompleted)
{
yield return null;
}
task.GetAwaiter().GetResult();
}
}
}
| 29 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#if !UNITY_SERVER
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLift.Runtime;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.Latency.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using Moq.Language;
using NUnit.Framework;
using UnityEngine.TestTools;
namespace SampleTests.Unit
{
public sealed class GameLiftClientTests
{
private readonly ClientCredentials _credentials = new ClientCredentials
{
RefreshToken = "RefreshToken",
AccessToken = "AccessToken",
IdToken = "IdToken"
};
private readonly GameLiftConfiguration _gameLiftConfiguration = new GameLiftConfiguration
{
ApiGatewayEndpoint = "TestApiGatewayEndpoint",
AwsRegion = "eu-central-1",
UserPoolClientId = "TestUserPoolClientId",
};
private readonly Logger _logger = new Mock<Logger>().Object;
[UnityTest]
public IEnumerator GetConnectionInfo_WhenStartGameFails_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var delayMock = new Mock<Delay>();
var coreApiMock = new Mock<GameLiftCoreApi>(_gameLiftConfiguration);
SetUpCoreApiMockStartGame(coreApiMock, success: false);
SetUpCoreApiMockGetLatencies(coreApiMock, success: true);
var underTest = new GameLiftClient(coreApiMock.Object, delayMock.Object, _logger)
{
ClientCredentials = _credentials
};
// Act
(bool success, ConnectionInfo _) = await underTest.GetConnectionInfo();
// Assert
coreApiMock.Verify();
Assert.IsFalse(success);
}
}
[UnityTest]
public IEnumerator GetConnectionInfo_WhenStartGameSucceedsAndGetGameConnectionSucceedsAndNotReady_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var delayMock = new Mock<Delay>();
SetUpDelayMockWait(delayMock);
var coreApiMock = new Mock<GameLiftCoreApi>(_gameLiftConfiguration);
SetUpCoreApiMockStartGame(coreApiMock, success: true);
SetUpCoreApiMockGetLatencies(coreApiMock, success: true);
GetGameConnectionResponse connectionResponse = Response.Ok(new GetGameConnectionResponse
{
IdToken = _credentials.IdToken,
});
coreApiMock.Setup(target => target.GetGameConnection(_credentials.IdToken, _credentials.RefreshToken))
.Returns(Task.FromResult(connectionResponse))
.Verifiable();
var underTest = new GameLiftClient(coreApiMock.Object, delayMock.Object, _logger)
{
ClientCredentials = _credentials
};
// Act
(bool success, ConnectionInfo connectionInfo) = await underTest.GetConnectionInfo();
// Assert
coreApiMock.Verify();
delayMock.Verify();
Assert.IsFalse(success);
}
}
private static readonly TestCaseData[] s_getConnectionInfoTestCases = new[]
{
new TestCaseData(0, true).Returns(null),
new TestCaseData(1, true).Returns(null),
new TestCaseData(2, true).Returns(null),
new TestCaseData(3, true).Returns(null),
new TestCaseData(4, true).Returns(null),
new TestCaseData(5, true).Returns(null),
new TestCaseData(6, true).Returns(null),
new TestCaseData(7, false).Returns(null),
new TestCaseData(8, false).Returns(null),
new TestCaseData(10, false).Returns(null),
};
[TestCaseSource(nameof(s_getConnectionInfoTestCases))]
[UnityTest]
public IEnumerator GetConnectionInfo_WhenGetGameConnectionSucceedsAndReadyAfterNTries_SuccessIsExpected(int failCount, bool success)
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testIp = "testIp";
const string testPort = "8080";
const string testPlayerSessionId = "psess-123";
var delayMock = new Mock<Delay>();
SetUpDelayMockWait(delayMock);
var coreApiMock = new Mock<GameLiftCoreApi>(_gameLiftConfiguration);
SetUpCoreApiMockStartGame(coreApiMock, success: true);
SetUpCoreApiMockGetLatencies(coreApiMock, success: true);
GetGameConnectionResponse connectionResponse = Response.Ok(new GetGameConnectionResponse
{
IdToken = _credentials.IdToken,
IpAddress = testIp,
Port = testPort,
PlayerSessionId = testPlayerSessionId,
Ready = false,
});
GetGameConnectionResponse connectionReadyResponse = Response.Ok(new GetGameConnectionResponse
{
IdToken = _credentials.IdToken,
IpAddress = testIp,
Port = testPort,
PlayerSessionId = testPlayerSessionId,
Ready = true,
});
ISetupSequentialResult<Task<GetGameConnectionResponse>> sequence = coreApiMock
.SetupSequence(target => target.GetGameConnection(_credentials.IdToken, _credentials.RefreshToken));
for (int i = 0; i < failCount; i++)
{
sequence = sequence.Returns(Task.FromResult(connectionResponse));
}
sequence = sequence.Returns(Task.FromResult(connectionReadyResponse));
var underTest = new GameLiftClient(coreApiMock.Object, delayMock.Object, _logger)
{
ClientCredentials = _credentials
};
// Act
(bool success, ConnectionInfo connectionInfo) info = await underTest.GetConnectionInfo();
// Assert
coreApiMock.Verify();
delayMock.Verify();
Assert.AreEqual(success, info.success);
if (success)
{
Assert.AreEqual(testIp, info.connectionInfo.IpAddress);
Assert.AreEqual(testPort, info.connectionInfo.Port.ToString());
Assert.AreEqual(testPlayerSessionId, info.connectionInfo.PlayerSessionId);
}
}
}
[UnityTest]
public IEnumerator GetConnectionInfo_WhenGetGameConnectionSucceedsAndReady_DnsNameExpected()
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testDns = "test.dns";
const string testIp = "testIp";
const string testPort = "8080";
var delayMock = new Mock<Delay>();
SetUpDelayMockWait(delayMock);
var coreApiMock = new Mock<GameLiftCoreApi>(_gameLiftConfiguration);
SetUpCoreApiMockStartGame(coreApiMock, success: true);
SetUpCoreApiMockGetLatencies(coreApiMock, success: true);
GetGameConnectionResponse connectionReadyResponse = Response.Ok(new GetGameConnectionResponse
{
IdToken = _credentials.IdToken,
DnsName = testDns,
IpAddress = testIp,
Port = testPort,
Ready = true,
});
coreApiMock.Setup(target => target.GetGameConnection(_credentials.IdToken, _credentials.RefreshToken))
.Returns(Task.FromResult(connectionReadyResponse))
.Verifiable();
var underTest = new GameLiftClient(coreApiMock.Object, delayMock.Object, _logger)
{
ClientCredentials = _credentials
};
// Act
(bool success, ConnectionInfo connectionInfo) info = await underTest.GetConnectionInfo();
// Assert
coreApiMock.Verify();
delayMock.Verify();
Assert.AreEqual(testDns, info.connectionInfo.IpAddress);
}
}
[Test]
public void GetConnectionInfo_WhenStartGameSucceedsAndCancelled_ThrowsException()
{
var delayMock = new Mock<Delay>();
SetUpDelayMockWait(delayMock);
var coreApiMock = new Mock<GameLiftCoreApi>(_gameLiftConfiguration);
SetUpCoreApiMockStartGame(coreApiMock, success: true);
SetUpCoreApiMockGetLatencies(coreApiMock, success: true);
GetGameConnectionResponse connectionResponse = Response.Ok(new GetGameConnectionResponse
{
IdToken = _credentials.IdToken,
});
coreApiMock.Setup(target => target.GetGameConnection(_credentials.IdToken, _credentials.RefreshToken))
.Returns(Task.FromResult(connectionResponse))
.Verifiable();
var underTest = new GameLiftClient(coreApiMock.Object, delayMock.Object, _logger)
{
ClientCredentials = _credentials
};
var cts = new CancellationTokenSource();
cts.Cancel();
// Act
AssertAsync.ThrowsAsync<TaskCanceledException>(async () => await underTest.GetConnectionInfo(cts.Token));
}
private void SetUpDelayMockWait(Mock<Delay> delayMock)
{
delayMock.Setup(target => target.Wait(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask)
.Verifiable();
}
private void SetUpCoreApiMockStartGame(Mock<GameLiftCoreApi> coreApiMock, bool success)
{
StartGameResponse okResponse = Response.Ok(new StartGameResponse
{
IdToken = _credentials.IdToken
});
StartGameResponse startGameResponse = success ? okResponse : Response.Fail(new StartGameResponse());
coreApiMock.Setup(target => target.StartGame(_credentials.IdToken, _credentials.RefreshToken, It.IsAny<Dictionary<string, long>>()))
.Returns(Task.FromResult(startGameResponse))
.Verifiable();
}
private void SetUpCoreApiMockGetLatencies(Mock<GameLiftCoreApi> coreApiMock, bool success)
{
GetLatenciesResponse okResponse = Response.Ok(new GetLatenciesResponse
{
RegionLatencies = new Dictionary<string, long> { }
});
GetLatenciesResponse startGameResponse = success ? okResponse : Response.Fail(new GetLatenciesResponse());
coreApiMock.Setup(target => target.GetLatencies(It.IsAny<string[]>()))
.Returns(Task.FromResult(startGameResponse))
.Verifiable();
}
}
}
#endif
| 296 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
namespace SampleTests.UI
{
public static class AssetPaths
{
public const string GameLiftClientSettings = "Assets/Settings/GameLiftClientSettings.asset";
}
}
| 11 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
namespace SampleTests.UI
{
internal sealed class AwsTestIdentity
{
private const string TestPass = "S1mplep@ss";
private readonly AmazonCognitoIdentityProviderClient _amazonCognitoIdentityProvider;
private readonly TestSettings _settings;
public string Email { get; private set; }
public string Password => TestPass;
public AwsTestIdentity(TestSettings settings)
{
_settings = settings;
var regionEndpoint = Amazon.RegionEndpoint.GetBySystemName(settings.Region);
_amazonCognitoIdentityProvider = new AmazonCognitoIdentityProviderClient(settings.AccessKey, settings.SecretKey, regionEndpoint);
}
public void CreateTestUser()
{
string timestamp = DateTime.UtcNow.ToBinary().ToString();
Email = $"valid.email{timestamp}@mail.com";
}
public void SignUpTestUser()
{
if (Email == null)
{
CreateTestUser();
}
_amazonCognitoIdentityProvider.AdminCreateUser(new AdminCreateUserRequest
{
UserPoolId = _settings.UserPoolId,
Username = Email,
TemporaryPassword = TestPass
});
_amazonCognitoIdentityProvider.AdminSetUserPassword(new AdminSetUserPasswordRequest
{
UserPoolId = _settings.UserPoolId,
Username = Email,
Password = TestPass,
Permanent = true
});
}
public void DeleteTestUser()
{
if (Email == null)
{
return;
}
try
{
_amazonCognitoIdentityProvider.AdminDeleteUser(new AdminDeleteUserRequest
{
UserPoolId = _settings.UserPoolId,
Username = Email
});
Email = null;
}
catch (UserNotFoundException) { }
}
}
}
| 77 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using AmazonGameLift.Runtime;
using UnityEditor;
using UnityEngine;
namespace SampleTests.UI
{
internal sealed class GameLiftClientSettingsOverride
{
private GameLiftClientSettings _settings;
private GameLiftClientSettings _backupConfig;
public void SetUp(TestSettings testSettings)
{
_settings = AssetDatabase.LoadAssetAtPath<GameLiftClientSettings>(AssetPaths.GameLiftClientSettings);
_backupConfig = Object.Instantiate(_settings);
_settings.AwsRegion = testSettings.Region;
_settings.UserPoolClientId = testSettings.UserPoolClientId;
_settings.ApiGatewayUrl = testSettings.ApiGatewayEndpoint;
}
public void TearDown()
{
if (_settings != null)
{
_settings.AwsRegion = _backupConfig.AwsRegion;
_settings.UserPoolClientId = _backupConfig.UserPoolClientId;
_settings.ApiGatewayUrl = _backupConfig.ApiGatewayUrl;
}
}
}
}
| 35 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
namespace SampleTests.UI
{
public static class GameObjectNames
{
public const string SignInScreen = "Canvas/SignInScreen(Clone)";
public const string SignUpScreen = "Canvas/SignUpScreen(Clone)";
public const string ConfirmationCodeScreen = "Canvas/ConfirmationCodeScreen(Clone)";
public const string StartGameScreen = "Canvas/StartGameScreen(Clone)";
}
}
| 14 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
namespace SampleTests.UI
{
public static class PlayModeUtility
{
public static void DestroyAll<T>() where T : Component
{
T[] oldObjects = Object.FindObjectsOfType<T>();
foreach (T item in oldObjects)
{
Object.Destroy(item.gameObject);
}
}
}
}
| 21 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
namespace SampleTests.UI
{
public sealed class SignInTests
{
private const string NextSceneName = "GameScene";
private AwsTestIdentity _testIdentity;
private GameLiftClientSettingsOverride _settingsOverride;
[SetUp]
public void SetUp()
{
TestSettings settings = new TestSettingsSource().Get();
_testIdentity = new AwsTestIdentity(settings);
_testIdentity.SignUpTestUser();
_settingsOverride = new GameLiftClientSettingsOverride();
_settingsOverride.SetUp(settings);
}
[TearDown]
public void TearDown()
{
_settingsOverride?.TearDown();
_testIdentity.DeleteTestUser();
}
[UnityTest]
public IEnumerator SignInScreen_WhenNoCredentialsEnteredAndSubmitted_IsActive()
{
SceneManager.LoadScene("BootstrapScene");
const string screenName = GameObjectNames.SignInScreen;
GameObject signInScreen = null;
while (signInScreen == null)
{
signInScreen = GameObject.Find(screenName);
yield return null;
}
var submitButton = GameObject.Find(screenName + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
Assert.IsTrue(signInScreen.activeSelf);
var message = GameObject.Find(screenName + "/MessageText");
string messageText = TestInput.GetText(message);
Assert.IsTrue(string.IsNullOrEmpty(messageText));
}
[UnityTest]
public IEnumerator SignInScreen_WhenNoEmailEnteredAndSubmitted_IsActive()
{
SceneManager.LoadScene("BootstrapScene");
const string screenName = GameObjectNames.SignInScreen;
GameObject signInScreen = null;
while (signInScreen == null)
{
signInScreen = GameObject.Find(screenName);
yield return null;
}
var passwordInputField = GameObject.Find(screenName + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, "0000");
var submitButton = GameObject.Find(screenName + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
Assert.IsTrue(signInScreen.activeSelf);
var message = GameObject.Find(screenName + "/MessageText");
string messageText = TestInput.GetText(message);
Assert.IsTrue(string.IsNullOrEmpty(messageText));
}
[UnityTest]
public IEnumerator SignInScreen_WhenInvalidCredentialsEnteredAndSubmitted_IsActiveAndLogsError()
{
SceneManager.LoadScene("BootstrapScene");
const string screenName = GameObjectNames.SignInScreen;
GameObject signInScreen = null;
while (signInScreen == null)
{
signInScreen = GameObject.Find(screenName);
yield return null;
}
var emailInputField = GameObject.Find(screenName + "/EmailInputField");
yield return TestInput.EnterText(emailInputField, "invalid@mail");
var passwordInputField = GameObject.Find(screenName + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, "0000");
LogAssert.Expect(LogType.Error, "Sign-in error AWSERROR: Incorrect username or password.");
var submitButton = GameObject.Find(screenName + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
Assert.IsTrue(signInScreen.activeSelf);
var message = GameObject.Find(screenName + "/MessageText");
string messageText = TestInput.GetText(message);
Assert.AreEqual("Incorrect username or password.", messageText);
}
[UnityTest]
public IEnumerator SignInScreen_WhenValidCredentialsEnteredAndSubmitted_LoadsGame()
{
SceneManager.LoadScene("BootstrapScene");
const string screenName = GameObjectNames.SignInScreen;
GameObject signInScreen = null;
while (signInScreen == null)
{
signInScreen = GameObject.Find(screenName);
yield return null;
}
var emailInputField = GameObject.Find(screenName + "/EmailInputField");
yield return TestInput.EnterText(emailInputField, _testIdentity.Email);
var passwordInputField = GameObject.Find(screenName + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, _testIdentity.Password);
var submitButton = GameObject.Find(screenName + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
var waitForScene = new WaitForSceneLoaded(NextSceneName, timeoutSec: 5);
yield return waitForScene;
Assert.IsFalse(waitForScene.TimedOut, $"Scene {NextSceneName} was never loaded");
}
}
}
| 142 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using Amazon;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
using AmazonGameLift.Runtime;
using AmazonGameLiftPlugin.Core.Shared;
using CoreConfirmSignUpResponse = AmazonGameLiftPlugin.Core.UserIdentityManagement.Models.ConfirmSignUpResponse;
namespace SampleTests.UI
{
internal sealed class SignUpTestGameLiftCoreApi : GameLiftCoreApi
{
private readonly IAmazonCognitoIdentityProvider _amazonCognitoIdentityProvider;
private readonly string _userPoolId;
public SignUpTestGameLiftCoreApi(TestSettings testSettings, GameLiftConfiguration configuration)
: base(configuration)
{
_userPoolId = testSettings.UserPoolId;
_amazonCognitoIdentityProvider = new AmazonCognitoIdentityProviderClient(
testSettings.AccessKey, testSettings.SecretKey, RegionEndpoint.GetBySystemName(testSettings.Region));
}
public override CoreConfirmSignUpResponse ConfirmSignUp(string email, string confirmationCode)
{
_amazonCognitoIdentityProvider.AdminConfirmSignUp(new AdminConfirmSignUpRequest
{
Username = email,
UserPoolId = _userPoolId
});
return Response.Ok(new CoreConfirmSignUpResponse());
}
}
}
| 37 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System.Collections;
using System.Globalization;
using AmazonGameLift.Runtime;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
namespace SampleTests.UI
{
public sealed class SignUpTests
{
private TestSettings _settings;
private AwsTestIdentity _testIdentity;
private GameLiftClientSettingsOverride _settingsOverride;
[SetUp]
public void SetUp()
{
_settings = new TestSettingsSource().Get();
_testIdentity = new AwsTestIdentity(_settings);
_testIdentity.CreateTestUser();
_settingsOverride = new GameLiftClientSettingsOverride();
_settingsOverride.SetUp(_settings);
}
[TearDown]
public void TearDown()
{
_settingsOverride?.TearDown();
_testIdentity.DeleteTestUser();
}
[UnityTest]
public IEnumerator SignUpScreen_WhenNoCredentialsEnteredAndSubmitted_IsActive()
{
yield return GoToSignUpScreen();
GameObject screen = null;
while (screen == null)
{
screen = GameObject.Find(GameObjectNames.SignUpScreen);
yield return null;
}
SubmitAndAssertNoError(screen);
}
[UnityTest]
public IEnumerator SignUpScreen_WhenNoEmailEnteredAndSubmitted_IsActive()
{
yield return GoToSignUpScreen();
GameObject signUpScreen = null;
while (signUpScreen == null)
{
signUpScreen = GameObject.Find(GameObjectNames.SignUpScreen);
yield return null;
}
var passwordInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, _testIdentity.Password);
SubmitAndAssertNoError(signUpScreen);
}
[UnityTest]
public IEnumerator SignUpScreen_WhenInvalidEmailEnteredAndSubmitted_IsActiveAndLogsError()
{
const string testEmail = "invalid";
const string expectedError = "Username should be an email.";
_testIdentity.SignUpTestUser();
yield return GoToSignUpScreen();
GameObject signUpScreen = null;
while (signUpScreen == null)
{
signUpScreen = GameObject.Find(GameObjectNames.SignUpScreen);
yield return null;
}
var emailInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/EmailInputField");
yield return TestInput.EnterText(emailInputField, testEmail);
var passwordInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, _testIdentity.Password);
yield return SubmitAndAssertError(signUpScreen, expectedError);
}
[UnityTest]
public IEnumerator SignUpScreen_WhenNoPasswordEnteredAndSubmitted_IsActive()
{
yield return GoToSignUpScreen();
GameObject signUpScreen = null;
while (signUpScreen == null)
{
signUpScreen = GameObject.Find(GameObjectNames.SignUpScreen);
yield return null;
}
var emailInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/EmailInputField");
yield return TestInput.EnterText(emailInputField, _testIdentity.Email);
SubmitAndAssertNoError(signUpScreen);
}
[UnityTest]
public IEnumerator SignUpScreen_WhenShortPasswordEnteredAndSubmitted_IsActive()
{
const string testPassword = "1234567";
_testIdentity.DeleteTestUser();
yield return GoToSignUpScreen();
GameObject signUpScreen = null;
while (signUpScreen == null)
{
signUpScreen = GameObject.Find(GameObjectNames.SignUpScreen);
yield return null;
}
var emailInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/EmailInputField");
yield return TestInput.EnterText(emailInputField, _testIdentity.Email);
var passwordInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, testPassword);
SubmitAndAssertNoError(signUpScreen);
}
[UnityTest]
public IEnumerator SignUpScreen_WhenInvalidPasswordEnteredAndSubmitted_IsActiveAndLogsError()
{
const string testPassword = "12345678";
const string expectedError = "Password did not conform with policy: Password must have lowercase characters";
_testIdentity.DeleteTestUser();
yield return GoToSignUpScreen();
GameObject signUpScreen = null;
while (signUpScreen == null)
{
signUpScreen = GameObject.Find(GameObjectNames.SignUpScreen);
yield return null;
}
var emailInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/EmailInputField");
yield return TestInput.EnterText(emailInputField, _testIdentity.Email);
var passwordInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, testPassword);
yield return SubmitAndAssertError(signUpScreen, expectedError);
}
[UnityTest]
public IEnumerator SignUpScreen_WhenValidCredentialsEnteredAndSubmitted_ShowsSignInScreen()
{
string testCode = Random.Range(100_000, 1_000_000)
.ToString(CultureInfo.InvariantCulture);
PlayModeUtility.DestroyAll<GameLift>();
_testIdentity.DeleteTestUser();
_testIdentity.CreateTestUser();
yield return GoToSignUpScreen();
GameLift gameLift = Object.FindObjectOfType<GameLift>();
Assert.IsNotNull(gameLift);
var testConfiguration = new GameLiftConfiguration
{
AwsRegion = _settings.Region,
UserPoolClientId = _settings.UserPoolClientId,
};
var coreApi = new SignUpTestGameLiftCoreApi(_settings, testConfiguration);
var client = new GameLiftClient(coreApi, new Delay(), Logger.SharedInstance);
gameLift.OverrideClient(client);
GameObject signUpScreen = null;
while (signUpScreen == null)
{
signUpScreen = GameObject.Find(GameObjectNames.SignUpScreen);
yield return null;
}
var emailInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/EmailInputField");
yield return TestInput.EnterText(emailInputField, _testIdentity.Email);
var passwordInputField = GameObject.Find(GameObjectNames.SignUpScreen + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, _testIdentity.Password);
var submitButton = GameObject.Find(GameObjectNames.SignUpScreen + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
var waitForConfirmation = new WaitForGameObjectFound(GameObjectNames.ConfirmationCodeScreen, timeoutSec: 10f);
yield return waitForConfirmation;
Assert.IsFalse(waitForConfirmation.TimedOut, $"Object {GameObjectNames.ConfirmationCodeScreen} was never loaded");
var confirmationScreen = GameObject.Find(GameObjectNames.ConfirmationCodeScreen);
Assert.IsFalse(signUpScreen.activeSelf);
Assert.IsTrue(confirmationScreen.activeSelf);
var codeInputField = GameObject.Find(GameObjectNames.ConfirmationCodeScreen + "/CodeInputField");
yield return TestInput.EnterText(codeInputField, testCode);
submitButton = GameObject.Find(GameObjectNames.ConfirmationCodeScreen + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
var waitForSignIn = new WaitForGameObjectFound(GameObjectNames.SignInScreen, timeoutSec: 1f);
yield return waitForSignIn;
Assert.IsFalse(waitForSignIn.TimedOut, $"Object {GameObjectNames.SignInScreen} was never loaded");
var signInScreen = GameObject.Find(GameObjectNames.SignInScreen);
Assert.IsTrue(signInScreen.activeSelf);
Assert.IsFalse(signUpScreen.activeSelf);
Assert.IsFalse(confirmationScreen.activeSelf);
}
private IEnumerator GoToSignUpScreen()
{
SceneManager.LoadScene("BootstrapScene");
const string screenName = GameObjectNames.SignInScreen;
GameObject signInScreen = null;
while (signInScreen == null)
{
signInScreen = GameObject.Find(screenName);
yield return null;
}
var signUpButton = GameObject.Find(screenName + "/SignUpButton");
yield return TestInput.PressButton(signUpButton);
}
private IEnumerator SubmitAndAssertNoError(GameObject screen)
{
var submitButton = GameObject.Find(screen.name + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
var message = GameObject.Find(screen.name + "/MessageText");
string messageText = TestInput.GetText(message);
Assert.IsTrue(screen.activeSelf);
Assert.IsTrue(string.IsNullOrEmpty(messageText));
}
private IEnumerator SubmitAndAssertError(GameObject screen, string expectedError)
{
LogAssert.Expect(LogType.Error, "Sign-up error AWSERROR: " + expectedError);
var submitButton = GameObject.Find(screen.name + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
var message = GameObject.Find(screen.name + "/MessageText");
string messageText = TestInput.GetText(message);
Assert.IsTrue(screen.activeSelf);
Assert.AreEqual(expectedError, messageText);
}
}
}
| 275 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
namespace SampleTests.UI
{
public sealed class StartGameTests
{
private const string GameSceneName = "GameScene";
private AwsTestIdentity _testIdentity;
private GameLiftClientSettingsOverride _settingsOverride;
[SetUp]
public void SetUp()
{
TestSettings settings = new TestSettingsSource().Get();
_testIdentity = new AwsTestIdentity(settings);
_testIdentity.SignUpTestUser();
_settingsOverride = new GameLiftClientSettingsOverride();
_settingsOverride.SetUp(settings);
}
[TearDown]
public void TearDown()
{
_settingsOverride?.TearDown();
_testIdentity.DeleteTestUser();
}
[UnityTest]
public IEnumerator StartGame_WhenValidCredentialsEnteredAndStartGameSubmitted_LoadsGame()
{
PlayModeUtility.DestroyAll<GameLift>();
SceneManager.LoadScene("BootstrapScene");
const string screenName = GameObjectNames.SignInScreen;
GameObject signInScreen = null;
while (signInScreen == null)
{
signInScreen = GameObject.Find(screenName);
yield return null;
}
var emailInputField = GameObject.Find(screenName + "/EmailInputField");
yield return TestInput.EnterText(emailInputField, _testIdentity.Email);
var passwordInputField = GameObject.Find(screenName + "/PasswordInputField");
yield return TestInput.EnterText(passwordInputField, _testIdentity.Password);
var submitButton = GameObject.Find(screenName + "/SubmitButton");
yield return TestInput.PressButton(submitButton);
var waitForScene = new WaitForSceneLoaded(GameSceneName, timeoutSec: 5);
yield return waitForScene;
Assert.IsFalse(waitForScene.TimedOut, $"Scene {GameSceneName} was never loaded");
const string screenName2 = GameObjectNames.StartGameScreen;
var startScreen = GameObject.Find(screenName2);
Assert.IsTrue(startScreen.activeSelf);
submitButton = GameObject.Find(screenName2 + "/SubmitButton");
Assert.IsNotNull(submitButton);
Assert.IsTrue(submitButton.activeSelf);
Button buttonScript = submitButton.GetComponent<Button>();
Assert.IsNotNull(buttonScript);
Assert.IsTrue(buttonScript.interactable);
yield return TestInput.PressButton(submitButton);
var messageText = GameObject.Find(screenName2 + "/MessageText");
Assert.IsNotNull(messageText);
string message = TestInput.GetText(messageText);
Assert.AreEqual(string.Empty, message);
CanvasGroup screenGroup = startScreen.GetComponent<CanvasGroup>();
Assert.IsNotNull(screenGroup);
Assert.IsFalse(screenGroup.interactable);
var waitForMessage = new WaitUnitilCondition(() => TestInput.GetText(messageText) != message || !startScreen.activeSelf, timeoutSec: 20f);
yield return waitForMessage;
Assert.IsFalse(waitForMessage.TimedOut, $"The session status was never updated");
}
}
}
| 96 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace SampleTests.UI
{
public static class TestInput
{
public static string GetText(GameObject text)
{
return text.GetComponent<Text>().text;
}
public static IEnumerator EnterText(GameObject inputField, string text)
{
inputField.GetComponent<InputField>().text = text;
yield break;
}
public static IEnumerator PressButton(GameObject button)
{
button.GetComponent<Button>().OnSubmit(null);
yield return null;
}
}
}
| 30 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
namespace SampleTests.UI
{
internal struct TestSettings
{
public string AccessKey;
public string SecretKey;
public string Region;
public string UserPoolId;
public string UserPoolClientId;
public string ApiGatewayEndpoint;
}
}
| 16 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System.IO;
using Newtonsoft.Json;
namespace SampleTests.UI
{
internal sealed class TestSettingsSource
{
private const string DefaultPath = "UiTestSettings.json";
public TestSettings Get(string filePath = DefaultPath)
{
string settingsText = File.ReadAllText(filePath);
return JsonConvert.DeserializeObject<TestSettings>(settingsText);
}
}
}
| 20 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
namespace SampleTests.UI
{
public sealed class WaitForGameObjectFound : WaitWithTimeOut
{
private readonly string _objectName;
public override bool keepWaiting
{
get
{
var gameObject = GameObject.Find(_objectName);
return gameObject == null && base.keepWaiting;
}
}
public WaitForGameObjectFound(string objectName, float timeoutSec = 5)
: base(timeoutSec, () => Time.realtimeSinceStartup)
{
_objectName = objectName;
}
}
}
| 28 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using UnityEngine;
using UnityEngine.SceneManagement;
namespace SampleTests.UI
{
public sealed class WaitForSceneLoaded : WaitWithTimeOut
{
private readonly string _sceneName;
public override bool keepWaiting
{
get
{
Scene scene = SceneManager.GetSceneByName(_sceneName);
bool sceneLoaded = scene.IsValid() && scene.isLoaded;
return !sceneLoaded && base.keepWaiting;
}
}
public WaitForSceneLoaded(string sceneName, float timeoutSec = 10)
: base(timeoutSec, () => Time.realtimeSinceStartup)
{
_sceneName = sceneName;
}
}
}
| 30 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using UnityEngine;
namespace SampleTests.UI
{
public sealed class WaitUnitilCondition : WaitWithTimeOut
{
private readonly Func<bool> _evaluateCondition;
public override bool keepWaiting
{
get
{
bool currentValue = _evaluateCondition();
return currentValue && base.keepWaiting;
}
}
public WaitUnitilCondition(Func<bool> evaluateCondition, float timeoutSec = 10)
: base(timeoutSec, () => Time.realtimeSinceStartup)
{
_evaluateCondition = evaluateCondition ?? throw new ArgumentNullException(nameof(evaluateCondition));
}
}
}
| 29 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using UnityEngine;
namespace SampleTests.UI
{
public class WaitWithTimeOut : CustomYieldInstruction
{
private readonly float _timeoutSec;
private readonly Func<float> _getCurrentTime;
private readonly float _startTime;
public bool TimedOut { get; private set; }
public override bool keepWaiting
{
get
{
if (_getCurrentTime() - _startTime >= _timeoutSec)
{
TimedOut = true;
}
return !TimedOut;
}
}
public WaitWithTimeOut(float timeoutSec, Func<float> getCurrentTime)
{
_timeoutSec = timeoutSec;
_getCurrentTime = getCurrentTime ?? throw new ArgumentNullException(nameof(getCurrentTime));
_startTime = getCurrentTime();
}
}
}
| 38 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Runtime.CompilerServices;
[assembly: System.Reflection.AssemblyCompany("Amazon Web Services")]
[assembly: System.Reflection.AssemblyTitle("GameLift Plugin Editor")]
[assembly: System.Reflection.AssemblyCopyright("Copyright 2021.")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
| 10 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading.Tasks;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public static class AssertAsync
{
public delegate Task AsyncTestDelegate();
// https://forum.unity.com/threads/can-i-replace-upgrade-unitys-nunit.488580/
public static TActual ThrowsAsync<TActual>(AsyncTestDelegate code, string message = "", params object[] args) where TActual : Exception
{
return Assert.Throws<TActual>(() =>
{
try
{
code.Invoke().Wait(); // Will wrap any exceptions in an AggregateException
}
catch (AggregateException e)
{
if (e.InnerException is null)
{
throw;
}
throw e.InnerException; // Throw the unwrapped exception
}
}, message, args);
}
}
}
| 36 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
using UnityEditor;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class AwsCredentialsCreationTests
{
private readonly TextProvider _textProvider = TextProviderFactory.Create();
#region Refresh
[Test]
public void Refresh_WhenAnyProfilesAndCurrentSaved_AllPropertiesAreUpdated()
{
var coreApiMock = new Mock<CoreApi>();
List<string> testProfiles = coreApiMock.SetUpWithTestProfileListOf2();
coreApiMock.SetUpCoreApiWithProfile(success: true, testProfiles[1]);
AwsCredentialsCreation underTest = GetAwsCredentials(coreApiMock.Object);
// Act
underTest.Refresh();
// Assert
coreApiMock.Verify();
Assert.AreEqual(testProfiles[1], underTest.CurrentProfileName);
Assert.IsNull(underTest.AccessKeyId);
Assert.IsNull(underTest.SecretKey);
}
[Test]
public void Refresh_WhenAnyProfilesAndCurrentInvalid_AllPropertiesAreUpdated()
{
string invalidProfile = "Invalid" + DateTime.UtcNow.ToBinary().ToString();
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpWithTestProfileListOf2();
coreApiMock.SetUpCoreApiWithProfile(success: true, invalidProfile);
AwsCredentialsCreation underTest = GetAwsCredentials(coreApiMock.Object);
// Act
underTest.Refresh();
// Assert
coreApiMock.Verify();
Assert.IsNull(underTest.CurrentProfileName);
Assert.IsNull(underTest.AccessKeyId);
Assert.IsNull(underTest.SecretKey);
}
[Test]
public void Refresh_WhenAnyProfilesAndNoCurrent_AllPropertiesAreUpdated()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpWithTestProfileListOf2();
coreApiMock.SetUpCoreApiWithProfile(success: false);
AwsCredentialsCreation underTest = GetAwsCredentials(coreApiMock.Object);
// Act
underTest.Refresh();
// Assert
coreApiMock.Verify();
Assert.IsNull(underTest.CurrentProfileName);
Assert.IsNull(underTest.AccessKeyId);
Assert.IsNull(underTest.SecretKey);
}
[Test]
public void Refresh_WhenNoProfilesAndNoCurrent_AllPropertiesAreUpdated()
{
var coreApiMock = new Mock<CoreApi>();
var testProfiles = new List<string>();
var profilesResponse = new GetProfilesResponse()
{
Profiles = testProfiles
};
profilesResponse = Response.Ok(profilesResponse);
coreApiMock.Setup(target => target.ListCredentialsProfiles())
.Returns(profilesResponse)
.Verifiable();
AwsCredentialsCreation underTest = GetAwsCredentials(coreApiMock.Object);
// Act
underTest.Refresh();
// Assert
coreApiMock.Verify();
Assert.IsNull(underTest.CurrentProfileName);
Assert.IsNull(underTest.AccessKeyId);
Assert.IsNull(underTest.SecretKey);
}
[Test]
public void Refresh_WhenGetProfilesError_AllPropertiesAreUpdated()
{
var coreApiMock = new Mock<CoreApi>();
GetProfilesResponse profilesResponse = Response.Fail(new GetProfilesResponse());
coreApiMock.Setup(target => target.ListCredentialsProfiles())
.Returns(profilesResponse)
.Verifiable();
AwsCredentialsCreation underTest = GetAwsCredentials(coreApiMock.Object);
// Act
underTest.Refresh();
// Assert
coreApiMock.Verify();
Assert.IsNull(underTest.CurrentProfileName);
Assert.IsNull(underTest.AccessKeyId);
Assert.IsNull(underTest.SecretKey);
}
#endregion
#region CanCreate
[Test]
public void CanCreate_WhenNewInstance_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsCreation awsCredentials = GetAwsCredentials(coreApiMock.Object);
Assert.AreEqual(false, awsCredentials.CanCreate);
}
[Test]
public void CanCreate_WhenSecretKeyEmpty_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsCreation awsCredentials = GetAwsCredentials(coreApiMock.Object);
awsCredentials.ProfileName = "TestProfile";
awsCredentials.AccessKeyId = "NonEmpty";
Assert.AreEqual(false, awsCredentials.CanCreate);
}
[Test]
public void CanCreate_WhenAccessKeyIdEmpty_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsCreation awsCredentials = GetAwsCredentials(coreApiMock.Object);
awsCredentials.ProfileName = "TestProfile";
awsCredentials.SecretKey = "NonEmpty";
Assert.AreEqual(false, awsCredentials.CanCreate);
}
[Test]
public void CanCreate_WhenProfileNameEmpty_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsCreation awsCredentials = GetAwsCredentials(coreApiMock.Object);
awsCredentials.AccessKeyId = "NonEmptyId";
awsCredentials.SecretKey = "NonEmpty";
Assert.AreEqual(false, awsCredentials.CanCreate);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void CanCreate_WhenNonEmptyFieldsAndCanSaveRegionIsParam_IsExpected(bool canSaveRegion)
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsCreation awsCredentials = GetAwsCredentials(coreApiMock.Object, canSaveRegion: canSaveRegion);
awsCredentials.ProfileName = "TestProfile";
awsCredentials.AccessKeyId = "NonEmptyId";
awsCredentials.SecretKey = "NonEmpty";
Assert.AreEqual(canSaveRegion, awsCredentials.CanCreate);
}
#endregion
#region Create
[Test]
public void Create_WhenCanCreate_SavesAwsCredentialsAndSetsCurrentProfile()
{
const string testProfileName = "TestProfile";
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
string actualProfileName = null;
string actualAccessKeyId = null;
string actualSecretKey = null;
var coreApiMock = new Mock<CoreApi>();
SaveAwsCredentialsResponse saveResponse = Response.Ok(new SaveAwsCredentialsResponse());
coreApiMock.Setup(target => target.SaveAwsCredentials(testProfileName, testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Callback<string, string, string>((profileName, accessKeyId, secretKey) =>
{
actualProfileName = profileName;
actualAccessKeyId = accessKeyId;
actualSecretKey = secretKey;
})
.Verifiable();
PutSettingResponse writeResponse = Response.Ok(new PutSettingResponse());
coreApiMock.Setup(target => target.PutSetting(SettingsKeys.CurrentProfileName, testProfileName))
.Returns(writeResponse)
.Verifiable();
AwsCredentialsCreation awsCredentials = GetAwsCredentials(coreApiMock.Object);
awsCredentials.ProfileName = testProfileName;
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
// Act
awsCredentials.Create();
// Assert
coreApiMock.Verify();
Assert.AreEqual(testProfileName, awsCredentials.CurrentProfileName);
Assert.AreEqual(testProfileName, actualProfileName);
Assert.AreEqual(testAccessKeyId, actualAccessKeyId);
Assert.AreEqual(testSecretKey, actualSecretKey);
}
[Test]
public void OnCreated_WhenCreateSuccess_IsRaised()
{
SetUpForCreateMethodSuccess(out Mock<CoreApi> coreApiMock, out AwsCredentialsCreation awsCredentials);
bool isEventRaised = false;
awsCredentials.OnCreated += () =>
{
isEventRaised = true;
};
// Act
awsCredentials.Create();
// Assert
coreApiMock.Verify();
Assert.IsTrue(isEventRaised);
}
[Test]
public void Status_WhenCreateSuccess_DisplaysCreated()
{
SetUpForCreateMethodSuccess(out Mock<CoreApi> coreApiMock, out AwsCredentialsCreation awsCredentials);
// Act
awsCredentials.Create();
// Assert
coreApiMock.Verify();
Assert.IsTrue(awsCredentials.Status.IsDisplayed);
Assert.AreEqual(MessageType.Info, awsCredentials.Status.Type);
Assert.AreEqual(_textProvider.Get(Strings.StatusProfileCreated), awsCredentials.Status.Message);
}
[Test]
public void Status_WhenCreateFailsToSetCurrent_DisplaysError()
{
const string testProfileName = "TestProfile";
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
var coreApiMock = new Mock<CoreApi>();
SaveAwsCredentialsResponse saveResponse = Response.Ok(new SaveAwsCredentialsResponse());
coreApiMock.Setup(target => target.SaveAwsCredentials(testProfileName, testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Verifiable();
PutSettingResponse writeResponse = Response.Fail(new PutSettingResponse());
coreApiMock.Setup(target => target.PutSetting(SettingsKeys.CurrentProfileName, testProfileName))
.Returns(writeResponse)
.Verifiable();
AwsCredentialsCreation awsCredentials = GetAwsCredentials(coreApiMock.Object);
awsCredentials.ProfileName = testProfileName;
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
// Act
awsCredentials.Create();
// Assert
coreApiMock.Verify();
Assert.IsTrue(awsCredentials.Status.IsDisplayed);
Assert.AreEqual(MessageType.Error, awsCredentials.Status.Type);
Assert.IsNotNull(awsCredentials.Status.Message);
}
[Test]
public void Status_WhenCreateFailsToCreate_DisplaysError()
{
const string testProfileName = "TestProfile";
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
var coreApiMock = new Mock<CoreApi>();
SaveAwsCredentialsResponse saveResponse = Response.Fail(new SaveAwsCredentialsResponse());
coreApiMock.Setup(target => target.SaveAwsCredentials(testProfileName, testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Verifiable();
AwsCredentialsCreation awsCredentials = GetAwsCredentials(coreApiMock.Object);
awsCredentials.ProfileName = testProfileName;
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
// Act
awsCredentials.Create();
// Assert
coreApiMock.Verify();
Assert.IsTrue(awsCredentials.Status.IsDisplayed);
Assert.AreEqual(MessageType.Error, awsCredentials.Status.Type);
Assert.IsNotNull(awsCredentials.Status.Message);
}
private void SetUpForCreateMethodSuccess(out Mock<CoreApi> coreApiMock, out AwsCredentialsCreation awsCredentials)
{
const string testProfileName = "TestProfile";
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
coreApiMock = new Mock<CoreApi>();
SaveAwsCredentialsResponse saveResponse = Response.Ok(new SaveAwsCredentialsResponse());
coreApiMock.Setup(target => target.SaveAwsCredentials(testProfileName, testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Verifiable();
PutSettingResponse writeResponse = Response.Ok(new PutSettingResponse());
coreApiMock.Setup(target => target.PutSetting(SettingsKeys.CurrentProfileName, testProfileName))
.Returns(writeResponse)
.Verifiable();
awsCredentials = GetAwsCredentials(coreApiMock.Object);
awsCredentials.ProfileName = testProfileName;
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
}
#endregion
private AwsCredentialsCreation GetAwsCredentials(CoreApi coreApi,
Mock<RegionBootstrap> regionMock = null, bool canSaveRegion = true)
{
regionMock = regionMock ?? new Mock<RegionBootstrap>(coreApi);
regionMock.Setup(target => target.CanSave)
.Returns(canSaveRegion)
.Verifiable();
regionMock.Setup(target => target.Refresh())
.Verifiable();
regionMock.Setup(target => target.Save())
.Returns((true, null))
.Verifiable();
return new AwsCredentialsCreation(_textProvider, regionMock.Object, coreApi, new MockLogger());
}
}
}
| 378 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class AwsCredentialsTests
{
private readonly TextProvider _textProvider = TextProviderFactory.Create();
[Test]
public void Refresh_WhenGetProfilesError_CanSelectIsFalse()
{
var coreApiMock = new Mock<CoreApi>();
var response = new GetProfilesResponse() { Profiles = new List<string>() };
response = Response.Fail(response);
coreApiMock.Setup(target => target.ListCredentialsProfiles())
.Returns(response)
.Verifiable();
AwsCredentials awsCredentials = GetAwsCredentialsWithStubComponents(coreApiMock.Object);
// Act
awsCredentials.Refresh();
// Assert
coreApiMock.Verify();
Assert.AreEqual(false, awsCredentials.CanSelect);
}
[Test]
public void Refresh_WhenNoProfiles_CanSelectIsFalse()
{
var coreApiMock = new Mock<CoreApi>();
var response = new GetProfilesResponse() { Profiles = new List<string>() };
response = Response.Ok(response);
coreApiMock.Setup(target => target.ListCredentialsProfiles())
.Returns(response)
.Verifiable();
AwsCredentials awsCredentials = GetAwsCredentialsWithStubComponents(coreApiMock.Object);
// Act
awsCredentials.Refresh();
// Assert
coreApiMock.Verify();
Assert.AreEqual(false, awsCredentials.CanSelect);
}
[Test]
public void Refresh_WhenAnyProfiles_CanSelectIsTrue()
{
var coreApiMock = new Mock<CoreApi>();
var profilesResponse = new GetProfilesResponse()
{
Profiles = new List<string> { "NonEmpty" }
};
profilesResponse = Response.Ok(profilesResponse);
coreApiMock.Setup(target => target.ListCredentialsProfiles())
.Returns(profilesResponse)
.Verifiable();
AwsCredentials awsCredentials = GetAwsCredentialsWithStubComponents(coreApiMock.Object);
// Act
awsCredentials.Refresh();
// Assert
coreApiMock.Verify();
Assert.AreEqual(true, awsCredentials.CanSelect);
}
private AwsCredentials GetAwsCredentialsWithStubComponents(CoreApi coreApi)
{
var regionMock = new Mock<RegionBootstrap>(coreApi);
regionMock.Setup(target => target.Refresh())
.Verifiable();
var mockLogger = new MockLogger();
var creationMock = new Mock<AwsCredentialsCreation>(_textProvider, regionMock.Object, coreApi, mockLogger);
creationMock.Setup(target => target.Refresh())
.Verifiable();
var updateMock = new Mock<AwsCredentialsUpdate>(_textProvider, regionMock.Object, coreApi, mockLogger);
updateMock.Setup(target => target.Refresh())
.Verifiable();
return new AwsCredentials(creationMock.Object, updateMock.Object, coreApi);
}
}
}
| 99 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class AwsCredentialsUpdateTests
{
private readonly TextProvider _textProvider = TextProviderFactory.Create();
#region Refresh
[Test]
public void Refresh_WhenAnyProfilesAndCurrentSaved_AllPropertiesAreUpdated()
{
PrepareProfileList(out AwsCredentialsUpdate awsCredentials, out List<string> testProfiles,
out Mock<CoreApi> coreApiMock, out _);
// Act
awsCredentials.Refresh();
// Assert
coreApiMock.Verify();
Assert.IsNotNull(awsCredentials.AllProlfileNames);
Assert.AreEqual(testProfiles.Count, awsCredentials.AllProlfileNames.Length);
Assert.AreEqual(1, awsCredentials.CurrentProfileIndex);
Assert.AreEqual(testProfiles[1], awsCredentials.CurrentProfileName);
Assert.AreEqual(1, awsCredentials.SelectedProfileIndex);
Assert.AreEqual(false, awsCredentials.CanUpdateCurrentProfile);
Assert.AreEqual(true, awsCredentials.CanUpdate);
Assert.AreEqual("NonEmptyKey", awsCredentials.AccessKeyId);
Assert.AreEqual("NonEmptySecret", awsCredentials.SecretKey);
}
[Test]
public void Refresh_WhenAnyProfilesAndCurrentCredentialsError_AllPropertiesAreUpdated()
{
var coreApiMock = new Mock<CoreApi>();
List<string> testProfiles = coreApiMock.SetUpWithTestProfileListOf2();
coreApiMock.SetUpCoreApiWithProfile(success: true, testProfiles[1]);
RetriveAwsCredentialsResponse credentialsResponse = Response.Fail(new RetriveAwsCredentialsResponse());
coreApiMock.Setup(target => target.RetrieveAwsCredentials(testProfiles[1]))
.Returns(credentialsResponse)
.Verifiable();
AwsCredentialsUpdate awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
// Act
awsCredentials.Refresh();
// Assert
coreApiMock.Verify();
Assert.IsNotNull(awsCredentials.AllProlfileNames);
Assert.AreEqual(testProfiles.Count, awsCredentials.AllProlfileNames.Length);
Assert.AreEqual(1, awsCredentials.CurrentProfileIndex);
Assert.AreEqual(testProfiles[1], awsCredentials.CurrentProfileName);
Assert.AreEqual(1, awsCredentials.SelectedProfileIndex);
Assert.AreEqual(false, awsCredentials.CanUpdateCurrentProfile);
Assert.AreEqual(false, awsCredentials.CanUpdate);
Assert.IsNull(awsCredentials.AccessKeyId);
Assert.IsNull(awsCredentials.SecretKey);
}
[Test]
public void Refresh_WhenAnyProfilesAndNoCurrent_AllPropertiesAreUpdated()
{
var coreApiMock = new Mock<CoreApi>();
List<string> testProfiles = coreApiMock.SetUpWithTestProfileListOf2();
coreApiMock.SetUpCoreApiWithProfile(success: false);
AwsCredentialsUpdate awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
// Act
awsCredentials.Refresh();
// Assert
coreApiMock.Verify();
AssertCurrentProfileNotLoaded(awsCredentials);
Assert.IsNotNull(awsCredentials.AllProlfileNames);
Assert.AreEqual(testProfiles.Count, awsCredentials.AllProlfileNames.Length);
Assert.IsNull(awsCredentials.AccessKeyId);
Assert.IsNull(awsCredentials.SecretKey);
}
[Test]
public void Refresh_WhenNoProfilesAndNoCurrent_AllPropertiesAreUpdated()
{
var coreApiMock = new Mock<CoreApi>();
var testProfiles = new List<string>();
var profilesResponse = new GetProfilesResponse()
{
Profiles = testProfiles
};
profilesResponse = Response.Ok(profilesResponse);
coreApiMock.Setup(target => target.ListCredentialsProfiles())
.Returns(profilesResponse)
.Verifiable();
AwsCredentialsUpdate awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
// Act
awsCredentials.Refresh();
// Assert
coreApiMock.Verify();
AssertCurrentProfileNotLoaded(awsCredentials);
Assert.IsNotNull(awsCredentials.AllProlfileNames);
Assert.AreEqual(0, awsCredentials.AllProlfileNames.Length);
Assert.IsNull(awsCredentials.AccessKeyId);
Assert.IsNull(awsCredentials.SecretKey);
}
[Test]
public void Refresh_WhenGetProfilesError_AllPropertiesAreUpdated()
{
var coreApiMock = new Mock<CoreApi>();
var profilesResponse = new GetProfilesResponse()
{
ErrorCode = "TestError"
};
profilesResponse = Response.Fail(profilesResponse);
coreApiMock.Setup(target => target.ListCredentialsProfiles())
.Returns(profilesResponse)
.Verifiable();
AwsCredentialsUpdate awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
// Act
awsCredentials.Refresh();
// Assert
coreApiMock.Verify();
AssertCurrentProfileNotLoaded(awsCredentials);
Assert.IsNotNull(awsCredentials.AllProlfileNames);
Assert.AreEqual(0, awsCredentials.AllProlfileNames.Length);
Assert.IsNull(awsCredentials.AccessKeyId);
Assert.IsNull(awsCredentials.SecretKey);
}
#endregion
#region CanUpdate
[Test]
public void CanUpdate_WhenNewInstance_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsUpdate awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
Assert.AreEqual(false, awsCredentials.CanUpdate);
}
[Test]
public void CanUpdate_WhenSecretKeyEmpty_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsUpdate awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
awsCredentials.AccessKeyId = "NonEmpty";
Assert.AreEqual(false, awsCredentials.CanUpdate);
}
[Test]
public void CanUpdate_WhenAccessKeyIdEmpty_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsUpdate awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
awsCredentials.SecretKey = "NonEmpty";
Assert.AreEqual(false, awsCredentials.CanUpdate);
}
[Test]
public void CanUpdate_WhenNonEmptyFieldsAndNotRefreshed_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
AwsCredentialsUpdate awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
awsCredentials.AccessKeyId = "NonEmptyId";
awsCredentials.SecretKey = "NonEmpty";
Assert.AreEqual(false, awsCredentials.CanUpdate);
}
[Test]
public void CanUpdate_WhenRefreshedAndUpdatedFields_IsTrue()
{
PrepareProfileList(out AwsCredentialsUpdate awsCredentials, out _, out _, out _);
awsCredentials.Refresh();
// Act
awsCredentials.AccessKeyId = DateTime.Now.ToString();
awsCredentials.SecretKey = DateTime.Now.ToString();
Assert.AreEqual(true, awsCredentials.CanUpdate);
}
#endregion
#region Update
[Test]
public void Update_WhenCanUpdate_SavesAwsCredentialsAndSetsCurrentProfile()
{
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
PrepareProfileList(out AwsCredentialsUpdate awsCredentials, out List<string> testProfiles,
out Mock<CoreApi> coreApiMock, out _);
awsCredentials.Refresh();
string testProfileName = testProfiles[awsCredentials.SelectedProfileIndex];
string actualProfileName = null;
string actualAccessKeyId = null;
string actualSecretKey = null;
// Credentials mock
UpdateAwsCredentialsResponse saveResponse = Response.Ok(new UpdateAwsCredentialsResponse());
coreApiMock.Setup(target => target.UpdateAwsCredentials(testProfileName, testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Callback<string, string, string>((profileName, accessKeyId, secretKey) =>
{
actualProfileName = profileName;
actualAccessKeyId = accessKeyId;
actualSecretKey = secretKey;
})
.Verifiable();
// Settings mock
PutSettingResponse writeResponse = Response.Ok(new PutSettingResponse());
coreApiMock.Setup(target => target.PutSetting(SettingsKeys.CurrentProfileName, testProfileName))
.Returns(writeResponse)
.Verifiable();
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
// Act
awsCredentials.Update();
// Assert
coreApiMock.Verify();
Assert.AreEqual(testProfileName, awsCredentials.CurrentProfileName);
Assert.AreEqual(testProfileName, actualProfileName);
Assert.AreEqual(testAccessKeyId, actualAccessKeyId);
Assert.AreEqual(testSecretKey, actualSecretKey);
}
[Test]
public void Update_WhenCanUpdate_ClearsBootstrapBucket()
{
AwsCredentialsUpdate awsCredentials = SetUpCredentialsForProfileSuccess(out Mock<CoreApi> coreApiMock);
coreApiMock.Setup(target => target.ClearSetting(SettingsKeys.CurrentBucketName))
.Verifiable();
// Act
awsCredentials.Update();
// Assert
coreApiMock.Verify();
}
private AwsCredentialsUpdate SetUpCredentialsForProfileSuccess(out Mock<CoreApi> coreApiMock)
{
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
PrepareProfileList(out AwsCredentialsUpdate awsCredentials, out List<string> testProfiles,
out coreApiMock, out _);
awsCredentials.Refresh();
string testProfileName = testProfiles[awsCredentials.SelectedProfileIndex];
string actualProfileName = null;
string actualAccessKeyId = null;
string actualSecretKey = null;
// Credentials mock
UpdateAwsCredentialsResponse saveResponse = Response.Ok(new UpdateAwsCredentialsResponse());
coreApiMock.Setup(target => target.UpdateAwsCredentials(testProfileName, testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Callback<string, string, string>((profileName, accessKeyId, secretKey) =>
{
actualProfileName = profileName;
actualAccessKeyId = accessKeyId;
actualSecretKey = secretKey;
})
.Verifiable();
// Settings mock
PutSettingResponse writeResponse = Response.Ok(new PutSettingResponse());
coreApiMock.Setup(target => target.PutSetting(SettingsKeys.CurrentProfileName, testProfileName))
.Returns(writeResponse)
.Verifiable();
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
return awsCredentials;
}
[Test]
public void Status_WhenUpdateSuccess_DisplaysUpdated()
{
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
PrepareProfileList(out AwsCredentialsUpdate awsCredentials, out List<string> testProfiles,
out Mock<CoreApi> coreApiMock, out _);
awsCredentials.Refresh();
// Credentials mock
UpdateAwsCredentialsResponse saveResponse = Response.Ok(new UpdateAwsCredentialsResponse());
coreApiMock.Setup(target => target.UpdateAwsCredentials(It.IsAny<string>(), testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Verifiable();
// Settings mock
PutSettingResponse writeResponse = Response.Ok(new PutSettingResponse());
coreApiMock.Setup(target => target.PutSetting(SettingsKeys.CurrentProfileName, It.IsAny<string>()))
.Returns(writeResponse)
.Verifiable();
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
// Act
awsCredentials.Update();
// Assert
coreApiMock.Verify();
Assert.IsTrue(awsCredentials.Status.IsDisplayed);
Assert.AreEqual(MessageType.Info, awsCredentials.Status.Type);
Assert.AreEqual(_textProvider.Get(Strings.StatusProfileUpdated), awsCredentials.Status.Message);
}
[Test]
public void Status_WhenUpdateFailsToSetCurrent_DisplaysError()
{
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
PrepareProfileList(out AwsCredentialsUpdate awsCredentials, out List<string> testProfiles,
out Mock<CoreApi> coreApiMock, out _);
awsCredentials.Refresh();
// Credentials mock
UpdateAwsCredentialsResponse saveResponse = Response.Ok(new UpdateAwsCredentialsResponse());
coreApiMock.Setup(target => target.UpdateAwsCredentials(It.IsAny<string>(), testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Verifiable();
// Settings mock
PutSettingResponse writeResponse = Response.Fail(new PutSettingResponse());
coreApiMock.Setup(target => target.PutSetting(SettingsKeys.CurrentProfileName, It.IsAny<string>()))
.Returns(writeResponse)
.Verifiable();
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
// Act
awsCredentials.Update();
// Assert
coreApiMock.Verify();
Assert.IsTrue(awsCredentials.Status.IsDisplayed);
Assert.AreEqual(MessageType.Error, awsCredentials.Status.Type);
Assert.IsNotNull(awsCredentials.Status.Message);
}
[Test]
public void Status_WhenUpdateFailsToUpdate_DisplaysError()
{
const string testAccessKeyId = "TestKey";
const string testSecretKey = "TestSecret";
PrepareProfileList(out AwsCredentialsUpdate awsCredentials, out List<string> testProfiles,
out Mock<CoreApi> coreApiMock, out _);
awsCredentials.Refresh();
// Credentials mock
UpdateAwsCredentialsResponse saveResponse = Response.Fail(new UpdateAwsCredentialsResponse());
coreApiMock.Setup(target => target.UpdateAwsCredentials(It.IsAny<string>(), testAccessKeyId, testSecretKey))
.Returns(saveResponse)
.Verifiable();
awsCredentials.AccessKeyId = testAccessKeyId;
awsCredentials.SecretKey = testSecretKey;
// Act
awsCredentials.Update();
// Assert
coreApiMock.Verify();
Assert.IsTrue(awsCredentials.Status.IsDisplayed);
Assert.AreEqual(MessageType.Error, awsCredentials.Status.Type);
Assert.IsNotNull(awsCredentials.Status.Message);
}
#endregion
private static void AssertCurrentProfileNotLoaded(AwsCredentialsUpdate awsCredentials)
{
Assert.AreEqual(-1, awsCredentials.CurrentProfileIndex);
Assert.IsNull(awsCredentials.CurrentProfileName);
Assert.AreEqual(-1, awsCredentials.SelectedProfileIndex);
Assert.AreEqual(false, awsCredentials.CanUpdateCurrentProfile);
Assert.AreEqual(false, awsCredentials.CanUpdate);
}
private AwsCredentialsUpdate GetUpdateInstanceWithMockRegion(CoreApi coreApi)
{
var regionMock = new Mock<RegionBootstrap>(coreApi);
regionMock.Setup(target => target.CanSave)
.Returns(true)
.Verifiable();
regionMock.Setup(target => target.Refresh())
.Verifiable();
regionMock.Setup(target => target.Save())
.Returns((true, null))
.Verifiable();
return new AwsCredentialsUpdate(_textProvider, regionMock.Object, coreApi, new MockLogger());
}
private void PrepareProfileList(out AwsCredentialsUpdate awsCredentials,
out List<string> testProfiles, out Mock<CoreApi> coreApiMock,
out Mock<CredentialsSetting> settingMock)
{
coreApiMock = new Mock<CoreApi>();
testProfiles = coreApiMock.SetUpWithTestProfileListOf2();
string currentProfile = testProfiles[1];
coreApiMock.SetUpCoreApiWithProfile(success: true, currentProfile);
var credentialsResponse = new RetriveAwsCredentialsResponse()
{
AccessKey = "NonEmptyKey",
SecretKey = "NonEmptySecret"
};
credentialsResponse = Response.Ok(credentialsResponse);
coreApiMock.Setup(target => target.RetrieveAwsCredentials(currentProfile))
.Returns(credentialsResponse)
.Verifiable();
// The setting mock
settingMock = new Mock<CredentialsSetting>(coreApiMock.Object);
awsCredentials = GetUpdateInstanceWithMockRegion(coreApiMock.Object);
}
}
}
| 470 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.AccountManagement.Models;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
internal static class CoreApiMockExtensions
{
public static void SetUpCoreApiForBootstrapSuccess(this Mock<CoreApi> coreApiMock,
string testBucketName = "test-bucket", string testRegion = "test-region")
{
SetUpCoreApiWithBucket(coreApiMock, true, testBucketName);
SetUpCoreApiWithRegion(coreApiMock, true, true, testRegion);
}
public static void SetUpCoreApiWithRegion(this Mock<CoreApi> coreApiMock, bool success, bool valid, string testRegion = "test-region")
{
if (coreApiMock is null)
{
throw new ArgumentNullException(nameof(coreApiMock));
}
SetUpCoreApiWithSetting(coreApiMock, SettingsKeys.CurrentRegion, success, testRegion);
coreApiMock.Setup(target => target.IsValidRegion(testRegion))
.Returns(valid);
}
public static void SetUpCoreApiWithBucket(this Mock<CoreApi> coreApiMock, bool success, string testBucketName = "test-bucket")
{
if (coreApiMock is null)
{
throw new ArgumentNullException(nameof(coreApiMock));
}
SetUpCoreApiWithSetting(coreApiMock, SettingsKeys.CurrentBucketName, success, testBucketName);
}
public static void SetUpCoreApiWithProfile(this Mock<CoreApi> coreApiMock, bool success, string profile = "test-profile")
{
SetUpCoreApiWithSetting(coreApiMock, SettingsKeys.CurrentProfileName, success, profile);
}
public static void SetUpCoreApiWithGameLiftLocalPath(this Mock<CoreApi> coreApiMock, bool success, string result = "X:/gl.exe")
{
SetUpCoreApiWithSetting(coreApiMock, SettingsKeys.GameLiftLocalPath, success, result);
}
public static void SetUpCoreApiWithAccountId(this Mock<CoreApi> coreApiMock, bool success, string accountId = "test-id")
{
var accountIdResponse = new RetrieveAccountIdByCredentialsResponse()
{
AccountId = accountId
};
accountIdResponse = success ? Response.Ok(accountIdResponse) : Response.Fail(accountIdResponse);
coreApiMock.Setup(target => target.RetrieveAccountId(It.IsAny<string>()))
.Returns(accountIdResponse);
}
public static void SetUpGetStackNameAsGameName(this Mock<CoreApi> coreApiMock, string gameName)
{
coreApiMock.Setup(target => target.GetStackName(gameName))
.Returns(gameName);
}
public static void SetUpGetBuildS3Key(this Mock<CoreApi> coreApiMock, string result)
{
coreApiMock.Setup(target => target.GetBuildS3Key())
.Returns(result);
}
public static void SetUpCoreApiWithDescribeStack(this Mock<CoreApi> coreApiMock, bool success,
string profileName = "test-profile", string region = "test-region", string stackName = "test-stack",
string result = StackStatus.CreateComplete, string gameName = "test-game", Dictionary<string, string> outputs = null)
{
var response = new DescribeStackResponse()
{
StackId = "test-stack-id",
StackStatus = result,
GameName = gameName,
Outputs = outputs ?? new Dictionary<string, string>()
};
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.DescribeStack(profileName, region, stackName))
.Returns(response)
.Verifiable();
}
public static List<string> SetUpWithTestProfileListOf2(this Mock<CoreApi> coreApiMock)
{
if (coreApiMock is null)
{
throw new ArgumentNullException(nameof(coreApiMock));
}
var testProfiles = new List<string> { "NonEmpty", "Current" };
var profilesResponse = new GetProfilesResponse()
{
Profiles = testProfiles
};
profilesResponse = Response.Ok(profilesResponse);
coreApiMock.Setup(target => target.ListCredentialsProfiles())
.Returns(profilesResponse)
.Verifiable();
return testProfiles;
}
internal static void SetUpCoreApiWithSetting(this Mock<CoreApi> coreApiMock, string key, bool success, string successResult)
{
var response = new GetSettingResponse() { Value = successResult };
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.GetSetting(key))
.Returns(response);
}
}
}
| 128 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections;
using System.Threading.Tasks;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public static class CoroutineTaskExtensions
{
public static IEnumerator AsCoroutine(this Task task)
{
if (task is null)
{
throw new ArgumentNullException(nameof(task));
}
while (!task.IsCompleted)
{
yield return null;
}
task.GetAwaiter().GetResult();
}
}
}
| 29 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using AmazonGameLift.Editor;
using Moq;
using Moq.Protected;
using NUnit.Framework;
using UnityEngine;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class ImageLoaderTests
{
private readonly Texture2D _testTexture = new Texture2D(1, 1);
[Test, Sequential]
public void LoadImageSequence_WhenCorrectRange_LoadsAllImages(
[Values(-2, -1, 0, 1, 2, 0)] int first, [Values(0, 2, 3, 3, 3, 0)] int last)
{
string assetNameBase = "TestBase";
string assetNamePattern = "{0} {1}";
var mock = new Mock<ImageLoader>();
for (int i = first; i <= last; i++)
{
string assetName = string.Format(assetNamePattern, assetNameBase, i);
string imagePath = ResourceUtility.GetImagePath(assetName);
mock.Protected()
.Setup<Texture2D>("Load", imagePath)
.Returns(_testTexture)
.Verifiable();
}
ImageLoader imageLoader = mock.Object;
IReadOnlyList<Texture2D> images = imageLoader.LoadImageSequence(assetNameBase, first, last);
mock.Verify();
Assert.IsNotNull(images);
Assert.AreEqual(last - first + 1, images.Count);
foreach (Texture2D item in images)
{
Assert.AreEqual(_testTexture, item);
}
}
[Test, Sequential]
public void LoadImageSequence_WhenrIncorrectRange_LoadsZeroImages(
[Values(-2, -1, 0, 1, 2)] int first, [Values(-3, -2, -1, 0, 0)] int last)
{
string assetNameBase = "TestBase";
var mock = new Mock<ImageLoader>();
mock.Protected()
.Setup<Texture2D>("Load", ItExpr.IsAny<string>())
.Throws<NotImplementedException>()
.Verifiable();
ImageLoader imageLoader = mock.Object;
IReadOnlyList<Texture2D> images = imageLoader.LoadImageSequence(assetNameBase, first, last);
Assert.IsNotNull(images);
Assert.AreEqual(0, images.Count);
}
[Test]
public void LoadImage_WhenItExistsInThemedPath_ImageIsExpected()
{
string assetName = string.Empty;
string imagePath = ResourceUtility.GetImagePath(assetName);
string imagePathForTheme = ResourceUtility.GetImagePathForCurrentTheme(assetName);
var mock = new Mock<ImageLoader>();
mock.Protected()
.Setup<Texture2D>("Load", imagePath)
.Returns<Texture2D>(null)
.Verifiable();
mock.Protected()
.Setup<Texture2D>("Load", imagePathForTheme)
.Returns(_testTexture)
.Verifiable();
ImageLoader imageLoader = mock.Object;
Texture2D image = imageLoader.LoadImage(assetName);
mock.Verify();
Assert.IsNotNull(image);
Assert.AreEqual(_testTexture, image);
}
[Test]
public void LoadImage_WhenItExistsInNonThemedPath_ImageIsExpected()
{
string assetName = string.Empty;
string imagePath = ResourceUtility.GetImagePath(assetName);
var mock = new Mock<ImageLoader>();
mock.Protected()
.Setup<Texture2D>("Load", imagePath)
.Returns(_testTexture)
.Verifiable();
ImageLoader imageLoader = mock.Object;
Texture2D image = imageLoader.LoadImage(assetName);
mock.Verify();
Assert.IsNotNull(image);
Assert.AreEqual(_testTexture, image);
}
[Test]
public void LoadImage_WhenPathIsNull_ThrowsException()
{
string assetName = null;
var imageLoader = new ImageLoader();
Assert.Throws<ArgumentNullException>(() => imageLoader.LoadImage(assetName));
}
}
}
| 123 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLiftPlugin.Core.Shared;
using UnityEngine;
namespace AmazonGameLift.Editor
{
internal sealed class MockLogger : ILogger
{
public void Log(string message, LogType logType)
{
}
public void LogException(Exception ex)
{
}
public void LogResponseError(Response response, LogType logType)
{
}
}
}
| 25 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class RegionBootstrapTests
{
[Test]
public void CanSave_WhenRefreshAndNoCurrentRegion_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
GetSettingResponse regionResponse = Response.Fail(new GetSettingResponse());
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.ListAvailableRegions())
.Returns(new List<string> { "test-region" });
var underTest = new RegionBootstrap(coreApiMock.Object);
// Act
underTest.Refresh();
// Assert
coreApiMock.Verify();
Assert.IsFalse(underTest.CanSave);
}
[Test]
public void CanSave_WhenRefreshAndHasCurrentRegion_IsTrue()
{
string testRegion = "eu-west-1";
var coreApiMock = new Mock<CoreApi>();
var regionResponse = new GetSettingResponse()
{
Value = testRegion
};
regionResponse = Response.Ok(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.ListAvailableRegions())
.Returns(new List<string> { testRegion });
var underTest = new RegionBootstrap(coreApiMock.Object);
// Act
underTest.Refresh();
// Assert
coreApiMock.Verify();
Assert.IsTrue(underTest.CanSave);
}
[Test]
public void CanSave_WhenSetInvalidRegionIndex_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Setup(target => target.ListAvailableRegions())
.Returns(new List<string> { "test-region" });
var underTest = new RegionBootstrap(coreApiMock.Object)
{
// Act
RegionIndex = -2
};
// Assert
coreApiMock.Verify();
Assert.IsFalse(underTest.CanSave);
}
[Test]
public void CanSave_WhenSetValidRegionIndex_IsTrue()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Setup(target => target.ListAvailableRegions())
.Returns(new List<string> { "test-region" });
var underTest = new RegionBootstrap(coreApiMock.Object)
{
// Act
RegionIndex = 0
};
// Assert
coreApiMock.Verify();
Assert.IsTrue(underTest.CanSave);
}
}
}
| 106 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLift.Editor;
using NUnit.Framework;
using UnityEditor;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class StatusTests
{
[Test]
public void IsDisplayed_WhenNewInstance_IsFalse()
{
var underTest = new Status();
Assert.IsFalse(underTest.IsDisplayed);
}
[Test]
public void GetMessage_WhenNewInstance_IsNull()
{
var underTest = new Status();
Assert.IsNull(underTest.Message);
}
[Test]
public void GetMessage_WhenNewInstanceAndMessageSet_ReturnsMessage()
{
string testMessage = DateTime.Now.ToString();
var underTest = new Status();
underTest.SetMessage(testMessage, MessageType.Info);
Assert.AreEqual(testMessage, underTest.Message);
}
[Test]
public void OnChangedEvent_WhenNewInstanceAndSetMessage_IsRaised()
{
string testMessage = DateTime.Now.ToString();
var underTest = new Status();
bool isEventRaised = false;
underTest.Changed += () =>
{
isEventRaised = true;
};
// Act
underTest.SetMessage(testMessage, MessageType.Info);
// Assert
Assert.IsTrue(isEventRaised);
}
[Test]
public void OnChangedEvent_WhenSetMessageSame_IsNotRaised()
{
string testMessage = DateTime.Now.ToString();
string testMessage2 = testMessage;
MessageType testType = MessageType.None;
var underTest = new Status();
underTest.SetMessage(testMessage, testType);
bool isEventRaised = false;
underTest.Changed += () =>
{
isEventRaised = true;
};
// Act
underTest.SetMessage(testMessage2, testType);
// Assert
Assert.IsFalse(isEventRaised);
}
[Test]
public void OnChangedEvent_WhenSetMessageDifferent_IsRaised()
{
string testMessage = DateTime.Now.ToString();
string testMessage2 = testMessage + "2";
MessageType testType = MessageType.None;
var underTest = new Status();
underTest.SetMessage(testMessage, testType);
bool isEventRaised = false;
underTest.Changed += () =>
{
isEventRaised = true;
};
// Act
underTest.SetMessage(testMessage2, testType);
// Assert
Assert.IsTrue(isEventRaised);
}
[Test]
public void OnChangedEvent_WhenSetMessageSameAndDifferentType_IsRaised()
{
string testMessage = DateTime.Now.ToString();
MessageType testType = MessageType.None;
MessageType testType2 = MessageType.Info;
var underTest = new Status();
underTest.SetMessage(testMessage, testType);
bool isEventRaised = false;
underTest.Changed += () =>
{
isEventRaised = true;
};
// Act
underTest.SetMessage(testMessage, testType2);
// Assert
Assert.IsTrue(isEventRaised);
}
}
}
| 124 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLift.Editor;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class TextProviderTests
{
[Test]
public void Get_WhenNullKey_ThrowsException()
{
TextProvider underTest = TextProviderFactory.Create();
Assert.Throws<ArgumentNullException>(() => underTest.Get(null));
}
[Test]
public void Get_WhenUnknownKey_IsKey()
{
string key = new Guid().ToString();
TextProvider underTest = TextProviderFactory.Create();
string message = underTest.Get(key);
Assert.AreEqual(key, message);
}
[Test]
public void GetError_WhenNullKey_IsNotNull()
{
TextProvider underTest = TextProviderFactory.Create();
string message = underTest.GetError(null);
Assert.IsNotNull(message);
}
[Test]
public void GetError_WhenUnknownCode_IsNotNull()
{
string errorCode = new Guid().ToString();
TextProvider underTest = TextProviderFactory.Create();
string message = underTest.GetError(errorCode);
Assert.IsNotNull(message);
}
}
}
| 53 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLift.Editor;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class BootstrapBucketFormatterTests
{
private static readonly Tuple<string, string>[] s_bucketKeyTestCases = new Tuple<string, string>[]
{
new Tuple<string, string>("us-east1", "us-east1"),
new Tuple<string, string>("GameName", "gamename"),
new Tuple<string, string>("!0@#$%%G$amEN^^a&m**()_e+0~!@##$", "0gamename0"),
new Tuple<string, string>("ыыgame-nameыы", "game-name"),
new Tuple<string, string>("ZKIA47PNZKGFNJMPHEVZ", "zkia47pnzkgfnjmphevz")
};
private readonly BootstrapBucketFormatter _bucketFormatter = new BootstrapBucketFormatter();
[Test]
public void FormatBucketName_WhenNullAccountId_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => _bucketFormatter.FormatBucketName(null, "Any"));
}
[Test]
public void FormatBucketName_WhenNullRegion_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => _bucketFormatter.FormatBucketName("Any", null));
}
[Test]
public void FormatBucketKey_WhenNullValue_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => _bucketFormatter.FormatBucketKey(null));
}
[Test]
public void ValidateBucketKey_WhenNullValue_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => _bucketFormatter.ValidateBucketKey(null));
}
[Test]
[TestCaseSource(nameof(s_bucketKeyTestCases))]
public void FormatBucketKey_WhenNonEmptyString_ReturnsValidKey(Tuple<string, string> testCase)
{
string expected = testCase.Item2;
string input = testCase.Item1;
string output = _bucketFormatter.FormatBucketKey(input);
Assert.IsNotNull(output);
Assert.AreEqual(expected, output);
}
[Test, Sequential]
public void ValidateBucketKey_WhenValidKey_ReturnsTrue(
[Values("g-n", "gamename", "0game-name0", "1example", "zkia47pnzkgfnjmphevz")] string input)
{
bool output = _bucketFormatter.ValidateBucketKey(input);
Assert.IsNotNull(output);
Assert.AreEqual(true, output);
}
[Test, Sequential]
public void ValidateBucketKey_WhenInvalidKey_ReturnsFalse(
[Values("", "-", "@", "Ab", "aB", "AB", "Ñ‘", "-gamename", "0gamename0.", "1example-", "zkia47pnzkGfnjmphevz", "Game Name")] string input)
{
bool output = _bucketFormatter.ValidateBucketKey(input);
Assert.IsNotNull(output);
Assert.AreEqual(false, output);
}
}
}
| 81 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.BucketManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
using UnityEditor;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class BootstrapSettingsTests
{
private readonly BucketUrlFormatter _bucketUrlFormatter = new BucketUrlFormatter();
#region CreateBucket
[Test]
public void CreateBucket_WhenCanCreateIsFalse_NotCalling()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Verify(target => target.CreateBucket(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never());
coreApiMock.Verify(target => target.PutBucketLifecycleConfiguration(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<BucketPolicy>()), Times.Never());
var bootstrapUtilityMock = new Mock<BootstrapUtility>(coreApiMock.Object);
bootstrapUtilityMock.Verify(target => target.GetBootstrapData(), Times.Never());
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock, bootstrapUtility: bootstrapUtilityMock);
// Act
underTest.CreateBucket();
// Assert
coreApiMock.Verify();
bootstrapUtilityMock.Verify();
}
[Test]
public void CreateBucket_WhenCanCreateAndBootstrapDataNotFound_IsStatusError()
{
const string testBucketName = "test-bucket";
var coreApiMock = new Mock<CoreApi>();
var currentResponse = new GetSettingResponse();
currentResponse = Response.Fail(currentResponse);
coreApiMock.Setup(target => target.GetSetting(It.IsAny<string>()))
.Returns(currentResponse)
.Verifiable();
var bootstrapUtilityMock = new Mock<BootstrapUtility>(coreApiMock.Object);
GetBootstrapDataResponse bootstrapResponse = Response.Fail(new GetBootstrapDataResponse());
bootstrapUtilityMock.Setup(target => target.GetBootstrapData())
.Returns(bootstrapResponse)
.Verifiable();
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock, bootstrapUtility: bootstrapUtilityMock);
underTest.SelectBucket(testBucketName);
// Act
underTest.CreateBucket();
// Assert
bootstrapUtilityMock.Verify();
Assert.AreEqual(MessageType.Error, underTest.Status.Type);
}
[Test]
public void CreateBucket_WhenCanCreateAndBootstrapDataFoundAndCreationFailed_IsStatusError()
{
const string testProfile = "test-profile";
const string testRegion = "test-region";
const string testBucketName = "test-bucket";
var coreApiMock = new Mock<CoreApi>();
var createResponse = new CreateBucketResponse();
createResponse = Response.Fail(createResponse);
coreApiMock.Setup(target => target.CreateBucket(testProfile, testRegion, It.IsAny<string>()))
.Returns(createResponse)
.Verifiable();
var bootstrapUtilityMock = new Mock<BootstrapUtility>(coreApiMock.Object);
var bootstrapResponse = new GetBootstrapDataResponse(testProfile, testRegion);
bootstrapResponse = Response.Ok(bootstrapResponse);
bootstrapUtilityMock.Setup(target => target.GetBootstrapData())
.Returns(bootstrapResponse)
.Verifiable();
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock, bootstrapUtility: bootstrapUtilityMock);
underTest.SelectBucket(testBucketName);
// Act
underTest.CreateBucket();
// Assert
coreApiMock.Verify();
bootstrapUtilityMock.Verify();
Assert.AreEqual(MessageType.Error, underTest.Status.Type);
}
[Test]
public void CreateBucket_WhenCanCreateAndBootstrapDataFoundAndCreationSuccessAndPutSettingFails_IsStatusError()
{
var coreApiMock = new Mock<CoreApi>();
var bootstrapUtilityMock = new Mock<BootstrapUtility>(coreApiMock.Object);
BootstrapSettings underTest = SetUpCreateBucketSuccess(isPutSettingSuccess: false, coreApiMock: coreApiMock, bootstrapUtilityMock: bootstrapUtilityMock);
// Act
underTest.CreateBucket();
// Assert
coreApiMock.Verify();
bootstrapUtilityMock.Verify();
Assert.AreEqual(MessageType.Error, underTest.Status.Type);
}
[Test]
public void CreateBucket_WhenCreationSuccessAndHasNoPolicy_IsStatusInfo()
{
var coreApiMock = new Mock<CoreApi>();
var bootstrapUtilityMock = new Mock<BootstrapUtility>(coreApiMock.Object);
coreApiMock.Verify(target => target.PutBucketLifecycleConfiguration(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<BucketPolicy>()), Times.Never());
BootstrapSettings underTest = SetUpCreateBucketSuccess(isPutSettingSuccess: true, coreApiMock: coreApiMock, bootstrapUtilityMock: bootstrapUtilityMock);
// Act
underTest.LifeCyclePolicyIndex = 0;
underTest.CreateBucket();
// Assert
coreApiMock.Verify();
bootstrapUtilityMock.Verify();
Assert.AreEqual(MessageType.Info, underTest.Status.Type);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void CreateBucket_WhenCreationSuccessAndHasPolicyAndPutPolicySuccessParam_IsStatusInfo(bool isPutPolicySuccess)
{
const string testProfile = "test-profile";
const string testRegion = "test-region";
const string testBucketName = "test-bucket";
var coreApiMock = new Mock<CoreApi>();
var bootstrapUtilityMock = new Mock<BootstrapUtility>(coreApiMock.Object);
var putPolicyResponse = new PutLifecycleConfigurationResponse();
putPolicyResponse = isPutPolicySuccess
? Response.Ok(putPolicyResponse)
: Response.Fail(putPolicyResponse);
coreApiMock.Setup(target => target.PutBucketLifecycleConfiguration(testProfile, testRegion, testBucketName, It.IsAny<BucketPolicy>()))
.Returns(putPolicyResponse)
.Verifiable();
BootstrapSettings underTest = SetUpCreateBucketSuccess(isPutSettingSuccess: true, testProfile, testRegion, testBucketName, coreApiMock, bootstrapUtilityMock);
// Act
underTest.LifeCyclePolicyIndex = 1;
underTest.CreateBucket();
// Assert
coreApiMock.Verify();
bootstrapUtilityMock.Verify();
Assert.AreEqual(MessageType.Info, underTest.Status.Type);
}
private static BootstrapSettings SetUpCreateBucketSuccess(bool isPutSettingSuccess,
string testProfile = "test-profile", string testRegion = "test-region", string testBucketName = "test-bucket",
Mock<CoreApi> coreApiMock = null, Mock<BootstrapUtility> bootstrapUtilityMock = null)
{
coreApiMock = coreApiMock ?? new Mock<CoreApi>();
// GetSettings is only called if PutSettings is successful
if (isPutSettingSuccess)
{
var currentResponse = new GetSettingResponse();
currentResponse = Response.Fail(currentResponse);
coreApiMock.Setup(target => target.GetSetting(It.IsAny<string>()))
.Returns(currentResponse)
.Verifiable();
}
var saveBucketResponse = new PutSettingResponse();
saveBucketResponse = isPutSettingSuccess
? Response.Ok(saveBucketResponse)
: Response.Fail(saveBucketResponse);
coreApiMock.Setup(target => target.PutSetting(SettingsKeys.CurrentBucketName, testBucketName))
.Returns(saveBucketResponse)
.Verifiable();
var createResponse = new CreateBucketResponse();
createResponse = Response.Ok(createResponse);
coreApiMock.Setup(target => target.CreateBucket(testProfile, testRegion, It.IsAny<string>()))
.Returns(createResponse)
.Verifiable();
bootstrapUtilityMock = bootstrapUtilityMock ?? new Mock<BootstrapUtility>(coreApiMock.Object);
var bootstrapResponse = new GetBootstrapDataResponse(testProfile, testRegion);
bootstrapResponse = Response.Ok(bootstrapResponse);
bootstrapUtilityMock.Setup(target => target.GetBootstrapData())
.Returns(bootstrapResponse)
.Verifiable();
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock, bootstrapUtility: bootstrapUtilityMock);
underTest.SelectBucket(testBucketName);
return underTest;
}
#endregion
#region Current Bucket
#region HasCurrentBucket
[Test]
public void HasCurrentBucket_WhenRefreshCurrentBucketAndBucketNotSavedAndRegionSaved_IsFalse()
{
const string testRegion = "test-region";
var coreApiMock = new Mock<CoreApi>();
GetSettingResponse bucketResponse = Response.Fail(new GetSettingResponse());
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentBucketName))
.Returns(bucketResponse)
.Verifiable();
var regionResponse = new GetSettingResponse() { Value = testRegion };
regionResponse = Response.Ok(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.IsValidRegion(testRegion))
.Returns(true);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshCurrentBucket();
// Assert
coreApiMock.Verify();
AssertNoCurrentBucket(underTest);
}
[Test]
public void HasCurrentBucket_WhenRefreshCurrentBucketAndBucketSavedAndRegionNotSaved_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithBucket(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: false, valid: false);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshCurrentBucket();
// Assert
coreApiMock.Verify();
AssertNoCurrentBucket(underTest);
}
[Test]
public void HasCurrentBucket_WhenRefreshCurrentBucketAndBucketSavedAndRegionSavedInvalid_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithBucket(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: false);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshCurrentBucket();
// Assert
coreApiMock.Verify();
AssertNoCurrentBucket(underTest);
}
[Test]
public void HasCurrentBucket_WhenRefreshCurrentBucketAndBucketAndRegionSaved_IsTrue()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiForBootstrapSuccess();
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshCurrentBucket();
// Assert
coreApiMock.Verify();
Assert.IsTrue(underTest.HasCurrentBucket);
}
#endregion
[Test]
public void CurrentBucketName_WhenRefreshCurrentBucketAndBucketAndRegionSaved_IsExpected()
{
const string testBucketName = "test-bucket";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiForBootstrapSuccess(testBucketName);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshCurrentBucket();
// Assert
coreApiMock.Verify();
Assert.AreEqual(testBucketName, underTest.CurrentBucketName);
}
[Test]
public void CurrentBucketUrl_WhenRefreshCurrentBucketAndBucketAndRegionSaved_IsExpected()
{
const string testBucketName = "test-bucket";
const string testRegion = "test-region";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiForBootstrapSuccess(testBucketName, testRegion);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshCurrentBucket();
// Assert
coreApiMock.Verify();
string expectedUrl = _bucketUrlFormatter.Format(testBucketName, testRegion);
Assert.AreEqual(expectedUrl, underTest.CurrentBucketUrl);
}
[Test]
public void CurrentRegion_WhenRefreshCurrentBucketAndBucketAndRegionSaved_IsExpected()
{
const string testRegion = "test-region";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiForBootstrapSuccess(testRegion: testRegion);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshCurrentBucket();
// Assert
coreApiMock.Verify();
Assert.AreEqual(testRegion, underTest.CurrentRegion);
}
[Test]
public void CurrentRegion_WhenRefreshCurrentBucketAndBucketSavedAndRegionSavedInvalid_IsNull()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithBucket(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: false);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshCurrentBucket();
string currentRegion = underTest.CurrentRegion;
// Assert
coreApiMock.Verify();
Assert.IsNull(currentRegion);
}
private static void AssertNoCurrentBucket(BootstrapSettings underTest)
{
Assert.IsFalse(underTest.HasCurrentBucket);
Assert.IsNull(underTest.CurrentBucketName);
Assert.IsNull(underTest.CurrentBucketUrl);
}
#endregion
[Test]
public void CurrentRegion_WhenRefreshBucketNameAndRegionNotSaved_IsNull()
{
var coreApiMock = new Mock<CoreApi>();
var regionResponse = new GetSettingResponse();
regionResponse = Response.Fail(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.IsValidRegion(It.IsAny<string>()))
.Returns(true);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshBucketName();
string currentRegion = underTest.CurrentRegion;
// Assert
coreApiMock.Verify();
Assert.IsNull(currentRegion);
}
[Test]
public void CurrentRegion_WhenRefreshBucketNameAndRegionSavedInvalid_IsNull()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithBucket(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: false);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshBucketName();
string currentRegion = underTest.CurrentRegion;
// Assert
coreApiMock.Verify();
Assert.IsNull(currentRegion);
}
[Test]
public void CurrentRegion_WhenRefreshBucketNameAndRegionAndAccountIdAndProfileSaved_IsExpected()
{
const string testRegion = "test-region";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: true, testRegion: testRegion);
coreApiMock.SetUpCoreApiWithAccountId(success: true);
coreApiMock.SetUpCoreApiWithProfile(success: true);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshBucketName();
string currentRegion = underTest.CurrentRegion;
// Assert
coreApiMock.Verify();
Assert.AreEqual(testRegion, currentRegion);
}
[Test]
public void BucketName_WhenRefreshBucketNameAndRegionNotSaved_IsNull()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithRegion(success: false, valid: false);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshBucketName();
string name = underTest.BucketName;
// Assert
coreApiMock.Verify();
Assert.IsNull(name);
}
[Test]
public void BucketName_WhenRefreshBucketNameAndRegionSavedAndInvalid_IsNull()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithBucket(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: false);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshBucketName();
string name = underTest.BucketName;
// Assert
coreApiMock.Verify();
Assert.IsNull(name);
}
[Test]
public void BucketName_WhenRefreshBucketNameAndCurrentProfileInvalid_IsNull()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiForBootstrapSuccess();
coreApiMock.SetUpCoreApiWithProfile(success: false);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshBucketName();
string name = underTest.BucketName;
// Assert
coreApiMock.Verify();
Assert.IsNull(name);
}
[Test]
public void BucketName_WhenRefreshBucketNameAndAccountIdInvalid_IsNull()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiForBootstrapSuccess();
coreApiMock.SetUpCoreApiWithProfile(success: true);
coreApiMock.SetUpCoreApiWithAccountId(success: false);
BootstrapSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.RefreshBucketName();
string name = underTest.BucketName;
// Assert
coreApiMock.Verify();
Assert.IsNull(name);
}
[Test]
public void BucketName_WhenRefreshBucketNameAndRegionAndAccountIdAndProfileSaved_IsExpected()
{
const string testBucketName = "test-bucket";
const string testRegion = "test-region";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: true, testRegion: testRegion);
coreApiMock.SetUpCoreApiWithAccountId(success: true);
coreApiMock.SetUpCoreApiWithProfile(success: true);
var bucketNameFormatterMock = new Mock<IBucketNameFormatter>();
bucketNameFormatterMock.Setup(target => target.FormatBucketName(It.IsAny<string>(), testRegion))
.Returns(testBucketName)
.Verifiable();
BootstrapSettings underTest = GetUnitUnderTest(bucketNameFormatterMock, coreApiMock);
// Act
underTest.RefreshBucketName();
string name = underTest.BucketName;
// Assert
coreApiMock.Verify();
Assert.AreEqual(testBucketName, name);
}
[Test]
public void BucketName_WhenNewInstance_IsNull()
{
var bucketNameFormatterMock = new Mock<IBucketNameFormatter>();
BootstrapSettings underTest = GetUnitUnderTest(bucketNameFormatterMock);
Assert.IsNull(underTest.BucketName);
}
private static BootstrapSettings GetUnitUnderTest(Mock<IBucketNameFormatter> bucketNameFormatterMock = null,
Mock<CoreApi> coreApi = null,
Mock<BootstrapUtility> bootstrapUtility = null)
{
bucketNameFormatterMock = bucketNameFormatterMock ?? new Mock<IBucketNameFormatter>();
coreApi = coreApi ?? new Mock<CoreApi>();
bootstrapUtility = bootstrapUtility ?? new Mock<BootstrapUtility>(coreApi.Object);
TextProvider textProvider = TextProviderFactory.Create();
string[] policyNames = new string[] { "none", "30 days" };
var lifecyclePolicies = new BucketPolicy[] { BucketPolicy.None, BucketPolicy.ThirtyDaysLifecycle };
return new BootstrapSettings(lifecyclePolicies, policyNames, textProvider, bucketNameFormatterMock.Object, new MockLogger(), coreApi.Object, bootstrapUtility.Object);
}
}
}
| 562 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class BootstrapUtilityTests
{
[Test]
public void GetBootstrapData_WhenBucketNotSavedAndRegionSaved_SuccessIsFalse()
{
const string testRegion = "test-region";
var coreApiMock = new Mock<CoreApi>();
GetSettingResponse profileResponse = Response.Fail(new GetSettingResponse());
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentProfileName))
.Returns(profileResponse)
.Verifiable();
var regionResponse = new GetSettingResponse() { Value = testRegion };
regionResponse = Response.Ok(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
var underTest = new BootstrapUtility(coreApiMock.Object);
// Act
GetBootstrapDataResponse actualResponse = underTest.GetBootstrapData();
// Assert
coreApiMock.Verify();
Assert.IsFalse(actualResponse.Success);
}
[Test]
public void GetBootstrapData_WhenBucketSavedAndRegionNotSaved_SuccessIsFalse()
{
const string testProfile = "test-profile";
var coreApiMock = new Mock<CoreApi>();
var profileResponse = new GetSettingResponse() { Value = testProfile };
profileResponse = Response.Ok(profileResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentProfileName))
.Returns(profileResponse);
var regionResponse = new GetSettingResponse();
regionResponse = Response.Fail(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
var underTest = new BootstrapUtility(coreApiMock.Object);
// Act
GetBootstrapDataResponse actualResponse = underTest.GetBootstrapData();
// Assert
coreApiMock.Verify();
Assert.IsFalse(actualResponse.Success);
}
[Test]
public void GetBootstrapData_WhenBucketSavedAndRegionSaved_SuccessIsTrue()
{
const string testProfile = "test-profile";
const string testRegion = "test-region";
Mock<CoreApi> coreApiMock = SetUpCoreApiForSuccess(testProfile, testRegion);
var underTest = new BootstrapUtility(coreApiMock.Object);
// Act
GetBootstrapDataResponse actualResponse = underTest.GetBootstrapData();
// Assert
coreApiMock.Verify();
Assert.IsTrue(actualResponse.Success);
}
[Test]
public void GetBootstrapData_WhenBucketSavedAndRegionSaved_ProfileIsExpected()
{
const string testProfile = "test-profile";
const string testRegion = "test-region";
Mock<CoreApi> coreApiMock = SetUpCoreApiForSuccess(testProfile, testRegion);
var underTest = new BootstrapUtility(coreApiMock.Object);
// Act
GetBootstrapDataResponse actualResponse = underTest.GetBootstrapData();
// Assert
coreApiMock.Verify();
Assert.AreEqual(testProfile, actualResponse.Profile);
}
[Test]
public void GetBootstrapData_WhenBucketSavedAndRegionSaved_RegionIsExpected()
{
const string testProfile = "test-profile";
const string testRegion = "test-region";
Mock<CoreApi> coreApiMock = SetUpCoreApiForSuccess(testProfile, testRegion);
var underTest = new BootstrapUtility(coreApiMock.Object);
// Act
GetBootstrapDataResponse actualResponse = underTest.GetBootstrapData();
// Assert
coreApiMock.Verify();
Assert.AreEqual(testRegion, actualResponse.Region);
}
private Mock<CoreApi> SetUpCoreApiForSuccess(string testProfile, string testRegion)
{
var coreApiMock = new Mock<CoreApi>();
var profileResponse = new GetSettingResponse() { Value = testProfile };
profileResponse = Response.Ok(profileResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentProfileName))
.Returns(profileResponse)
.Verifiable();
var regionResponse = new GetSettingResponse() { Value = testRegion };
regionResponse = Response.Ok(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
return coreApiMock;
}
}
}
| 142 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using AmazonGameLift.Editor;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class BucketUrlFormatterTests
{
private readonly BucketUrlFormatter _bucketFormatter = new BucketUrlFormatter();
[Test]
public void Format_WhenNullBucketName_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => _bucketFormatter.Format(null, "any"));
}
[Test]
public void Format_WhenNullRegion_ThrowsException()
{
Assert.Throws<ArgumentNullException>(() => _bucketFormatter.Format("any", null));
}
[Test]
public void Format_WhenLongBucketName_ThrowsException()
{
const string bucket = "any_long_bucket_name_is_invalid_if_it_is_longer_than__63_symbols";
Assert.Throws<ArgumentException>(() => _bucketFormatter.Format(bucket, "any"));
}
[Test]
public void Format_WhenValidArguments_ReturnsString()
{
string bucketName = "NonEmpty";
string region = "NonEmpty";
string output = _bucketFormatter.Format(bucketName, region);
Assert.IsNotEmpty(output);
}
}
}
| 45 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
using UnityEngine.TestTools;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class DeployerTests
{
private const string TestS3BucketKey = "nonempty";
private static readonly bool[] s_boolValues = new bool[] { true, false };
[Test]
public void StartDeployment_WhenSenarioFolderPathIsNull_ThrowsArgumentNullException()
{
const string testGameName = "test";
var coreApiMock = new Mock<CoreApi>();
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
AssertAsync.ThrowsAsync<ArgumentNullException>(async () => await underTest.StartDeployment(null, TestS3BucketKey, testGameName, true, ConfirmChangeSetTask));
}
[Test]
public void StartDeployment_WhenGameNameIsNull_ThrowsArgumentNullException()
{
const string testScenarioPath = "C:/test";
var coreApiMock = new Mock<CoreApi>();
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
AssertAsync.ThrowsAsync<ArgumentNullException>(async () => await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, null, true, ConfirmChangeSetTask));
}
#region StartDeployment Success
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestFailure_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase _, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestFailure();
Assert.IsFalse(response.Success);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestSuccessAndValidateCfnTemplateFailure_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase _, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestSuccessAndValidateCfnTemplateFailure();
Assert.IsFalse(response.Success);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestSuccessAndCreateChangeSetFailure_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase _, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestSuccessAndCreateChangeSetFailure();
Assert.IsFalse(response.Success);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestSuccessAndDescribeChangeSetFailure_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase _, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestSuccessAndDescribeChangeSetFailure();
Assert.IsFalse(response.Success);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestSuccessAndDescribeChangeSetNotAvailable_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase _, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestSuccessAndDescribeChangeSetNotAvailable();
Assert.IsFalse(response.Success);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestSuccessAndStackExistsFailure_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase _, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestSuccessAndStackExistsFailure();
Assert.IsFalse(response.Success);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestSuccessAndNotConfirmed_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase _, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestSuccessAndNotConfirmed();
Assert.IsFalse(response.Success);
Assert.AreEqual(response.ErrorCode, AmazonGameLift.Editor.ErrorCode.OperationCancelled);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestSuccessAndDeploySuccessIsExpected_SuccessIsIsExpected(
[ValueSource(nameof(s_boolValues))] bool expected)
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase _, DeploymentRequest _, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestSuccessAndDeploySuccess(expected);
Assert.AreEqual(expected, response.Success);
}
}
#endregion
[UnityTest]
public IEnumerator StartDeployment_WhenCreateRequestSuccessAndDeploySuccess_DeploymentIdIsExpected()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeployerBase deployer, DeploymentRequest request, DeploymentResponse response) = await TestStartDeploymentWhenCreateRequestSuccessAndDeploySuccess(true);
Assert.AreEqual(request.Profile, response.DeploymentId.Profile);
Assert.AreEqual(request.Region, response.DeploymentId.Region);
Assert.AreEqual(deployer.DisplayName, response.DeploymentId.ScenarioName);
Assert.AreEqual(request.StackName, response.DeploymentId.StackName);
}
}
private async Task<(DeployerBase underTest, DeploymentResponse response)> TestStartDeploymentWhenCreateRequestFailure()
{
const string testGameName = "test";
const string testScenarioPath = "C:/test";
var coreApiMock = new Mock<CoreApi>();
var requestFactoryMock = new Mock<DeploymentRequestFactory>(coreApiMock.Object);
requestFactoryMock.Setup(target => target.CreateRequest(testScenarioPath, testGameName, true))
.Returns((null, false, Response.Fail(new Response())))
.Verifiable();
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
underTest.RequestFactory = requestFactoryMock.Object;
// Act
DeploymentResponse response = await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, testGameName, true, ConfirmChangeSetTask);
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeployerBase underTest, DeploymentResponse response)> TestStartDeploymentWhenCreateRequestSuccessAndValidateCfnTemplateFailure()
{
const string testGameName = "test";
const string testScenarioPath = "C:/test";
var coreApiMock = new Mock<CoreApi>();
Mock<DeploymentRequestFactory> requestFactoryMock = SetUpRequestMockForSuccess(testGameName,
testScenarioPath, coreApiMock, out DeploymentRequest request);
SetUpCoreApiWithValidateCfnTemplate(coreApiMock, success: false, request.Profile, request.Region, request.CfnTemplatePath);
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
underTest.RequestFactory = requestFactoryMock.Object;
// Act
DeploymentResponse response = await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, testGameName, true, ConfirmChangeSetTask);
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeployerBase underTest, DeploymentResponse response)> TestStartDeploymentWhenCreateRequestSuccessAndCreateChangeSetFailure()
{
const string testGameName = "test";
const string testScenarioPath = "C:/test";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpGetStackNameAsGameName(testGameName);
Mock<DeploymentRequestFactory> requestFactoryMock = SetUpRequestMockForSuccess(testGameName,
testScenarioPath, coreApiMock, out DeploymentRequest request);
SetUpCoreApiWithValidateCfnTemplate(coreApiMock, success: true, request.Profile, request.Region, request.CfnTemplatePath);
SetUpCoreApiWithCreateChangeSet(coreApiMock, success: false, request.Profile, request.Region,
request.BucketName, request.StackName, request.CfnTemplatePath, request.ParametersPath,
request.GameName, request.LambdaFolderPath, request.BuildS3Key);
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
underTest.RequestFactory = requestFactoryMock.Object;
// Act
DeploymentResponse response = await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, testGameName, true, ConfirmChangeSetTask);
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeployerBase underTest, DeploymentResponse response)> TestStartDeploymentWhenCreateRequestSuccessAndDescribeChangeSetFailure()
{
const string testGameName = "test";
const string testScenarioPath = "C:/test";
const string testChangeSet = "test-set";
var coreApiMock = new Mock<CoreApi>();
Mock<DeploymentRequestFactory> requestFactoryMock = SetUpRequestMockForSuccess(testGameName,
testScenarioPath, coreApiMock, out DeploymentRequest request);
SetUpCoreApiWithValidateCfnTemplate(coreApiMock, success: true, request.Profile, request.Region, request.CfnTemplatePath);
SetUpCoreApiWithCreateChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.BucketName, request.StackName, request.CfnTemplatePath, request.ParametersPath,
request.GameName, request.LambdaFolderPath, request.BuildS3Key, testChangeSet);
SetUpCoreApiWithDescribeChangeSet(coreApiMock, success: false, request.Profile, request.Region,
request.StackName, testChangeSet);
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
underTest.RequestFactory = requestFactoryMock.Object;
// Act
DeploymentResponse response = await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, testGameName, true, ConfirmChangeSetTask);
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeployerBase underTest, DeploymentResponse response)> TestStartDeploymentWhenCreateRequestSuccessAndDescribeChangeSetNotAvailable()
{
const string testGameName = "test";
const string testScenarioPath = "C:/test";
const string testChangeSet = "test-set";
var coreApiMock = new Mock<CoreApi>();
Mock<DeploymentRequestFactory> requestFactoryMock = SetUpRequestMockForSuccess(testGameName,
testScenarioPath, coreApiMock, out DeploymentRequest request);
SetUpCoreApiWithValidateCfnTemplate(coreApiMock, success: true, request.Profile, request.Region, request.CfnTemplatePath);
SetUpCoreApiWithCreateChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.BucketName, request.StackName, request.CfnTemplatePath, request.ParametersPath,
request.GameName, request.LambdaFolderPath, request.BuildS3Key, testChangeSet);
SetUpCoreApiWithDescribeChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.StackName, testChangeSet, ChangeSetExecutionStatus.Obsolete);
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
underTest.RequestFactory = requestFactoryMock.Object;
// Act
DeploymentResponse response = await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, testGameName, true, ConfirmChangeSetTask);
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeployerBase underTest, DeploymentResponse response)> TestStartDeploymentWhenCreateRequestSuccessAndStackExistsFailure()
{
const string testGameName = "test";
const string testScenarioPath = "C:/test";
const string testChangeSet = "test-set";
var coreApiMock = new Mock<CoreApi>();
Mock<DeploymentRequestFactory> requestFactoryMock = SetUpRequestMockForSuccess(testGameName,
testScenarioPath, coreApiMock, out DeploymentRequest request);
SetUpCoreApiWithValidateCfnTemplate(coreApiMock, success: true, request.Profile, request.Region, request.CfnTemplatePath);
SetUpCoreApiWithCreateChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.BucketName, request.StackName, request.CfnTemplatePath, request.ParametersPath,
request.GameName, request.LambdaFolderPath, request.BuildS3Key, testChangeSet);
SetUpCoreApiWithDescribeChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.StackName, testChangeSet);
coreApiMock.SetUpCoreApiWithDescribeStack(success: false, request.Profile, request.Region,
request.StackName);
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
underTest.RequestFactory = requestFactoryMock.Object;
// Act
DeploymentResponse response = await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, testGameName, true, ConfirmChangeSetTask);
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeployerBase underTest, DeploymentResponse response)> TestStartDeploymentWhenCreateRequestSuccessAndNotConfirmed()
{
const string testGameName = "test";
const string testScenarioPath = "C:/test";
const string testChangeSet = "test-set";
var coreApiMock = new Mock<CoreApi>();
Mock<DeploymentRequestFactory> requestFactoryMock = SetUpRequestMockForSuccess(testGameName,
testScenarioPath, coreApiMock, out DeploymentRequest request);
SetUpCoreApiWithValidateCfnTemplate(coreApiMock, success: true, request.Profile, request.Region, request.CfnTemplatePath);
SetUpCoreApiWithCreateChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.BucketName, request.StackName, request.CfnTemplatePath, request.ParametersPath,
request.GameName, request.LambdaFolderPath, request.BuildS3Key, testChangeSet);
SetUpCoreApiWithDescribeChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.StackName, testChangeSet);
coreApiMock.SetUpCoreApiWithDescribeStack(success: true, request.Profile, request.Region,
request.StackName);
ConfirmChangesDelegate dontConfirmChanges = _ => Task.FromResult(false);
TestedDeployer underTest = GetTestedDeployer(coreApiMock);
underTest.RequestFactory = requestFactoryMock.Object;
// Act
DeploymentResponse response = await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, testGameName, true, dontConfirmChanges);
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeployerBase underTest, DeploymentRequest request, DeploymentResponse response)> TestStartDeploymentWhenCreateRequestSuccessAndDeploySuccess(bool deployReturnsSuccess)
{
const string testGameName = "test";
const string testScenarioPath = "C:/test";
const string testChangeSet = "test-set";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpGetStackNameAsGameName(testGameName);
Mock<DeploymentRequestFactory> requestFactoryMock = SetUpRequestMockForSuccess(testGameName,
testScenarioPath, coreApiMock, out DeploymentRequest request);
SetUpCoreApiWithValidateCfnTemplate(coreApiMock, success: true, request.Profile, request.Region, request.CfnTemplatePath);
SetUpCoreApiWithCreateChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.BucketName, request.StackName, request.CfnTemplatePath, request.ParametersPath,
request.GameName, request.LambdaFolderPath, request.BuildS3Key, testChangeSet);
SetUpCoreApiWithDescribeChangeSet(coreApiMock, success: true, request.Profile, request.Region,
request.StackName, testChangeSet);
coreApiMock.SetUpCoreApiWithDescribeStack(success: true, request.Profile, request.Region,
request.StackName, result: StackStatus.ReviewInProgress);
TestedDeployer underTest = GetTestedDeployer(coreApiMock, deployReturnsSuccess);
underTest.RequestFactory = requestFactoryMock.Object;
// Act
DeploymentResponse response = await underTest.StartDeployment(testScenarioPath, TestS3BucketKey, testGameName, true, ConfirmChangeSetTask);
// Assert
coreApiMock.Verify();
return (underTest, request, response);
}
private static Mock<DeploymentRequestFactory> SetUpRequestMockForSuccess(string testGameName, string testScenarioPath,
Mock<CoreApi> coreApiMock, out DeploymentRequest request)
{
const string testBuildPath = "C:/testbuild";
var requestFactoryMock = new Mock<DeploymentRequestFactory>(coreApiMock.Object);
var requestLocal = new DeploymentRequest()
{
BucketName = "test-bucket",
CfnTemplatePath = "C:/test/template.yml",
GameName = testGameName,
LambdaFolderPath = "C:/test/l",
ParametersPath = "C:/test/p.json",
Profile = "test-profile",
Region = "test-region",
StackName = testGameName,
};
request = requestLocal;
requestFactoryMock.Setup(target => target.CreateRequest(testScenarioPath, testGameName, true))
.Returns((request, true, null))
.Verifiable();
requestFactoryMock.Setup(target => target.WithServerBuild(requestLocal, testBuildPath))
.CallBase();
return requestFactoryMock;
}
private static void SetUpCoreApiWithValidateCfnTemplate(Mock<CoreApi> coreApiMock, bool success,
string profileName, string region, string templateFilePath)
{
var response = new ValidateCfnTemplateResponse();
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.ValidateCfnTemplate(profileName, region, templateFilePath))
.Returns(response)
.Verifiable();
}
private static void SetUpCoreApiWithCreateChangeSet(Mock<CoreApi> coreApiMock, bool success,
string profileName, string region, string bucketName, string stackName,
string templateFilePath, string parametersFilePath, string gameName, string lambdaFolderPath,
string buildS3Key, string result = "test-cs")
{
var response = new CreateChangeSetResponse() { CreatedChangeSetName = result };
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.CreateChangeSet(profileName, region, bucketName,
stackName, templateFilePath, parametersFilePath, gameName, lambdaFolderPath, buildS3Key))
.Returns(response)
.Verifiable();
}
private static void SetUpCoreApiWithDescribeChangeSet(Mock<CoreApi> coreApiMock, bool success,
string profileName, string region, string stackName, string changeSetName,
string resultExecutionStatus = ChangeSetExecutionStatus.Available)
{
var response = new DescribeChangeSetResponse()
{
ExecutionStatus = resultExecutionStatus,
Changes = new Change[0]
};
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.DescribeChangeSet(profileName, region, stackName, changeSetName))
.Returns(response)
.Verifiable();
}
private static Task<bool> ConfirmChangeSetTask(ConfirmChangesRequest _)
{
return Task.FromResult(true);
}
private static TestedDeployer GetTestedDeployer(Mock<CoreApi> coreApiMock, bool deployReturnsSuccess = true, bool hasGameServer = false)
{
var delayMock = new Mock<Delay>();
delayMock.Setup(target => target.Wait(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
return new TestedDeployer(delayMock.Object, coreApiMock.Object, deployReturnsSuccess, hasGameServer);
}
}
}
| 459 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.IO;
using System.Linq;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class DeploymentRequestFactoryTests
{
private const string TestGameName = "test";
private const string TestBuildPath = "C:/testbuild";
private const string TestScenarioPath = "C:/test";
#region CreateRequest
[Test]
public void CreateRequest_WhenSenarioFolderPathIsNull_ThrowsArgumentNullException()
{
var coreApiMock = new Mock<CoreApi>();
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
Assert.Throws<ArgumentNullException>(() => underTest.CreateRequest(null, TestGameName, true));
}
[Test]
public void CreateRequest_WhenSenarioFolderPathIsInvalid_ThrowsArgumentException()
{
string testPath = Path.GetInvalidPathChars().First().ToString();
var coreApiMock = new Mock<CoreApi>();
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
Assert.Throws<ArgumentException>(() => underTest.CreateRequest(testPath, TestGameName, true));
}
[Test]
public void CreateRequest_WhenGameNameIsNull_ThrowsArgumentNullException()
{
var coreApiMock = new Mock<CoreApi>();
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
Assert.Throws<ArgumentNullException>(() => underTest.CreateRequest(TestScenarioPath, null, true));
}
[Test]
public void CreateRequest_WhenProfileNotSet_SuccessIsFalse()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithProfile(success: false);
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
(DeploymentRequest _, bool success, Response failedResponse) = underTest
.CreateRequest(TestScenarioPath, TestGameName, true);
// Assert
Assert.IsFalse(success);
Assert.IsNotNull(failedResponse);
}
[Test]
public void CreateRequest_WhenRegionNotSet_SuccessIsFalse()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithProfile(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: false, valid: false);
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
(DeploymentRequest _, bool success, Response failedResponse) = underTest
.CreateRequest(TestScenarioPath, TestGameName, true);
// Assert
Assert.IsFalse(success);
Assert.IsNotNull(failedResponse);
}
[Test]
public void CreateRequest_WhenBucketNotSet_SuccessIsFalse()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithProfile(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: true);
coreApiMock.SetUpCoreApiWithBucket(success: false);
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
(DeploymentRequest _, bool success, Response failedResponse) = underTest
.CreateRequest(TestScenarioPath, TestGameName, true);
// Assert
Assert.IsFalse(success);
Assert.IsNotNull(failedResponse);
}
[Test]
public void CreateRequest_WhenAllSet_SuccessIsTrue()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithProfile(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: true);
coreApiMock.SetUpCoreApiWithBucket(success: true);
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
(DeploymentRequest request, bool success, Response failedResponse) = underTest
.CreateRequest(TestScenarioPath, TestGameName, true);
// Assert
Assert.IsTrue(success);
Assert.IsNotNull(request);
Assert.IsNull(failedResponse);
}
[Test]
public void CreateRequest_WhenAllSet_RequestIsValid()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithProfile(success: true);
coreApiMock.SetUpCoreApiWithRegion(success: true, valid: true);
coreApiMock.SetUpCoreApiWithBucket(success: true);
coreApiMock.SetUpGetStackNameAsGameName(TestGameName);
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
(DeploymentRequest request, bool _, Response _) = underTest
.CreateRequest(TestScenarioPath, TestGameName, true);
// Assert
Assert.IsNotNull(request);
Assert.IsNotNull(request.BucketName);
Assert.IsNotNull(request.CfnTemplatePath);
Assert.IsNotNull(request.GameName);
Assert.IsNotNull(request.LambdaFolderPath);
Assert.IsNotNull(request.ParametersPath);
Assert.IsNotNull(request.Profile);
Assert.IsNotNull(request.Region);
Assert.IsNotNull(request.StackName);
}
#endregion
#region
[Test]
public void WithServerBuild_WhenRequestIsNull_ThrowsArgumentNullException()
{
var coreApiMock = new Mock<CoreApi>();
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
Assert.Throws<ArgumentNullException>(() => underTest.WithServerBuild(null, TestBuildPath));
}
[Test]
public void WithServerBuild_WhenBuildFolderPathIsNull_ThrowsArgumentNullException()
{
var coreApiMock = new Mock<CoreApi>();
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
Assert.Throws<ArgumentNullException>(() => underTest.WithServerBuild(new DeploymentRequest(), null));
}
[Test]
public void WithServerBuild_WhenAllSet_ModifiesRequest()
{
const string testKey = "testKey";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpGetBuildS3Key(testKey);
var underTest = new DeploymentRequestFactory(coreApiMock.Object);
DeploymentRequest result = underTest.WithServerBuild(new DeploymentRequest(), TestBuildPath);
// Assert
Assert.AreEqual(TestBuildPath, result.BuildFolderPath);
Assert.AreEqual(testKey, result.BuildS3Key);
}
#endregion
}
}
| 188 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class DeploymentSettingsTests
{
private static readonly bool[] s_boolValues = new bool[] { true, false };
#region Form persistence
[Test]
[TestCase(true)]
[TestCase(false)]
public void ScenarioIndex_WhenFormFilledAndRestore_IsExpected(bool coreSuccess)
{
int testIndex = UnityEngine.Random.Range(int.MinValue, int.MaxValue);
int testIndex1 = UnityEngine.Random.Range(int.MinValue, int.MaxValue);
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentScenarioIndex, coreSuccess, SettingsFormatter.FormatInt(testIndex1));
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentGameName, false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentBuildFolderPath, false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentBuildFilePath, false, null);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.ScenarioIndex = testIndex;
underTest.Restore();
// Assert
Assert.AreEqual(coreSuccess ? testIndex1 : 1, underTest.ScenarioIndex);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void GameName_WhenFormFilledAndRestore_IsExpected(bool coreSuccess)
{
string id = DateTime.UtcNow.Ticks.ToString();
string testGameName = "test" + id;
string testGameName1 = "test1" + id;
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentGameName, coreSuccess, testGameName1);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentScenarioIndex, false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentBuildFolderPath, false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentBuildFilePath, false, null);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.GameName = testGameName;
underTest.Restore();
// Assert
Assert.AreEqual(coreSuccess ? testGameName1 : null, underTest.GameName);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void BuildFolderPath_WhenFormFilledAndRestore_IsExpected(bool coreSuccess)
{
string id = DateTime.UtcNow.Ticks.ToString();
string testBuildFolderPath = "test path" + id;
string testBuildFolderPath1 = "test path1" + id;
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentBuildFolderPath, coreSuccess, testBuildFolderPath1);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentGameName, false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentScenarioIndex, false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentBuildFilePath, false, null);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.BuildFolderPath = testBuildFolderPath;
underTest.Restore();
// Assert
Assert.AreEqual(coreSuccess ? testBuildFolderPath1 : null, underTest.BuildFolderPath);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void BuildFilePath_WhenFormFilledAndRestore_IsExpected(bool coreSuccess)
{
string id = DateTime.UtcNow.Ticks.ToString();
string testBuildExePath = "test path" + id;
string testBuildExePath1 = "test path1" + id;
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentBuildFilePath, coreSuccess, testBuildExePath1);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentGameName, false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentScenarioIndex, false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.DeploymentBuildFolderPath, false, null);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Act
underTest.BuildFolderPath = testBuildExePath;
underTest.Restore();
// Assert
Assert.AreEqual(coreSuccess ? testBuildExePath1 : null, underTest.BuildFilePath);
}
#endregion
#region IsBootstrapped
[Test]
public void IsBootstrapped_WhenNewInstance_IsFalse()
{
DeploymentSettings underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.IsBootstrapped);
}
[Test]
[TestCase(false, false, false, false)]
[TestCase(false, false, false, true)]
[TestCase(false, false, true, false)]
[TestCase(false, false, true, true)]
[TestCase(false, true, false, false)]
[TestCase(false, true, false, true)]
[TestCase(false, true, true, true)]
[TestCase(true, false, false, false)]
[TestCase(true, false, false, true)]
[TestCase(true, false, true, true)]
[TestCase(true, true, true, true)]
public void IsBootstrapped_WhenRefreshAndSettingsSetParam_IsExpected(bool profileSet, bool bucketSet, bool regionSet, bool regionValid)
{
bool expected = profileSet && bucketSet && regionSet && regionValid;
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithProfile(success: profileSet);
coreApiMock.SetUpCoreApiWithBucket(success: bucketSet);
coreApiMock.SetUpCoreApiWithRegion(success: regionSet, regionValid);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
underTest.GameName = null;
underTest.Refresh();
coreApiMock.Verify();
Assert.AreEqual(expected, underTest.IsBootstrapped);
}
#endregion
#region Form validation
[Test]
public void IsFormFilled_WhenNewInstance_IsFalse()
{
DeploymentSettings underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.IsFormFilled);
}
[Test]
public void IsFormFilled_WhenFieldsFilledAndNoServerBuild_IsTrue()
{
DeploymentSettings underTest = TestWhenFieldsFilledAndNoServerBuild();
Assert.IsTrue(underTest.IsFormFilled);
}
[Test]
public void IsBuildPathFilled_WhenFieldsFilledAndNoServerBuild_IsTrue()
{
DeploymentSettings underTest = TestWhenFieldsFilledAndNoServerBuild();
Assert.IsTrue(underTest.IsBuildFolderPathFilled);
}
private DeploymentSettings TestWhenFieldsFilledAndNoServerBuild()
{
const string testGameName = "test";
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
coreApiMock.Setup(target => target.FolderExists(It.IsAny<string>()))
.Returns(false);
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = 0;
underTest.BuildFolderPath = "test path";
underTest.BuildFilePath = "test path/build.exe";
underTest.GameName = testGameName;
// Assert
scenarioLocatorMock.Verify();
return underTest;
}
[Test]
[TestCase(false, false, false)]
[TestCase(false, true, false)]
[TestCase(true, false, false)]
[TestCase(true, true, true)]
public void IsFormFilled_WhenFieldsFilledAndServerBuildPathFilledParam_IsExpected(bool buildFolderExists, bool buildExeExists, bool expected)
{
DeploymentSettings underTest = TestWhenFieldsFilledAndServerBuild(buildFolderExists, buildExeExists);
Assert.AreEqual(expected, underTest.IsFormFilled);
}
[Test]
[TestCase(false, false, false)]
[TestCase(false, true, false)]
[TestCase(true, false, true)]
[TestCase(true, true, true)]
public void IsBuildFolderPathFilled_WhenFieldsFilledAndServerBuildPathFilledParam_IsExpected(bool buildFolderExists, bool buildExeExists, bool expected)
{
DeploymentSettings underTest = TestWhenFieldsFilledAndServerBuild(buildFolderExists, buildExeExists);
Assert.AreEqual(expected, underTest.IsBuildFolderPathFilled);
}
[Test]
[TestCase(false, false, false)]
[TestCase(false, true, true)]
[TestCase(true, false, false)]
[TestCase(true, true, true)]
public void IsBuildFilePathFilled_WhenFieldsFilledAndServerBuildPathFilledParam_IsExpected(bool buildFolderExists, bool buildExeExists, bool expected)
{
DeploymentSettings underTest = TestWhenFieldsFilledAndServerBuild(buildFolderExists, buildExeExists);
Assert.AreEqual(expected, underTest.IsBuildFilePathFilled);
}
private DeploymentSettings TestWhenFieldsFilledAndServerBuild(bool buildFolderExists, bool buildExeExists)
{
const string testGameName = "test";
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
coreApiMock.Setup(target => target.FolderExists(It.IsAny<string>()))
.Returns(buildFolderExists)
.Verifiable();
coreApiMock.Setup(target => target.FileExists(It.IsAny<string>()))
.Returns(buildExeExists)
.Verifiable();
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: true, coreApiMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = 0;
underTest.BuildFolderPath = "test path";
underTest.BuildFilePath = "test path/build.exe";
underTest.GameName = testGameName;
// Assert
scenarioLocatorMock.Verify();
return underTest;
}
[Test]
public void IsValidScenarioIndex_WhenRefreshAndScenarioIndexNegative_IsFalse()
{
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock);
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = -1;
// Assert
scenarioLocatorMock.Verify();
Assert.IsFalse(underTest.IsValidScenarioIndex);
}
[Test]
public void IsValidScenarioIndex_WhenRefreshAndScenarioIndexOutOfRange_IsFalse()
{
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock);
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = 1;
// Assert
scenarioLocatorMock.Verify();
Assert.IsFalse(underTest.IsValidScenarioIndex);
}
[Test]
public void IsValidScenarioIndex_WhenRefreshAndScenarioIndexInRange_IsTrue()
{
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock);
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = 0;
// Assert
scenarioLocatorMock.Verify();
Assert.IsTrue(underTest.IsValidScenarioIndex);
}
#endregion
[Test]
public void ScenarioName_WhenRefresh_IsExpected()
{
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock);
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = 0;
// Assert
scenarioLocatorMock.Verify();
Assert.AreEqual(testScenarioName, underTest.ScenarioName);
}
[Test]
public void ScenarioPath_WhenNewInstance_IsNull()
{
DeploymentSettings underTest = GetUnitUnderTest();
Assert.IsNull(underTest.ScenarioPath);
}
[Test]
public void ScenarioPath_WhenRefresh_IsExpected()
{
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
string expectedFolderPath = "expected";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock);
var pathConverterMock = new Mock<PathConverter>(coreApiMock.Object);
pathConverterMock.Setup(target => target.GetScenarioAbsolutePath(testScenarioName))
.Returns(expectedFolderPath)
.Verifiable();
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock, scenarioFolder: testScenarioName);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock, pathConverter: pathConverterMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = 0;
// Assert
pathConverterMock.Verify();
scenarioLocatorMock.Verify();
Assert.AreEqual(expectedFolderPath, underTest.ScenarioPath);
}
[Test]
public void ScenarioDescription_WhenRefresh_IsExpected()
{
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock);
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = 0;
// Assert
scenarioLocatorMock.Verify();
Assert.AreEqual(testScenarioDescription, underTest.ScenarioDescription);
}
[Test]
public void ScenarioHelpUrl_WhenRefresh_IsExpected()
{
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock);
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
// Act
underTest.Refresh();
underTest.ScenarioIndex = 0;
// Assert
scenarioLocatorMock.Verify();
Assert.AreEqual(testScenarioUrl, underTest.ScenarioHelpUrl);
}
[UnityTest]
public IEnumerator ScenarioLocator_WhenRefreshAndScenarioSelected_IsExececuted([ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
var scenarioLocatorMock = new Mock<ScenarioLocator>();
DeploymentSettings underTest = SetUpStartDeployment(
deployerMock => SetUpDeployerStartDeployment(deployerMock, success: true),
waitSuccess: true, hasGameServer, scenarioLocatorMock: scenarioLocatorMock);
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
// Assert
scenarioLocatorMock.Verify();
}
}
#region IsDeploymentRunning
[Test]
public void IsDeploymentRunning_WhenNewInstance_IsFalse()
{
DeploymentSettings underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.IsDeploymentRunning);
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenRefreshAndScenarioSelectedAndStartDeploymentSuccess_IsFalse([ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
DeploymentSettings underTest = SetUpStartDeployment(deployerMock =>
SetUpDeployerStartDeployment(deployerMock, success: true), waitSuccess: true, hasGameServer);
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
Assert.IsFalse(underTest.IsDeploymentRunning);
}
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenRefreshAndScenarioSelectedAndStartDeploymentFailure_IsFalse(
[ValueSource(nameof(s_boolValues))] bool waitSuccess,
[ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
DeploymentSettings underTest = SetUpStartDeployment(deployerMock =>
SetUpDeployerStartDeployment(deployerMock, success: false), waitSuccess, hasGameServer);
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
Assert.IsFalse(underTest.IsDeploymentRunning);
}
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenRefreshAndScenarioSelectedAndStartDeploymentException_IsFalse([ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testMessage = "TestException";
await TestWhenRefreshAndScenarioSelectedAndStartDeploymentException(testMessage, hasGameServer, underTest => Assert.IsFalse(underTest.IsDeploymentRunning));
}
}
#endregion
#region CanCancel
[Test]
public void CanCancel_WhenNewInstance_IsFalse()
{
DeploymentSettings underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.CanCancel);
}
[UnityTest]
public IEnumerator CanCancel_WhenRefreshAndScenarioSelectedAndStartDeploymentSuccess_IsFalse(
[ValueSource(nameof(s_boolValues))] bool waitSuccess,
[ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
DeploymentSettings underTest = SetUpStartDeployment(deployerMock =>
SetUpDeployerStartDeployment(deployerMock, success: true), waitSuccess, hasGameServer);
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
Assert.IsFalse(underTest.CanCancel);
}
}
[UnityTest]
public IEnumerator CanCancel_WhenRefreshAndScenarioSelectedAndStartDeploymentFailure_IsFalse(
[ValueSource(nameof(s_boolValues))] bool waitSuccess,
[ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
DeploymentSettings underTest = SetUpStartDeployment(deployerMock =>
SetUpDeployerStartDeployment(deployerMock, success: false), waitSuccess, hasGameServer);
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
Assert.IsFalse(underTest.CanCancel);
}
}
[UnityTest]
public IEnumerator CanCancel_WhenRefreshAndScenarioSelectedAndStartDeploymentException_IsFalse([ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testMessage = "TestException";
await TestWhenRefreshAndScenarioSelectedAndStartDeploymentException(testMessage, hasGameServer, underTest => Assert.IsFalse(underTest.CanCancel));
}
}
#endregion
#region CancelDeployment
[UnityTest]
public IEnumerator CancelDeployment_WhenCanCancel_CallsDeploymentWaiterCancelDeployment()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
Mock<Delay> delayMock = SetUpDelayMock();
var deploymentWaiterMock = new Mock<DeploymentWaiter>(delayMock.Object, coreApiMock.Object);
(DeploymentSettings underTest, Mock<DeployerBase> deployerMock) = SetUpCancelDeploymentWhenCanCancelTrue(coreApiMock, deploymentWaiterMock);
Task task = underTest.StartDeployment(ConfirmChangeSetTask);
Assert.IsTrue(underTest.IsDeploymentRunning);
Assert.IsTrue(underTest.CanCancel);
underTest.CancelDeployment();
await task;
coreApiMock.Verify();
deployerMock.Verify();
deploymentWaiterMock.Verify();
}
}
[UnityTest]
public IEnumerator CancelDeployment_WhenCanCancelAndDeployerCancelSuccess_DescribeStackStatusRefreshed()
{
yield return Run().AsCoroutine();
async Task Run()
{
string testStatus = "TestStatus" + DateTime.UtcNow.Ticks.ToString();
TextProvider textProvider = TextProviderFactory.Create();
string expectedText = string.Format(textProvider.Get(Strings.StackStatusTemplate), testStatus);
var coreApiMock = new Mock<CoreApi>();
Mock<Delay> delayMock = SetUpDelayMock();
var deploymentWaiterMock = new Mock<DeploymentWaiter>(delayMock.Object, coreApiMock.Object);
(DeploymentSettings underTest, Mock<DeployerBase> _) = SetUpCancelDeploymentWhenCanCancelTrue(coreApiMock, deploymentWaiterMock);
var response = new DescribeStackResponse()
{
StackStatus = testStatus,
Outputs = new Dictionary<string, string>()
};
response = Response.Ok(response);
coreApiMock.Setup(target => target.DescribeStack(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(response)
.Verifiable();
Task task = underTest.StartDeployment(ConfirmChangeSetTask);
Assert.IsTrue(underTest.IsDeploymentRunning);
Assert.IsTrue(underTest.CanCancel);
// Act
underTest.CancelDeployment();
await task;
// Assert
coreApiMock.Verify();
deploymentWaiterMock.Verify();
Assert.AreEqual(expectedText, underTest.CurrentStackInfo.Status);
}
}
[UnityTest]
public IEnumerator CancelDeployment_WhenCanCancelAndDeployerCancelSuccess_DescribeStackStatusNotRefreshed()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
Mock<Delay> delayMock = SetUpDelayMock();
var deploymentWaiterMock = new Mock<DeploymentWaiter>(delayMock.Object, coreApiMock.Object);
(DeploymentSettings underTest, Mock<DeployerBase> _) = SetUpCancelDeploymentWhenCanCancelTrue(coreApiMock, deploymentWaiterMock);
// It is called once in StartDeployment
coreApiMock.Verify(target => target.DescribeStack(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
Task task = underTest.StartDeployment(ConfirmChangeSetTask);
Assert.IsTrue(underTest.IsDeploymentRunning);
Assert.IsTrue(underTest.CanCancel);
underTest.CancelDeployment();
await task;
coreApiMock.Verify();
deploymentWaiterMock.Verify();
}
}
private static (DeploymentSettings underTest, Mock<DeployerBase> deployerMock) SetUpCancelDeploymentWhenCanCancelTrue(
Mock<CoreApi> coreApiMock, Mock<DeploymentWaiter> deploymentWaiterMock)
{
const string testGameName = "test";
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
const string testScenarioPath = "C:/test";
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
Mock<Delay> delayMock = SetUpDelayMock();
var deployerMock = new Mock<DeployerBase>(delayMock.Object, coreApiMock.Object);
DeploymentResponse response = Response.Ok(new DeploymentResponse());
deployerMock.Setup(target => target.StartDeployment(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<bool>(), ConfirmChangeSetTask))
.Returns(Task.FromResult(response))
.Verifiable();
Mock<ScenarioLocator> scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: false, coreApiMock, deployerMock);
Mock<PathConverter> pathConverterMock = GetMockPathConverter();
pathConverterMock.Setup(target => target.GetScenarioAbsolutePath(It.IsAny<string>()))
.Returns(testScenarioPath);
pathConverterMock.Setup(target => target.GetParametersFilePath(testScenarioPath))
.Returns(string.Empty);
var cancelResponse = Response.Ok(new Response());
deploymentWaiterMock.Setup(target => target.CancelDeployment())
.Returns(cancelResponse)
.Verifiable();
deploymentWaiterMock.Setup(target => target.CanCancel)
.Returns(true)
.Verifiable();
DeploymentResponse waitResponse = Response.Fail(new DeploymentResponse(AmazonGameLift.Editor.ErrorCode.OperationCancelled));
deploymentWaiterMock.Setup(target => target.WaitUntilDone(It.IsAny<DeploymentId>()))
.Returns(Task.Delay(200).ContinueWith(_ => waitResponse))
.Verifiable();
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock, pathConverter: pathConverterMock, deploymentWaiter: deploymentWaiterMock);
underTest.Refresh();
underTest.ScenarioIndex = 0;
underTest.BuildFolderPath = "test path";
underTest.BuildFilePath = "test path/build.exe";
underTest.GameName = testGameName;
return (underTest, deployerMock);
}
#endregion
#region StartDeployment
[UnityTest]
public IEnumerator StartDeployment_WhenRefreshAndScenarioSelected_IsExececuted(
[ValueSource(nameof(s_boolValues))] bool waitSuccess,
[ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
Mock<DeployerBase> deployerMock = null;
DeploymentSettings underTest = SetUpStartDeployment(mock =>
{
SetUpDeployerStartDeployment(mock, success: true);
deployerMock = mock;
}, waitSuccess, hasGameServer);
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
// Assert
deployerMock.Verify();
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenRefreshAndScenarioSelectedAndHasNoServerAndInvalidBuildFilePath_IsExececuted()
{
yield return Run().AsCoroutine();
async Task Run()
{
Mock<DeployerBase> deployerMock = null;
DeploymentSettings underTest = SetUpStartDeployment(mock =>
{
SetUpDeployerStartDeployment(mock, success: true);
deployerMock = mock;
}, waitSuccess: true, hasGameServer: false);
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
// Assert
deployerMock.Verify();
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenRefreshAndScenarioSelectedAndHasServerAndInvalidBuildFilePath_IsNotExececuted()
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testGameName = "test";
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
const string testBuildFilePath = "invalid";
const string testBuildFolderPath = "test path";
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Setup(target => target.FileExists(testBuildFilePath))
.Returns(true)
.Verifiable();
coreApiMock.Setup(target => target.FolderExists(testBuildFolderPath))
.Returns(true)
.Verifiable();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
Mock<Delay> delayMock = SetUpDelayMock();
var deployerMock = new Mock<DeployerBase>(delayMock.Object, coreApiMock.Object);
var scenarioLocatorMock = new Mock<ScenarioLocator>();
SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasServer: true,
coreApiMock, deployerMock, scenarioLocatorMock);
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock);
underTest.Refresh();
underTest.ScenarioIndex = 0;
underTest.GameName = testGameName;
underTest.BuildFolderPath = testBuildFolderPath;
underTest.BuildFilePath = testBuildFilePath;
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
// Assert
VerifyStartDeploymentNotExecuted(deployerMock);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenRefreshAndScenarioNotSelected_IsNotExececuted([ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
Mock<DeployerBase> deployerMock = null;
DeploymentSettings underTest = SetUpStartDeployment(mock =>
{
SetUpDeployerStartDeployment(mock, success: true);
deployerMock = mock;
}, waitSuccess: false, hasGameServer);
underTest.Refresh();
underTest.ScenarioIndex = -1;
underTest.BuildFolderPath = "test path";
underTest.BuildFilePath = "test path/build.exe";
underTest.GameName = "test";
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
VerifyStartDeploymentNotExecuted(deployerMock);
}
}
[UnityTest]
public IEnumerator StartDeployment_WhenRefreshAndScenarioSelectedAndGameNameEmpty_IsNotExececuted(
[ValueSource(nameof(s_boolValues))] bool hasGameServer)
{
yield return Run().AsCoroutine();
async Task Run()
{
Mock<DeployerBase> deployerMock = null;
DeploymentSettings underTest = SetUpStartDeployment(mock =>
{
SetUpDeployerStartDeployment(mock, success: true);
deployerMock = mock;
}, waitSuccess: false, hasGameServer);
underTest.GameName = string.Empty;
// Act
await underTest.StartDeployment(ConfirmChangeSetTask);
VerifyStartDeploymentNotExecuted(deployerMock);
}
}
private static void VerifyStartDeploymentNotExecuted(Mock<DeployerBase> deployerMock)
{
try
{
deployerMock.Verify(target =>
target.StartDeployment(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), ConfirmChangeSetTask),
Times.Never);
}
catch (MockException)
{
Assert.IsFalse(true, "The method was executed.");
}
}
#endregion
#region CurrentStackInfo
[Test]
public void CurrentStackInfo_WhenBootstrappedAndNewInstance_IsDefault()
{
string key = DateTime.UtcNow.Ticks.ToString();
string testStatus = "TestStatus" + key;
string testGameName = "test" + key;
string testApiGatewayEndpoint = "ApiGatewayEndpoint" + key;
string testUserPoolClientId = "UserPoolClientId" + key;
var testOutputs = new Dictionary<string, string>
{
{StackOutputKeys.ApiGatewayEndpoint, testApiGatewayEndpoint},
{StackOutputKeys.UserPoolClientId, testUserPoolClientId},
};
TextProvider textProvider = TextProviderFactory.Create();
string expectedStatusText = textProvider.Get(Strings.StatusNothingDeployed);
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
coreApiMock.SetUpCoreApiWithDescribeStack(success: true, stackName: testGameName, result: testStatus,
outputs: testOutputs);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
// Assert
Assert.AreEqual(expectedStatusText, underTest.CurrentStackInfo.Status);
Assert.IsNull(underTest.CurrentStackInfo.ApiGatewayEndpoint);
Assert.IsNull(underTest.CurrentStackInfo.UserPoolClientId);
}
[UnityTest]
public IEnumerator CurrentStackInfoChanged_WhenBootstrappedAndGameNameChanged_IsRaised()
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testGameName = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
underTest.Refresh();
underTest.ScenarioIndex = 0;
bool isEventRaised = false;
underTest.CurrentStackInfoChanged += () =>
{
isEventRaised = true;
};
// Act
await underTest.SetGameNameAsync(testGameName);
// Assert
Assert.IsTrue(isEventRaised);
}
}
[UnityTest]
public IEnumerator CurrentStackInfoChanged_WhenBootstrappedAndGameNameSetAndRefreshCurrentStackInfo_IsRaised()
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testGameName = "test";
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
underTest.Refresh();
underTest.ScenarioIndex = 0;
await underTest.SetGameNameAsync(testGameName);
bool isEventRaised = false;
underTest.CurrentStackInfoChanged += () =>
{
isEventRaised = true;
};
// Act
underTest.RefreshCurrentStackInfo();
// Assert
Assert.IsTrue(isEventRaised);
}
}
[UnityTest]
public IEnumerator CurrentStackInfo_WhenBootstrappedAndGameNameChanged_IsExpected()
{
yield return Run().AsCoroutine();
async Task Run()
{
string key = DateTime.UtcNow.Ticks.ToString();
string testStatus = "TestStatus" + key;
string testGameName = "test" + key;
string testApiGatewayEndpoint = "ApiGatewayEndpoint" + key;
string testUserPoolClientId = "UserPoolClientId" + key;
var testOutputs = new Dictionary<string, string>
{
{StackOutputKeys.ApiGatewayEndpoint, testApiGatewayEndpoint},
{StackOutputKeys.UserPoolClientId, testUserPoolClientId},
};
TextProvider textProvider = TextProviderFactory.Create();
string expectedStatusText = string.Format(textProvider.Get(Strings.StackStatusTemplate), testStatus);
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
coreApiMock.SetUpCoreApiWithDescribeStack(success: true, stackName: testGameName, result: testStatus,
outputs: testOutputs);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
underTest.Refresh();
underTest.ScenarioIndex = 0;
// Act
await underTest.SetGameNameAsync(testGameName);
// Assert
Assert.AreEqual(testStatus, underTest.CurrentStackInfo.StackStatus);
Assert.AreEqual(expectedStatusText, underTest.CurrentStackInfo.Status);
Assert.AreEqual(testApiGatewayEndpoint, underTest.CurrentStackInfo.ApiGatewayEndpoint);
Assert.AreEqual(testUserPoolClientId, underTest.CurrentStackInfo.UserPoolClientId);
}
}
[UnityTest]
public IEnumerator CurrentStackInfo_WhenWaitForCurrentDeploymentAndDeploymentContainerEmpty_IsNotChanged()
{
yield return Run().AsCoroutine();
async Task Run()
{
var deploymentIdContainer = new Mock<IDeploymentIdContainer>();
deploymentIdContainer.SetupGet(target => target.HasValue)
.Returns(false)
.Verifiable();
DeploymentSettings underTest = GetUnitUnderTest(deploymentIdContainer: deploymentIdContainer);
DeploymentStackInfo expectedInfo = underTest.CurrentStackInfo;
await underTest.WaitForCurrentDeployment();
Assert.AreEqual(expectedInfo, underTest.CurrentStackInfo);
}
}
[UnityTest]
public IEnumerator CurrentStackInfo_WhenWaitForCurrentDeploymentAndDeploymentWaiterSuccess_IsExpected()
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testProfile = "test";
const string testScenarioName = "Test Name";
const string testRegion = "test-region";
const string testGameName = "test";
const string testStackName = "test-name";
var deploymentId = new DeploymentId(testProfile, testRegion, testStackName, testScenarioName);
var expectedInfo = new DeploymentInfo(testRegion, testGameName, testScenarioName, DateTime.Now, StackStatus.CreateComplete, new Dictionary<string, string>());
DeploymentStackInfo expectedStackInfo = DeploymentStackInfoFactory.Create(TextProviderFactory.Create(), expectedInfo);
var coreApiMock = new Mock<CoreApi>();
Mock<Delay> delayMock = SetUpDelayMock();
var deploymentWaiter = new Mock<DeploymentWaiter>(delayMock.Object, coreApiMock.Object);
DeploymentResponse waitResponse = Response.Ok(new DeploymentResponse());
deploymentWaiter.Setup(target => target.WaitUntilDone(It.IsAny<DeploymentId>()))
.Returns(Task.FromResult(waitResponse))
.Raises(mock => mock.InfoUpdated += null, expectedInfo)
.Verifiable();
var deploymentIdContainer = new Mock<IDeploymentIdContainer>();
SetUpContainer(deploymentIdContainer, deploymentId);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock, deploymentWaiter: deploymentWaiter, deploymentIdContainer: deploymentIdContainer);
DeploymentStackInfo unexpectedInfo = underTest.CurrentStackInfo;
await underTest.WaitForCurrentDeployment();
Assert.AreNotEqual(unexpectedInfo, underTest.CurrentStackInfo);
Assert.AreEqual(expectedStackInfo, underTest.CurrentStackInfo);
}
}
[UnityTest]
public IEnumerator CurrentStackInfo_WhenWaitForCurrentDeploymentAndDeploymentWaiterFails_IsExpected()
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testProfile = "test";
const string testScenarioName = "Test Name";
const string testRegion = "test-region";
const string testStackName = "test-name";
var deploymentId = new DeploymentId(testProfile, testRegion, testStackName, testScenarioName);
var coreApiMock = new Mock<CoreApi>();
Mock<Delay> delayMock = SetUpDelayMock();
var deploymentWaiter = new Mock<DeploymentWaiter>(delayMock.Object, coreApiMock.Object);
DeploymentResponse waitResponse = Response.Fail(new DeploymentResponse());
deploymentWaiter.Setup(target => target.WaitUntilDone(It.IsAny<DeploymentId>()))
.Returns(Task.FromResult(waitResponse))
.Verifiable();
var deploymentIdContainer = new Mock<IDeploymentIdContainer>();
SetUpContainer(deploymentIdContainer, deploymentId);
deploymentIdContainer.Setup(target => target.Clear())
.Verifiable();
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock, deploymentWaiter: deploymentWaiter, deploymentIdContainer: deploymentIdContainer);
DeploymentStackInfo expectedInfo = underTest.CurrentStackInfo;
await underTest.WaitForCurrentDeployment();
deploymentWaiter.Verify();
deploymentIdContainer.Verify();
Assert.AreEqual(expectedInfo, underTest.CurrentStackInfo);
}
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenWaitForCurrentDeploymentAndDeploymentWaiterException_IsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
const string testMessage = "TestException";
const string testProfile = "test";
const string testScenarioName = "Test Name";
const string testRegion = "test-region";
const string testStackName = "test-name";
var deploymentId = new DeploymentId(testProfile, testRegion, testStackName, testScenarioName);
var coreApiMock = new Mock<CoreApi>();
Mock<Delay> delayMock = SetUpDelayMock();
var deploymentWaiter = new Mock<DeploymentWaiter>(delayMock.Object, coreApiMock.Object);
deploymentWaiter.Setup(target => target.WaitUntilDone(It.IsAny<DeploymentId>()))
.Throws(new Exception(testMessage))
.Verifiable();
var deploymentIdContainer = new Mock<IDeploymentIdContainer>();
SetUpContainer(deploymentIdContainer, deploymentId);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock, deploymentWaiter: deploymentWaiter, deploymentIdContainer: deploymentIdContainer);
try
{
await underTest.WaitForCurrentDeployment();
}
catch (Exception ex)
{
if (ex.Message != testMessage)
{
throw;
}
Assert.IsFalse(underTest.IsDeploymentRunning);
return;
}
Assert.Fail("Did not throw.");
}
}
#endregion
[UnityTest]
[TestCase(null, true, ExpectedResult = null)]
[TestCase(StackStatus.CreateComplete, true, ExpectedResult = null)]
[TestCase(StackStatus.CreateFailed, false, ExpectedResult = null)]
[TestCase(StackStatus.CreateInProgress, false, ExpectedResult = null)]
[TestCase(StackStatus.DeleteComplete, false, ExpectedResult = null)]
[TestCase(StackStatus.DeleteFailed, false, ExpectedResult = null)]
[TestCase(StackStatus.DeleteInProgress, false, ExpectedResult = null)]
[TestCase(StackStatus.RollbackComplete, false, ExpectedResult = null)]
[TestCase(StackStatus.RollbackFailed, false, ExpectedResult = null)]
[TestCase(StackStatus.RollbackInProgress, false, ExpectedResult = null)]
[TestCase(StackStatus.UpdateComplete, true, ExpectedResult = null)]
[TestCase(StackStatus.UpdateCompleteCleanUpInProgress, true, ExpectedResult = null)]
[TestCase(StackStatus.UpdateInProgress, false, ExpectedResult = null)]
[TestCase(StackStatus.UpdateRollbackComplete, true, ExpectedResult = null)]
[TestCase(StackStatus.UpdateRollbackInProgress, false, ExpectedResult = null)]
public IEnumerator IsCurrentStackModifiable_WhenBootstrappedAndGameNameChanged_IsExpected(string testStatus, bool isModifiableExpected)
{
yield return Run().AsCoroutine();
async Task Run()
{
string key = DateTime.UtcNow.Ticks.ToString();
string testGameName = "test" + key;
var testOutputs = new Dictionary<string, string>();
var coreApiMock = new Mock<CoreApi>();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
coreApiMock.SetUpCoreApiWithDescribeStack(success: true, stackName: testGameName, result: testStatus,
outputs: testOutputs);
DeploymentSettings underTest = GetUnitUnderTest(coreApi: coreApiMock);
underTest.Refresh();
underTest.ScenarioIndex = 0;
// Act
await underTest.SetGameNameAsync(testGameName);
// Assert
Assert.AreEqual(isModifiableExpected, underTest.IsCurrentStackModifiable);
}
}
private static void SetUpContainer(Mock<IDeploymentIdContainer> deploymentIdContainer, DeploymentId deploymentId)
{
deploymentIdContainer.SetupGet(target => target.HasValue)
.Returns(true)
.Verifiable();
deploymentIdContainer.Setup(target => target.Get())
.Returns(deploymentId)
.Verifiable();
}
private static async Task TestWhenRefreshAndScenarioSelectedAndStartDeploymentException(string testError, bool hasGameServer, Action<DeploymentSettings> assert)
{
var testException = new Exception(testError);
DeploymentSettings underTest = SetUpStartDeployment(deployerMock =>
{
deployerMock.Setup(target => target.StartDeployment(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<bool>(), It.IsAny<ConfirmChangesDelegate>()))
.Throws(testException)
.Verifiable();
}, waitSuccess: false, hasGameServer);
try
{
await underTest.StartDeployment(ConfirmChangeSetTask);
}
catch (Exception ex)
{
if (ex.Message != testError)
{
throw;
}
assert(underTest);
}
}
private static void SetUpDeployerStartDeployment(Mock<DeployerBase> deployerMock, bool success)
{
var response = new DeploymentResponse();
response = success ? Response.Ok(response) : Response.Fail(response);
deployerMock.Setup(target => target.StartDeployment(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<bool>(), ConfirmChangeSetTask))
.Returns(Task.FromResult(response))
.Verifiable();
}
private static void SetUpcoreApiforRefreshSuccess(Mock<CoreApi> coreApiMock, string profile = "test-profile", string gameName = "game", string result = StackStatus.CreateComplete)
{
coreApiMock.SetUpCoreApiWithProfile(success: true, profile);
coreApiMock.SetUpCoreApiForBootstrapSuccess();
SetUpcoreApiforRefreshStackStatusSuccess(coreApiMock, profile, gameName, result);
}
private static void SetUpcoreApiforRefreshStackStatusSuccess(Mock<CoreApi> coreApiMock, string profile = "test-profile", string gameName = "game", string result = StackStatus.CreateComplete)
{
coreApiMock.SetUpGetStackNameAsGameName(gameName);
coreApiMock.SetUpCoreApiWithDescribeStack(success: true, profile, stackName: gameName, result: result);
}
private static DeploymentSettings SetUpStartDeployment(Action<Mock<DeployerBase>> setUpDeployer,
bool waitSuccess, bool hasGameServer, string buildFilePath = "test path/build.exe",
Mock<ScenarioLocator> scenarioLocatorMock = null, Mock<CoreApi> coreApiMock = null,
Mock<DeploymentWaiter> deploymentWaiter = null, Mock<IDeploymentIdContainer> deploymentIdContainer = null)
{
const string testGameName = "test";
const string testScenarioName = "test scenario";
const string testScenarioDescription = "test scenario description";
const string testScenarioUrl = "test";
const string testScenarioPath = "C:/test";
const string testBuildFolderPath = "test path";
coreApiMock = coreApiMock ?? new Mock<CoreApi>();
coreApiMock.Setup(target => target.FileExists(buildFilePath))
.Returns(hasGameServer)
.Verifiable();
coreApiMock.Setup(target => target.FolderExists(testBuildFolderPath))
.Returns(hasGameServer)
.Verifiable();
SetUpcoreApiforRefreshSuccess(coreApiMock, gameName: testGameName);
Mock<Delay> delayMock = SetUpDelayMock();
var deployerMock = new Mock<DeployerBase>(delayMock.Object, coreApiMock.Object);
setUpDeployer(deployerMock);
scenarioLocatorMock = SetUpScenarioLocatorToReturnTestDeployer(
testScenarioName, testScenarioDescription, testScenarioUrl, hasGameServer, coreApiMock, deployerMock,
scenarioLocatorMock);
Mock<PathConverter> pathConverterMock = GetMockPathConverter();
pathConverterMock.Setup(target => target.GetScenarioAbsolutePath(It.IsAny<string>()))
.Returns(testScenarioPath);
pathConverterMock.Setup(target => target.GetParametersFilePath(testScenarioPath))
.Returns(string.Empty);
deploymentWaiter = deploymentWaiter ?? new Mock<DeploymentWaiter>(delayMock.Object, coreApiMock.Object);
DeploymentResponse waitResponse = waitSuccess
? Response.Ok(new DeploymentResponse())
: Response.Fail(new DeploymentResponse());
deploymentWaiter.Setup(target => target.WaitUntilDone(It.IsAny<DeploymentId>()))
.Returns(Task.FromResult(waitResponse))
.Verifiable();
DeploymentSettings underTest = GetUnitUnderTest(scenarioLocatorMock, coreApi: coreApiMock,
pathConverter: pathConverterMock, deploymentWaiter: deploymentWaiter, deploymentIdContainer: deploymentIdContainer);
underTest.Refresh();
underTest.ScenarioIndex = 0;
underTest.GameName = testGameName;
if (hasGameServer)
{
underTest.BuildFolderPath = testBuildFolderPath;
underTest.BuildFilePath = buildFilePath;
}
return underTest;
}
private static Mock<ScenarioLocator> SetUpScenarioLocatorToReturnTestDeployer(
string name, string description, string url, bool hasServer,
Mock<CoreApi> coreApiMock, Mock<DeployerBase> deployerMock = null,
Mock<ScenarioLocator> scenarioLocatorMock = null, string scenarioFolder = null)
{
Mock<Delay> delayMock = SetUpDelayMock();
deployerMock = deployerMock ?? new Mock<DeployerBase>(delayMock.Object, coreApiMock.Object);
deployerMock.SetupGet(target => target.DisplayName)
.Returns(name);
deployerMock.SetupGet(target => target.Description)
.Returns(description);
deployerMock.SetupGet(target => target.ScenarioFolder)
.Returns(scenarioFolder);
deployerMock.SetupGet(target => target.HelpUrl)
.Returns(url);
deployerMock.SetupGet(target => target.HasGameServer)
.Returns(hasServer);
scenarioLocatorMock = scenarioLocatorMock ?? new Mock<ScenarioLocator>();
var scenarios = new DeployerBase[] { deployerMock.Object };
scenarioLocatorMock.Setup(target => target.GetScenarios())
.Returns(scenarios)
.Verifiable();
return scenarioLocatorMock;
}
private static Mock<Delay> SetUpDelayMock()
{
var delayMock = new Mock<Delay>();
delayMock.Setup(target => target.Wait(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
return delayMock;
}
private static DeploymentSettings GetUnitUnderTest(Mock<ScenarioLocator> scenarioLocator = null,
Mock<PathConverter> pathConverter = null, Mock<CoreApi> coreApi = null,
Mock<ScenarioParametersUpdater> parametersUpdater = null, Mock<DeploymentWaiter> deploymentWaiter = null,
Mock<IDeploymentIdContainer> deploymentIdContainer = null, Mock<Delay> delay = null)
{
coreApi = coreApi ?? new Mock<CoreApi>();
scenarioLocator = scenarioLocator ?? new Mock<ScenarioLocator>();
Mock<Delay> delayMock = delay ?? SetUpDelayMock();
deploymentWaiter = deploymentWaiter ?? new Mock<DeploymentWaiter>(delayMock.Object, coreApi.Object);
pathConverter = pathConverter ?? GetMockPathConverter(coreApi);
parametersUpdater = parametersUpdater ?? GetMockScenarioParametersUpdater(coreApi);
deploymentIdContainer = deploymentIdContainer ?? new Mock<IDeploymentIdContainer>();
return new DeploymentSettings(scenarioLocator.Object, pathConverter.Object, coreApi.Object,
parametersUpdater.Object, TextProviderFactory.Create(), deploymentWaiter.Object,
deploymentIdContainer.Object, delayMock.Object, new MockLogger());
}
private static Mock<PathConverter> GetMockPathConverter(Mock<CoreApi> coreApi = null)
{
coreApi = coreApi ?? new Mock<CoreApi>();
return new Mock<PathConverter>(coreApi.Object);
}
private static Mock<ScenarioParametersUpdater> GetMockScenarioParametersUpdater(Mock<CoreApi> coreApi = null)
{
coreApi = coreApi ?? new Mock<CoreApi>();
var scenarioParametersEditor = new Mock<ScenarioParametersEditor>();
var factory = (Func<ScenarioParametersEditor>)(() => scenarioParametersEditor.Object);
return new Mock<ScenarioParametersUpdater>(coreApi.Object, factory);
}
private static Task<bool> ConfirmChangeSetTask(ConfirmChangesRequest _)
{
return Task.FromResult(true);
}
}
}
| 1,476 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.DeploymentManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using Moq.Language;
using NUnit.Framework;
using UnityEngine.TestTools;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class DeploymentWaiterTests
{
private const string TestProfile = "test";
private const string TestScenarioName = "Test Name";
private const string TestRegion = "test-region";
private const string TestStackName = "test-name";
private static readonly bool[] s_boolValues = new bool[] { true, false };
#region WaitUntilDone Success
[UnityTest]
public IEnumerator WaitUntilDone_WhenDescribeStackFailure_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
DescribeStackResponse response1 = Response.Fail(new DescribeStackResponse());
(DeploymentWaiter _, Task<DeploymentResponse> waitTask) =
SetUpWaitUntilDoneWithDescribeStackResponses(new[] { response1 }, coreApiMock);
// Act
DeploymentResponse response = await waitTask;
// Assert
coreApiMock.Verify();
Assert.IsFalse(response.Success);
}
}
[UnityTest]
public IEnumerator WaitUntilDone_WhenDescribeStackReviewAndFailure_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeploymentWaiter _, DeploymentResponse response) = await TestWaitUntilDoneWhenDescribeStackReviewAndFailure();
Assert.IsFalse(response.Success);
}
}
[UnityTest]
public IEnumerator WaitUntilDone_WhenDescribeStackInvalidStatus_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeploymentWaiter _, DeploymentResponse response) = await TestWaitUntilDoneWhenDescribeStackReviewAndInvalidStatus();
Assert.IsFalse(response.Success);
Assert.AreEqual(AmazonGameLift.Editor.ErrorCode.StackStatusInvalid, response.ErrorCode);
}
}
[UnityTest]
public IEnumerator WaitUntilDone_WhenDescribeStackCreateComplete_SuccessIsTrue()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeploymentWaiter _, DeploymentResponse response) = await TestWaitUntilDoneWhenDescribeStackStatusCreateComplete();
Assert.IsTrue(response.Success);
}
}
[UnityTest]
public IEnumerator WaitUntilDone_WhenCancelWaiting_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
DescribeStackResponse[] responses = new[]
{
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.ReviewInProgress }),
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.CreateInProgress }),
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.CreateComplete }),
};
(DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) = SetUpWaitUntilDoneWithDescribeStackResponses(responses, coreApiMock);
underTest.CancelWaiting();
// Act
Response response = await waitTask;
// Assert
coreApiMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(AmazonGameLift.Editor.ErrorCode.OperationCancelled, response.ErrorCode);
}
}
#endregion
#region CancelWaiting
[Test]
public void CancelWaiting_WhenNotWaiting_SuccessIsFalse()
{
var coreApiMock = new Mock<CoreApi>();
DeploymentWaiter underTest = GetUnitUnderTest(coreApiMock);
Response response = underTest.CancelWaiting();
Assert.IsFalse(response.Success);
}
[UnityTest]
public IEnumerator CancelWaiting_WhenWaitUntilDone_SuccessIsTrue()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
DescribeStackResponse[] responses = new[]
{
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.ReviewInProgress }),
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.CreateInProgress }),
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.CreateComplete }),
};
(DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) = SetUpWaitUntilDoneWithDescribeStackResponses(responses, coreApiMock);
// Act
Response response = underTest.CancelWaiting();
// Assert
coreApiMock.Verify();
Assert.IsTrue(response.Success);
await waitTask;
}
}
[UnityTest]
public IEnumerator CancelWaiting_WhenWaitUntilDoneAndCancelWaiting_SuccessIsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
DescribeStackResponse[] responses = new[]
{
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.ReviewInProgress }),
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.CreateInProgress }),
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.CreateComplete }),
};
(DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) = SetUpWaitUntilDoneWithDescribeStackResponses(responses, coreApiMock);
underTest.CancelWaiting();
// Act
Response response = underTest.CancelWaiting();
// Assert
coreApiMock.Verify();
Assert.IsFalse(response.Success);
await waitTask;
}
}
#endregion
#region CanCancel
[Test]
public void CanCancel_WhenNewInstance_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
DeploymentWaiter underTest = GetUnitUnderTest(coreApiMock);
Assert.IsFalse(underTest.CanCancel);
}
[UnityTest]
public IEnumerator CanCancel_WhenDescribeStackReviewAndFailure_IsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeploymentWaiter underTest, DeploymentResponse _) = await TestWaitUntilDoneWhenDescribeStackReviewAndFailure();
Assert.IsFalse(underTest.CanCancel);
}
}
[UnityTest]
public IEnumerator CanCancel_WhenWaitUntilDoneAndDescribeStackReviewAndInvalidStatus_IsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeploymentWaiter underTest, DeploymentResponse _) = await TestWaitUntilDoneWhenDescribeStackReviewAndInvalidStatus();
Assert.IsFalse(underTest.CanCancel);
}
}
[UnityTest]
public IEnumerator CanCancel_WhenWaitUntilDoneAndDescribeStackStatusCreateComplete_IsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
(DeploymentWaiter underTest, DeploymentResponse _) = await TestWaitUntilDoneWhenDescribeStackStatusCreateComplete();
Assert.IsFalse(underTest.CanCancel);
}
}
[UnityTest]
public IEnumerator CanCancel_WhenWaitUntilDoneAndNewStackAndCancelDeploymentAndCoreNotExpected_IsExpected([ValueSource(nameof(s_boolValues))] bool expected)
{
var coreApiMock = new Mock<CoreApi>();
(DeploymentWaiter underTest, Task<DeploymentResponse> _) = SetUpCancelDeploymentWhenNewStack(coreApiSuccess: !expected, coreApiMock);
while (!underTest.CanCancel)
{
yield return null;
}
// Act
underTest.CancelDeployment();
// Assert
coreApiMock.Verify();
Assert.AreEqual(expected, underTest.CanCancel);
}
[UnityTest]
public IEnumerator CanCancel_WhenWaitUntilDoneAndStackExistsAndCancelDeploymentAndCoreNotExpected_IsExpected([ValueSource(nameof(s_boolValues))] bool expected)
{
var coreApiMock = new Mock<CoreApi>();
(DeploymentWaiter underTest, Task<DeploymentResponse> _) = SetUpCancelDeploymentWhenStackExists(coreApiSuccess: !expected, coreApiMock);
while (!underTest.CanCancel)
{
yield return null;
}
// Act
underTest.CancelDeployment();
// Assert
coreApiMock.Verify();
Assert.AreEqual(expected, underTest.CanCancel);
}
#endregion
#region CancelDeployment
[Test]
public void CancelDeployment_WhenCanCancelIsFalse_SuccessIsFalse()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Verify(
target => target.CancelDeployment(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()),
Times.Never);
coreApiMock.Verify(
target => target.DeleteStack(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()),
Times.Never);
DeploymentWaiter underTest = GetUnitUnderTest(coreApiMock);
Response cancelResponse = underTest.CancelDeployment();
// Assert
coreApiMock.Verify();
Assert.IsFalse(cancelResponse.Success);
Assert.AreEqual(AmazonGameLift.Editor.ErrorCode.OperationInvalid, cancelResponse.ErrorCode);
}
[UnityTest]
public IEnumerator CancelDeployment_WhenWaitUntilDoneAndNewStackAndCanCancelIsTrueAndCoreExpected_SuccessIsExpected([ValueSource(nameof(s_boolValues))] bool expected)
{
var coreApiMock = new Mock<CoreApi>();
(DeploymentWaiter underTest, Task<DeploymentResponse> _) = SetUpCancelDeploymentWhenNewStack(coreApiSuccess: expected, coreApiMock);
while (!underTest.CanCancel)
{
yield return null;
}
// Act
Response cancelResponse = underTest.CancelDeployment();
// Assert
coreApiMock.Verify();
Assert.AreEqual(expected, cancelResponse.Success);
}
[UnityTest]
public IEnumerator CancelDeployment_WhenWaitUntilDoneAndStackExistsAndCanCancelIsTrueAndCoreExpected_SuccessIsExpected([ValueSource(nameof(s_boolValues))] bool expected)
{
var coreApiMock = new Mock<CoreApi>();
(DeploymentWaiter underTest, Task<DeploymentResponse> _) = SetUpCancelDeploymentWhenStackExists(coreApiSuccess: expected, coreApiMock);
while (!underTest.CanCancel)
{
yield return null;
}
// Act
Response cancelResponse = underTest.CancelDeployment();
// Assert
coreApiMock.Verify();
Assert.AreEqual(expected, cancelResponse.Success);
}
#endregion
#region InfoUpdated
[UnityTest]
public IEnumerator InfoUpdated_WhenWaitUntilDoneAndDescribeStackStatusPolled_IsRaised()
{
yield return Run().AsCoroutine();
async Task Run()
{
const int expectedUpdateCount = 3;
string[] statuses = new[]
{
StackStatus.UpdateInProgress,
StackStatus.UpdateInProgress,
StackStatus.UpdateComplete
};
var coreApiMock = new Mock<CoreApi>();
DescribeStackResponse[] responses = CreateDescribeStackSequenceResponses(statuses);
SetUpCoreApiWithDescribeStackSequence(coreApiMock, TestProfile, TestRegion, TestStackName, responses);
var deploymentId = new DeploymentId(TestProfile, TestRegion, TestStackName, TestScenarioName);
DeploymentWaiter underTest = GetUnitUnderTest(coreApiMock);
int updateCount = 0;
var updates = new List<DeploymentInfo>();
underTest.InfoUpdated += info =>
{
updateCount++;
updates.Add(info);
};
DeploymentResponse response = await underTest.WaitUntilDone(deploymentId);
Assert.AreEqual(expectedUpdateCount, updateCount);
for (int i = 0; i < updates.Count; i++)
{
DeploymentInfo info = updates[i];
Assert.AreEqual(statuses[i], info.StackStatus);
}
}
}
[UnityTest]
public IEnumerator InfoUpdated_WhenWaitUntilDoneAndDescribeStackStatusPollFails_IsNotRaised()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
DescribeStackResponse response1 = Response.Fail(new DescribeStackResponse());
(DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) =
SetUpWaitUntilDoneWithDescribeStackResponses(new[] { response1 }, coreApiMock);
int updateCount = 0;
underTest.InfoUpdated += info =>
{
updateCount++;
};
// Act
DeploymentResponse response = await waitTask;
// Assert
coreApiMock.Verify();
Assert.AreEqual(0, updateCount);
}
}
#endregion
private static (DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) SetUpCancelDeploymentWhenNewStack(bool coreApiSuccess, Mock<CoreApi> coreApiMock)
{
DescribeStackResponse[] responses = new[]
{
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.ReviewInProgress }),
Response.Ok(new DescribeStackResponse { StackStatus = StackStatus.CreateInProgress }),
Response.Fail(new DescribeStackResponse { ErrorCode = "TestError" }),
};
SetUpCoreApiWithDeleteStack(coreApiMock, success: coreApiSuccess, TestProfile, TestRegion, TestStackName);
return SetUpWaitUntilDoneWithDescribeStackResponses(responses, coreApiMock);
}
private static (DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) SetUpCancelDeploymentWhenStackExists(bool coreApiSuccess, Mock<CoreApi> coreApiMock)
{
string[] statuses = new[]
{
StackStatus.UpdateInProgress,
StackStatus.UpdateRollbackInProgress,
StackStatus.UpdateRollbackComplete
};
SetUpCoreApiWithCancelDeployment(coreApiMock, success: coreApiSuccess, TestProfile, TestRegion, TestStackName);
DescribeStackResponse[] responses = CreateDescribeStackSequenceResponses(statuses);
return SetUpWaitUntilDoneWithDescribeStackResponses(responses, coreApiMock);
}
private static (DeploymentWaiter underTest, Task<DeploymentResponse> waitTask)
SetUpWaitUntilDoneWithDescribeStackResponses(DescribeStackResponse[] responses, Mock<CoreApi> coreApiMock)
{
SetUpCoreApiWithDescribeStackSequence(coreApiMock, TestProfile, TestRegion, TestStackName, responses);
var deploymentId = new DeploymentId(TestProfile, TestRegion, TestStackName, TestScenarioName);
DeploymentWaiter underTest = GetUnitUnderTest(coreApiMock);
Task<DeploymentResponse> waitTask = underTest.WaitUntilDone(deploymentId);
return (underTest, waitTask);
}
private async Task<(DeploymentWaiter underTest, DeploymentResponse response)> TestWaitUntilDoneWhenDescribeStackReviewAndFailure()
{
var coreApiMock = new Mock<CoreApi>();
DescribeStackResponse response1 = Response.Ok(new DescribeStackResponse() { StackStatus = StackStatus.ReviewInProgress });
DescribeStackResponse response2 = Response.Fail(new DescribeStackResponse());
(DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) =
SetUpWaitUntilDoneWithDescribeStackResponses(new[] { response1, response2 }, coreApiMock);
// Act
DeploymentResponse response = await waitTask;
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeploymentWaiter underTest, DeploymentResponse response)> TestWaitUntilDoneWhenDescribeStackReviewAndInvalidStatus()
{
var coreApiMock = new Mock<CoreApi>();
string[] statuses = new[]
{
StackStatus.ReviewInProgress,
StackStatus.DeleteComplete,
};
DescribeStackResponse[] responses = CreateDescribeStackSequenceResponses(statuses);
(DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) =
SetUpWaitUntilDoneWithDescribeStackResponses(responses, coreApiMock);
// Act
DeploymentResponse response = await waitTask;
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private async Task<(DeploymentWaiter underTest, DeploymentResponse response)> TestWaitUntilDoneWhenDescribeStackStatusCreateComplete()
{
var coreApiMock = new Mock<CoreApi>();
string[] statuses = new[]
{
StackStatus.ReviewInProgress,
StackStatus.CreateComplete,
};
DescribeStackResponse[] responses = CreateDescribeStackSequenceResponses(statuses);
(DeploymentWaiter underTest, Task<DeploymentResponse> waitTask) =
SetUpWaitUntilDoneWithDescribeStackResponses(responses, coreApiMock);
// Act
DeploymentResponse response = await waitTask;
// Assert
coreApiMock.Verify();
return (underTest, response);
}
private static DescribeStackResponse[] CreateDescribeStackSequenceResponses(IEnumerable<string> results)
{
return results.Select(status => Response.Ok(new DescribeStackResponse() { StackStatus = status })).ToArray();
}
private static void SetUpCoreApiWithDescribeStackSequence(Mock<CoreApi> coreApiMock,
string profileName, string region, string stackName,
DescribeStackResponse[] responses)
{
ISetupSequentialResult<DescribeStackResponse> setup = coreApiMock
.SetupSequence(target => target.DescribeStack(profileName, region, stackName));
foreach (DescribeStackResponse item in responses)
{
setup = setup.Returns(item);
}
}
private static void SetUpCoreApiWithCancelDeployment(Mock<CoreApi> coreApiMock, bool success,
string profileName = "test-profile", string region = "test-region", string stackName = "test-stack")
{
var response = new CancelDeploymentResponse();
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.CancelDeployment(profileName, region, stackName, It.IsAny<string>()))
.Returns(response)
.Verifiable();
}
private static void SetUpCoreApiWithDeleteStack(Mock<CoreApi> coreApiMock, bool success,
string profileName = "test-profile", string region = "test-region", string stackName = "test-stack")
{
var response = new DeleteStackResponse();
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.DeleteStack(profileName, region, stackName))
.Returns(response)
.Verifiable();
}
private static DeploymentWaiter GetUnitUnderTest(Mock<CoreApi> coreApiMock)
{
var delayMock = new Mock<Delay>();
delayMock.Setup(target => target.Wait(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
return new DeploymentWaiter(delayMock.Object, coreApiMock.Object);
}
}
}
| 558 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class ScenarioParametersUpdaterTests
{
[Test]
public void Update_WhenFileReadAllTextError_FailsWithError()
{
const string testFilePath = "TestFile";
const string testGameName = "Test Game";
const string testErrorCode = "testErrorCode";
var coreApiMock = new Mock<CoreApi>();
FileReadAllTextResponse fileReadResponse = Response.Fail(new FileReadAllTextResponse() { ErrorCode = testErrorCode });
coreApiMock.Setup(target => target.FileReadAllText(testFilePath))
.Returns(fileReadResponse)
.Verifiable();
ScenarioParametersUpdater underTest = GetUnitUnderTest(coreApiMock);
// Act
Response response = underTest.Update(testFilePath, PrepareParameters(testGameName));
// Assert
coreApiMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(testErrorCode, response.ErrorCode);
}
[Test]
public void Update_WhenReadParametersError_FailsWithError()
{
const string testFilePath = "TestFile";
const string testGameName = "Test Game";
const string testParametersInput = "test input";
const string testErrorCode = "testErrorCode";
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiForFileReadAllTextSuccess(coreApiMock, testFilePath, testParametersInput);
var editorMock = new Mock<ScenarioParametersEditor>();
var readResponse = Response.Fail(new Response() { ErrorCode = testErrorCode });
editorMock.Setup(target => target.ReadParameters(testParametersInput))
.Returns(readResponse)
.Verifiable();
ScenarioParametersUpdater underTest = GetUnitUnderTest(coreApiMock, editorMock);
// Act
Response response = underTest.Update(testFilePath, PrepareParameters(testGameName));
// Assert
coreApiMock.Verify();
editorMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(testErrorCode, response.ErrorCode);
}
[Test]
public void Update_WhenSetParameterError_FailsWithError()
{
const string testFilePath = "TestFile";
const string testGameName = "Test Game";
const string testParametersInput = "test input";
const string testErrorCode = "testErrorCode";
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiForFileReadAllTextSuccess(coreApiMock, testFilePath, testParametersInput);
var editorMock = new Mock<ScenarioParametersEditor>();
var readResponse = Response.Ok(new Response());
editorMock.Setup(target => target.ReadParameters(testParametersInput))
.Returns(readResponse)
.Verifiable();
var setResponse = Response.Fail(new Response() { ErrorCode = testErrorCode });
editorMock.Setup(target => target.SetParameter(ScenarioParameterKeys.GameName, testGameName))
.Returns(setResponse)
.Verifiable();
ScenarioParametersUpdater underTest = GetUnitUnderTest(coreApiMock, editorMock);
// Act
Response response = underTest.Update(testFilePath, PrepareParameters(testGameName));
// Assert
coreApiMock.Verify();
editorMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(testErrorCode, response.ErrorCode);
}
[Test]
public void Update_WhenSaveParametersError_FailsWithError()
{
const string testFilePath = "TestFile";
const string testGameName = "Test Game";
const string testParametersInput = "test input";
const string testErrorCode = "testErrorCode";
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiForFileReadAllTextSuccess(coreApiMock, testFilePath, testParametersInput);
var editorMock = new Mock<ScenarioParametersEditor>();
var readResponse = Response.Ok(new Response());
editorMock.Setup(target => target.ReadParameters(testParametersInput))
.Returns(readResponse)
.Verifiable();
var setResponse = Response.Ok(new Response());
editorMock.Setup(target => target.SetParameter(ScenarioParameterKeys.GameName, testGameName))
.Returns(setResponse)
.Verifiable();
SaveParametersResponse saveResponse = Response.Fail(new SaveParametersResponse() { ErrorCode = testErrorCode });
editorMock.Setup(target => target.SaveParameters())
.Returns(saveResponse)
.Verifiable();
ScenarioParametersUpdater underTest = GetUnitUnderTest(coreApiMock, editorMock);
// Act
Response response = underTest.Update(testFilePath, PrepareParameters(testGameName));
// Assert
coreApiMock.Verify();
editorMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(testErrorCode, response.ErrorCode);
}
[Test]
public void Update_WhenFileWriteAllTextError_FailsWithError()
{
const string testFilePath = "TestFile";
const string testGameName = "Test Game";
const string testParametersInput = "test input";
const string testParametersOutput = "test output";
const string testErrorCode = "testErrorCode";
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiForFileReadAllTextSuccess(coreApiMock, testFilePath, testParametersInput);
var writeResponse = Response.Fail(new Response() { ErrorCode = testErrorCode });
coreApiMock.Setup(target => target.FileWriteAllText(testFilePath, testParametersOutput))
.Returns(writeResponse)
.Verifiable();
var editorMock = new Mock<ScenarioParametersEditor>();
var readResponse = Response.Ok(new Response());
editorMock.Setup(target => target.ReadParameters(testParametersInput))
.Returns(readResponse)
.Verifiable();
var setResponse = Response.Ok(new Response());
editorMock.Setup(target => target.SetParameter(ScenarioParameterKeys.GameName, testGameName))
.Returns(setResponse)
.Verifiable();
SaveParametersResponse saveResponse = Response.Ok(new SaveParametersResponse(testParametersOutput));
editorMock.Setup(target => target.SaveParameters())
.Returns(saveResponse)
.Verifiable();
ScenarioParametersUpdater underTest = GetUnitUnderTest(coreApiMock, editorMock);
// Act
Response response = underTest.Update(testFilePath, PrepareParameters(testGameName));
// Assert
coreApiMock.Verify();
editorMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(testErrorCode, response.ErrorCode);
}
[Test]
public void Update_WhenNoErrors_ReadsAndSetsParameterAndSaves()
{
const string testFilePath = "TestFile";
const string testGameName = "Test Game";
const string testParametersInput = "test input";
const string testParametersOutput = "test output";
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiForFileReadAllTextSuccess(coreApiMock, testFilePath, testParametersInput);
SetUpCoreApiForFileWriteAllTextSuccess(coreApiMock, testFilePath, testParametersOutput);
var editorMock = new Mock<ScenarioParametersEditor>();
var readResponse = Response.Ok(new Response());
editorMock.Setup(target => target.ReadParameters(testParametersInput))
.Returns(readResponse)
.Verifiable();
var setResponse = Response.Ok(new Response());
editorMock.Setup(target => target.SetParameter(ScenarioParameterKeys.GameName, testGameName))
.Returns(setResponse)
.Verifiable();
SaveParametersResponse saveResponse = Response.Ok(new SaveParametersResponse(testParametersOutput));
editorMock.Setup(target => target.SaveParameters())
.Returns(saveResponse)
.Verifiable();
ScenarioParametersUpdater underTest = GetUnitUnderTest(coreApiMock, editorMock);
// Act
Response response = underTest.Update(testFilePath, PrepareParameters(testGameName));
// Assert
coreApiMock.Verify();
editorMock.Verify();
Assert.IsTrue(response.Success);
}
private void SetUpCoreApiForFileReadAllTextSuccess(Mock<CoreApi> coreApiMock, string testFilePath, string testParametersInput)
{
FileReadAllTextResponse response = Response.Ok(new FileReadAllTextResponse(testParametersInput));
coreApiMock.Setup(target => target.FileReadAllText(testFilePath))
.Returns(response)
.Verifiable();
}
private void SetUpCoreApiForFileWriteAllTextSuccess(Mock<CoreApi> coreApiMock, string testFilePath, string testParametersOutput)
{
var response = Response.Ok(new Response());
coreApiMock.Setup(target => target.FileWriteAllText(testFilePath, testParametersOutput))
.Returns(response)
.Verifiable();
}
private IReadOnlyDictionary<string, string> PrepareParameters(string gameName)
{
return new Dictionary<string, string>
{
{ ScenarioParameterKeys.GameName, gameName }
};
}
private ScenarioParametersUpdater GetUnitUnderTest(Mock<CoreApi> coreApi = null,
Mock<ScenarioParametersEditor> scenarioParametersEditor = null)
{
coreApi = coreApi ?? new Mock<CoreApi>();
scenarioParametersEditor = scenarioParametersEditor ?? new Mock<ScenarioParametersEditor>();
return new ScenarioParametersUpdater(coreApi.Object, () => scenarioParametersEditor.Object);
}
}
}
| 263 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.Shared;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
internal class TestedDeployer : DeployerBase
{
private readonly bool _deployReturnsSuccess;
public override string DisplayName => "Test";
public override string Description => "TestDescription";
public override string HelpUrl => "https://test.com/";
public override string ScenarioFolder => "TestScenario";
public override bool HasGameServer { get; }
public TestedDeployer(Delay delay, CoreApi coreApi, bool deployReturnsSuccess = true, bool hasGameServer = false) : base(delay, coreApi)
{
_deployReturnsSuccess = deployReturnsSuccess;
HasGameServer = hasGameServer;
}
protected override Task<DeploymentResponse> Deploy(DeploymentRequest request)
{
DeploymentResponse result = _deployReturnsSuccess
? Response.Ok(new DeploymentResponse())
: Response.Fail(new DeploymentResponse());
return Task.FromResult(result);
}
}
}
| 39 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
using UnityEngine.TestTools;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class UntilResponseFailurePollerTests
{
[UnityTest]
public IEnumerator Poll_WhenStopConditionIsTrueAndResponseOk_ReturnsExpectedResponse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var returnedResponse = new Response();
UntilResponseFailurePoller underTest = GetUnitUnderTest();
Response response = await underTest.Poll(0, () => Response.Ok(returnedResponse), _ => true);
Assert.AreEqual(returnedResponse, response);
}
}
[UnityTest]
public IEnumerator Poll_WhenStopConditionIsFalseAndResponseFail_ReturnsExpectedResponse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var returnedResponse = new Response();
UntilResponseFailurePoller underTest = GetUnitUnderTest();
Response response = await underTest.Poll(0, () => Response.Fail(returnedResponse), _ => false);
Assert.AreEqual(returnedResponse, response);
Assert.IsFalse(response.Success);
}
}
private static UntilResponseFailurePoller GetUnitUnderTest()
{
var delayMock = new Mock<Delay>();
delayMock.Setup(target => target.Wait(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
return new UntilResponseFailurePoller(delayMock.Object);
}
}
}
| 58 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.GameLiftLocalTesting.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using UnityEngine.TestTools;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class LocalTestTests
{
#region GameLiftLocalPath
[Test]
public void GameLiftLocalPath_WhenNewInstance_IsNull()
{
LocalTest underTest = GetUnitUnderTest();
Assert.IsNull(underTest.GameLiftLocalPath);
}
[Test]
public void GameLiftLocalPath_WhenRefreshAndGameLiftLocalPathNotSet_IsNull()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithGameLiftLocalPath(success: false);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.LocalServerPath, success: false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.GameLiftLocalPort, success: false, null);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
coreApiMock.Verify();
Assert.IsNull(underTest.GameLiftLocalPath);
}
[Test]
[TestCase(false)]
[TestCase(true)]
public void GameLiftLocalPath_WhenRefreshAndGameLiftLocalPathSetAndExistsParam_IsExpected(bool glFileExists)
{
string testGlPath = DateTime.UtcNow.Ticks.ToString();
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithGameLiftLocalPath(success: true, testGlPath);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.LocalServerPath, success: false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.GameLiftLocalPort, success: false, null);
coreApiMock.Setup(target => target.FileExists(testGlPath))
.Returns(glFileExists);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
coreApiMock.Verify();
Assert.AreEqual(glFileExists ? testGlPath : null, underTest.GameLiftLocalPath);
}
#endregion
#region IsBootstrapped
[Test]
public void IsBootstrapped_WhenNewInstance_IsFalse()
{
LocalTest underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.IsBootstrapped);
}
[Test]
[TestCase(false, false, false)]
[TestCase(true, false, false)]
[TestCase(true, true, true)]
public void IsBootstrapped_WhenRefreshAndGameLiftLocalPathSetParam_IsTrue(bool glPathSet, bool glFileExists, bool expected)
{
string testGlPath = "GL" + DateTime.UtcNow.Ticks.ToString();
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Setup(target => target.FileExists(testGlPath))
.Returns(glFileExists);
coreApiMock.SetUpCoreApiWithGameLiftLocalPath(success: glPathSet, testGlPath);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.LocalServerPath, success: false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.GameLiftLocalPort, success: false, null);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
coreApiMock.Verify();
Assert.AreEqual(expected, underTest.IsBootstrapped);
}
#endregion
[Test]
[TestCase(false, -1, false)]
[TestCase(false, 0, false)]
[TestCase(false, 1, false)]
[TestCase(false, 100, false)]
[TestCase(true, -1, true)]
[TestCase(true, 0, true)]
[TestCase(true, 1, true)]
[TestCase(true, 100, true)]
public void IsFormFilled_WhenBuildExePathExistsAndPortParams_IsExpected(bool exeExists, int port, bool expected)
{
string testBuildExePath = "build" + DateTime.UtcNow.Ticks.ToString();
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Setup(target => target.FileExists(testBuildExePath))
.Returns(exeExists);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.BuildExecutablePath = testBuildExePath;
underTest.GameLiftLocalPort = port;
coreApiMock.Verify();
Assert.AreEqual(expected, underTest.IsBuildExecutablePathFilled);
}
#region CanStart
[Test]
public void CanStart_WhenNewInstance_IsFalse()
{
LocalTest underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.CanStart);
}
[Test]
public void CanStart_WhenAnyFileExistsIsFalse_IsFalse()
{
Mock<CoreApi> coreApiMock = SetUpCoreApiAnyFileExistsIsFalse();
LocalTest underTest = GetUnitUnderTest(coreApiMock);
Assert.IsFalse(underTest.CanStart);
}
[Test]
[TestCase(false, false, false, -1, false)]
[TestCase(false, false, false, 0, false)]
[TestCase(false, false, false, 1, false)]
[TestCase(false, false, false, 100, false)]
[TestCase(false, false, true, -1, false)]
[TestCase(false, false, true, 0, false)]
[TestCase(false, false, true, 1, false)]
[TestCase(false, false, true, 100, false)]
[TestCase(true, false, false, -1, false)]
[TestCase(true, false, false, 0, false)]
[TestCase(true, false, false, 1, false)]
[TestCase(true, false, false, 100, false)]
[TestCase(true, false, true, -1, false)]
[TestCase(true, false, true, 0, false)]
[TestCase(true, false, true, 1, false)]
[TestCase(true, false, true, 100, false)]
[TestCase(true, true, false, -1, false)]
[TestCase(true, true, false, 0, false)]
[TestCase(true, true, false, 1, false)]
[TestCase(true, true, false, 100, false)]
[TestCase(true, true, true, -1, true)]
[TestCase(true, true, true, 0, true)]
[TestCase(true, true, true, 1, true)]
[TestCase(true, true, true, 100, true)]
public void CanStart_WhenRefreshAndIsBootstrappedAndIsFormFilledParams_IsExpected(bool glPathSet, bool glFileExists, bool exeExists, int port, bool expected)
{
string testGlPath = "GL" + DateTime.UtcNow.Ticks.ToString();
string testBuildExePath = "build" + DateTime.UtcNow.Ticks.ToString();
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Setup(target => target.FileExists(testGlPath))
.Returns(glFileExists);
coreApiMock.SetUpCoreApiWithGameLiftLocalPath(success: glPathSet, testGlPath);
coreApiMock.Setup(target => target.FileExists(testBuildExePath))
.Returns(exeExists);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.LocalServerPath, success: false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.GameLiftLocalPort, success: false, null);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
underTest.BuildExecutablePath = testBuildExePath;
underTest.GameLiftLocalPort = port;
coreApiMock.Verify();
Assert.AreEqual(expected, underTest.CanStart);
}
#endregion
#region CanStop
[Test]
public void CanStop_WhenNewInstance_IsFalse()
{
LocalTest underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.CanStop);
}
[UnityTest]
public IEnumerator CanStop_WhenNewInstanceAndStart_IsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
LocalTest underTest = GetUnitUnderTest();
await underTest.Start();
Assert.IsFalse(underTest.CanStop);
}
}
[UnityTest]
public IEnumerator CanStop_WhenCanStartAndStartSucceeds_IsTrue()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
LocalTest underTest = await TestWhenCanStartAndStartSucceeds(coreApiMock);
coreApiMock.Verify();
Assert.IsTrue(underTest.CanStop);
}
}
#endregion
#region Start
[UnityTest]
public IEnumerator Start_WhenAnyFileExistsIsFalse_NotCallingCore()
{
yield return Run().AsCoroutine();
async Task Run()
{
Mock<CoreApi> coreApiMock = SetUpCoreApiAnyFileExistsIsFalse();
coreApiMock.Verify(target => target.StartGameLiftLocal(It.IsAny<string>(), It.IsAny<int>(), LocalOperatingSystem.WINDOWS), Times.Never());
LocalTest underTest = GetUnitUnderTest(coreApiMock);
await underTest.Start();
coreApiMock.Verify();
}
}
[Test]
public void Start_WhenCanStartAndStartAndCancelledWhileWaiting_ThrowsTaskCanceledException()
{
string testBuildExePath = "build" + DateTime.UtcNow.Ticks.ToString();
int testPort = UnityEngine.Random.Range(1, ushort.MaxValue);
var coreApiMock = new Mock<CoreApi>();
SetUpWithCoreStartGameLiftLocal(coreApiMock, success: true, testBuildExePath, testPort);
var delayMock = new Mock<Delay>();
delayMock.Setup(target => target.Wait(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Throws(new TaskCanceledException())
.Verifiable();
LocalTest underTest = GetUnitUnderTest(coreApiMock, delayMock);
underTest.Refresh();
underTest.BuildExecutablePath = testBuildExePath;
underTest.GameLiftLocalPort = testPort;
AssertAsync.ThrowsAsync<TaskCanceledException>(async () => await underTest.Start());
}
#endregion
#region IsDeploymentRunning
[Test]
public void IsDeploymentRunning_WhenNewInstance_IsFalse()
{
LocalTest underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.IsDeploymentRunning);
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenAnyFileExistsIsFalseAndStart_IsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
Mock<CoreApi> coreApiMock = SetUpCoreApiAnyFileExistsIsFalse();
LocalTest underTest = GetUnitUnderTest(coreApiMock);
await underTest.Start();
Assert.IsFalse(underTest.IsDeploymentRunning);
}
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenCanStartAndStartAndRunLocalServerFails_IsTrue()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
LocalTest underTest = await TestWhenCanStartAndStartAndRunLocalServerFails(coreApiMock);
// Assert
coreApiMock.Verify();
Assert.IsTrue(underTest.IsDeploymentRunning);
}
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenCanStartAndStartAndRunLocalServerFailsAndStop_IsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiWithStopProcess(coreApiMock, success: true);
LocalTest underTest = await TestWhenCanStartAndStartAndRunLocalServerFails(coreApiMock);
underTest.Stop();
// Assert
coreApiMock.Verify();
Assert.IsFalse(underTest.IsDeploymentRunning);
}
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenCanStartAndStartSucceedsAndStop_IsFalse()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiWithStopProcess(coreApiMock, success: true);
LocalTest underTest = await TestWhenCanStartAndStartSucceeds(coreApiMock);
underTest.Stop();
// Assert
coreApiMock.Verify();
Assert.IsFalse(underTest.IsDeploymentRunning);
}
}
[UnityTest]
public IEnumerator IsDeploymentRunning_WhenCanStartAndStartSucceeds_IsTrue()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
LocalTest underTest = await TestWhenCanStartAndStartSucceeds(coreApiMock);
// Assert
coreApiMock.Verify();
Assert.IsTrue(underTest.IsDeploymentRunning);
}
}
#endregion
#region Status
[Test]
public void Status_WhenNewInstance_IsNotDisplayed()
{
LocalTest underTest = GetUnitUnderTest();
Assert.IsFalse(underTest.Status.IsDisplayed);
}
[UnityTest]
public IEnumerator Status_WhenCanStartAndStartAndStartGameLiftLocalFails_IsDisplayedError()
{
yield return Run().AsCoroutine();
async Task Run()
{
string testBuildExePath = "build" + DateTime.UtcNow.Ticks.ToString();
int testPort = UnityEngine.Random.Range(1, ushort.MaxValue);
var coreApiMock = new Mock<CoreApi>();
SetUpWithCoreStartGameLiftLocal(coreApiMock, success: false, testBuildExePath, testPort);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
underTest.BuildExecutablePath = testBuildExePath;
underTest.GameLiftLocalPort = testPort;
// Act
await underTest.Start();
// Assert
coreApiMock.Verify();
Assert.AreEqual(MessageType.Error, underTest.Status.Type);
}
}
[UnityTest]
public IEnumerator Status_WhenCanStartAndStartAndRunLocalServerFails_IsDisplayedError()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
LocalTest underTest = await TestWhenCanStartAndStartAndRunLocalServerFails(coreApiMock);
// Assert
coreApiMock.Verify();
Assert.AreEqual(MessageType.Error, underTest.Status.Type);
}
}
[UnityTest]
public IEnumerator Status_WhenCanStartAndStartAndStopWhileWaiting_IsNotDisplayed()
{
yield return Run().AsCoroutine();
async Task Run()
{
string testBuildExePath = "build" + DateTime.UtcNow.Ticks.ToString();
int testPort = UnityEngine.Random.Range(1, ushort.MaxValue);
var coreApiMock = new Mock<CoreApi>();
SetUpWithCoreStartGameLiftLocal(coreApiMock, success: true, testBuildExePath, testPort);
SetUpCoreApiWithStopProcess(coreApiMock, success: true);
var delayMock = new Mock<Delay>();
LocalTest underTest = GetUnitUnderTest(coreApiMock, delayMock);
delayMock.Setup(target => target.Wait(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Callback(() => underTest.Stop());
underTest.Refresh();
underTest.BuildExecutablePath = testBuildExePath;
underTest.GameLiftLocalPort = testPort;
// Act
await underTest.Start();
// Assert
coreApiMock.Verify();
Assert.IsFalse(underTest.Status.IsDisplayed);
}
}
[UnityTest]
public IEnumerator Status_WhenCanStartAndStartSucceeds_IsDisplayedInfo()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
LocalTest underTest = await TestWhenCanStartAndStartSucceeds(coreApiMock);
// Assert
coreApiMock.Verify();
Assert.AreEqual(MessageType.Info, underTest.Status.Type);
}
}
[UnityTest]
public IEnumerator Status_WhenCanStartAndStartAndRunLocalServerFailsAndStop_IsNotDisplayed()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiWithStopProcess(coreApiMock, success: true);
LocalTest underTest = await TestWhenCanStartAndStartAndRunLocalServerFails(coreApiMock);
underTest.Stop();
// Assert
coreApiMock.Verify();
Assert.IsFalse(underTest.Status.IsDisplayed);
}
}
[UnityTest]
public IEnumerator Status_WhenCanStartAndStartSucceedsAndStop_IsNotDisplayed()
{
yield return Run().AsCoroutine();
async Task Run()
{
var coreApiMock = new Mock<CoreApi>();
SetUpCoreApiWithStopProcess(coreApiMock, success: true);
LocalTest underTest = await TestWhenCanStartAndStartSucceeds(coreApiMock);
underTest.Stop();
// Assert
coreApiMock.Verify();
Assert.IsFalse(underTest.Status.IsDisplayed);
}
}
#endregion
#region Form fields
[Test]
public void BuildExePath_WhenNewInstance_IsNull()
{
LocalTest underTest = GetUnitUnderTest();
Assert.IsNull(underTest.BuildExecutablePath);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void BuildExePath_WhenRefreshAndPathSavedParam_IsExpected(bool saved)
{
string testBuildExePath = "build" + DateTime.UtcNow.Ticks.ToString();
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithGameLiftLocalPath(success: false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.LocalServerPath, saved, testBuildExePath);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.GameLiftLocalPort, success: false, null);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
coreApiMock.Verify();
if (saved)
{
Assert.AreEqual(testBuildExePath, underTest.BuildExecutablePath);
}
else
{
Assert.IsNull(underTest.BuildExecutablePath);
}
}
[Test]
[TestCase(int.MinValue, 1)]
[TestCase(int.MinValue + 12345, 1)]
[TestCase(-1000, 1)]
[TestCase(0, 1)]
[TestCase(ushort.MaxValue + 1, ushort.MaxValue)]
[TestCase(int.MaxValue, ushort.MaxValue)]
[TestCase(int.MaxValue - 123, ushort.MaxValue)]
public void GameLiftLocalPort_WhenSetOutOfRangeParam_IsExpected(int testPort, int expected)
{
LocalTest underTest = GetUnitUnderTest();
underTest.GameLiftLocalPort = testPort;
Assert.AreEqual(expected, underTest.GameLiftLocalPort);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void GameLiftLocalPort_WhenRefreshAndPortSavedParam_IsExpected(bool saved)
{
int testPort = UnityEngine.Random.Range(1, ushort.MaxValue);
string testPortSetting = SettingsFormatter.FormatInt(testPort);
var coreApiMock = new Mock<CoreApi>();
coreApiMock.SetUpCoreApiWithGameLiftLocalPath(success: false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.GameLiftLocalPort, saved, testPortSetting);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.LocalServerPath, success: false, null);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
coreApiMock.Verify();
if (saved)
{
Assert.AreEqual(testPort, underTest.GameLiftLocalPort);
}
}
#endregion
private static async Task<LocalTest> TestWhenCanStartAndStartAndRunLocalServerFails(Mock<CoreApi> coreApiMock)
{
string testBuildExePath = "build" + DateTime.UtcNow.Ticks.ToString();
int testPort = UnityEngine.Random.Range(1, ushort.MaxValue);
SetUpWithCoreStartGameLiftLocal(coreApiMock, success: true, testBuildExePath, testPort);
SetUpCoreApiWithRunLocalServer(coreApiMock, success: false, testBuildExePath);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
underTest.BuildExecutablePath = testBuildExePath;
underTest.GameLiftLocalPort = testPort;
// Act
await underTest.Start();
return underTest;
}
private static async Task<LocalTest> TestWhenCanStartAndStartSucceeds(Mock<CoreApi> coreApiMock)
{
string testBuildExePath = "build" + DateTime.UtcNow.Ticks.ToString();
int testPort = UnityEngine.Random.Range(1, ushort.MaxValue);
SetUpWithCoreStartGameLiftLocal(coreApiMock, success: true, testBuildExePath, testPort);
SetUpCoreApiWithRunLocalServer(coreApiMock, success: true, testBuildExePath);
LocalTest underTest = GetUnitUnderTest(coreApiMock);
underTest.Refresh();
underTest.BuildExecutablePath = testBuildExePath;
underTest.GameLiftLocalPort = testPort;
// Act
await underTest.Start();
return underTest;
}
private static void SetUpWithCoreStartGameLiftLocal(Mock<CoreApi> coreApiMock, bool success, string testBuildExePath, int testPort)
{
string testGlPath = "GL" + DateTime.UtcNow.Ticks.ToString();
coreApiMock.Setup(target => target.FileExists(testBuildExePath))
.Returns(true)
.Verifiable();
coreApiMock.Setup(target => target.FileExists(testGlPath))
.Returns(true)
.Verifiable();
coreApiMock.SetUpCoreApiWithGameLiftLocalPath(success: true, testGlPath);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.LocalServerPath, success: false, null);
coreApiMock.SetUpCoreApiWithSetting(SettingsKeys.GameLiftLocalPort, success: false, null);
SetUpCoreApiWithStartGameLiftLocal(coreApiMock, success: success, testGlPath, testPort);
}
private static Mock<CoreApi> SetUpCoreApiAnyFileExistsIsFalse()
{
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Setup(target => target.FileExists(It.IsAny<string>()))
.Returns(false);
return coreApiMock;
}
private static void SetUpCoreApiWithStartGameLiftLocal(Mock<CoreApi> coreApiMock, bool success,
string gameLiftLocalFilePath, int port)
{
var response = new StartResponse();
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.StartGameLiftLocal(gameLiftLocalFilePath, port, LocalOperatingSystem.WINDOWS))
.Returns(response)
.Verifiable();
}
private static void SetUpCoreApiWithRunLocalServer(Mock<CoreApi> coreApiMock, bool success, string exeFilePath)
{
var response = new RunLocalServerResponse();
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.RunLocalServer(exeFilePath, "testApplicationProductName", LocalOperatingSystem.WINDOWS))
.Returns(response)
.Verifiable();
}
private static void SetUpCoreApiWithStopProcess(Mock<CoreApi> coreApiMock, bool success)
{
var response = new StopResponse();
response = success ? Response.Ok(response) : Response.Fail(response);
coreApiMock.Setup(target => target.StopProcess(It.IsAny<int>(), LocalOperatingSystem.WINDOWS))
.Returns(response)
.Verifiable();
}
private static void SetUpDelayMockWait(Mock<Delay> delayMock)
{
delayMock.Setup(target => target.Wait(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask)
.Verifiable();
}
private static LocalTest GetUnitUnderTest(Mock<CoreApi> coreApi = null, Mock<Delay> delayMock = null)
{
coreApi = coreApi ?? new Mock<CoreApi>();
TextProvider textProvider = TextProviderFactory.Create();
if (delayMock == null)
{
delayMock = new Mock<Delay>();
SetUpDelayMockWait(delayMock);
}
return new LocalTest(coreApi.Object, textProvider, delayMock.Object, new MockLogger());
}
}
}
| 708 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class BootstrapSettingTests
{
[Test]
public void IsPrimaryActionEnabled_WhenNewInstance_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
var credentialsSettingMock = new Mock<CredentialsSetting>(coreApiMock.Object);
var underTest = new BootstrapSetting(coreApiMock.Object, credentialsSettingMock.Object);
bool actual = underTest.IsPrimaryActionEnabled;
// Assert
coreApiMock.Verify();
Assert.IsFalse(actual);
}
[Test]
[TestCase(false, false)]
[TestCase(true, true)]
public void IsPrimaryActionEnabled_WhenRefreshAndCredentialsSettingIsConfiguredParam_IsExpected(bool credentialsSettingSet, bool expected)
{
const bool isRegionValid = true;
const string testBucketName = "test-bucket";
const string testRegion = "test-region";
Mock<CoreApi> coreApiMock = SetUpCurrentBucketForSuccessSettings(testBucketName, testRegion, isRegionValid);
var credentialsSettingMock = new Mock<CredentialsSetting>(coreApiMock.Object);
credentialsSettingMock.Setup(target => target.IsConfigured)
.Returns(credentialsSettingSet)
.Verifiable();
var underTest = new BootstrapSetting(coreApiMock.Object, credentialsSettingMock.Object);
// Act
underTest.Refresh();
bool actual = underTest.IsPrimaryActionEnabled;
// Assert
coreApiMock.Verify();
Assert.AreEqual(expected, actual);
}
[Test]
public void IsConfigured_WhenRefreshAndBucketNotSavedAndRegionSaved_IsFalse()
{
const string testRegion = "test-region";
var coreApiMock = new Mock<CoreApi>();
GetSettingResponse bucketResponse = Response.Fail(new GetSettingResponse());
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentBucketName))
.Returns(bucketResponse)
.Verifiable();
var regionResponse = new GetSettingResponse() { Value = testRegion };
regionResponse = Response.Ok(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.IsValidRegion(testRegion))
.Returns(true);
var credentialsSettingMock = new Mock<CredentialsSetting>(coreApiMock.Object);
var underTest = new BootstrapSetting(coreApiMock.Object, credentialsSettingMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsFalse(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndBucketSavedAndRegionNotSaved_IsFalse()
{
const string testBucketName = "test-bucket";
var coreApiMock = new Mock<CoreApi>();
var bucketResponse = new GetSettingResponse() { Value = testBucketName };
bucketResponse = Response.Ok(bucketResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentBucketName))
.Returns(bucketResponse)
.Verifiable();
var regionResponse = new GetSettingResponse();
regionResponse = Response.Fail(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.IsValidRegion(It.IsAny<string>()))
.Returns(false);
var credentialsSettingMock = new Mock<CredentialsSetting>(coreApiMock.Object);
var underTest = new BootstrapSetting(coreApiMock.Object, credentialsSettingMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsFalse(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndBucketSavedAndRegionSavedInvalid_IsFalse()
{
const bool isRegionValid = false;
const string testBucketName = "test-bucket";
const string testRegion = "test-region";
Mock<CoreApi> coreApiMock = SetUpCurrentBucketForSuccessSettings(testBucketName, testRegion, isRegionValid);
var credentialsSettingMock = new Mock<CredentialsSetting>(coreApiMock.Object);
var underTest = new BootstrapSetting(coreApiMock.Object, credentialsSettingMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsFalse(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndBucketAndRegionSaved_IsTrue()
{
const bool isRegionValid = true;
const string testBucketName = "test-bucket";
const string testRegion = "test-region";
Mock<CoreApi> coreApiMock = SetUpCurrentBucketForSuccessSettings(testBucketName, testRegion, isRegionValid);
var credentialsSettingMock = new Mock<CredentialsSetting>(coreApiMock.Object);
var underTest = new BootstrapSetting(coreApiMock.Object, credentialsSettingMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsTrue(isConfigured);
}
private Mock<CoreApi> SetUpCurrentBucketForSuccessSettings(string testBucketName, string testRegion, bool isRegionValid)
{
var coreApiMock = new Mock<CoreApi>();
var bucketResponse = new GetSettingResponse() { Value = testBucketName };
bucketResponse = Response.Ok(bucketResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentBucketName))
.Returns(bucketResponse)
.Verifiable();
var regionResponse = new GetSettingResponse() { Value = testRegion };
regionResponse = Response.Ok(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.IsValidRegion(testRegion))
.Returns(isRegionValid)
.Verifiable();
return coreApiMock;
}
}
}
| 180 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using AmazonGameLift.Editor;
using AmazonGameLiftPlugin.Core.CredentialManagement.Models;
using AmazonGameLiftPlugin.Core.SettingsManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class CredentialsSettingTests
{
[Test]
public void IsConfigured_WhenRefreshAndProfileNotSaved_IsFalse()
{
var coreApiMock = new Mock<CoreApi>();
GetSettingResponse profileResponse = Response.Fail(new GetSettingResponse());
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentProfileName))
.Returns(profileResponse)
.Verifiable();
var underTest = new CredentialsSetting(coreApiMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsFalse(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndCredentialsNotSaved_IsFalse()
{
const string testProfileName = "test-profile";
var coreApiMock = new Mock<CoreApi>();
var profileResponse = new GetSettingResponse() { Value = testProfileName };
profileResponse = Response.Ok(profileResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentProfileName))
.Returns(profileResponse)
.Verifiable();
var credentialsResponse = new RetriveAwsCredentialsResponse();
credentialsResponse = Response.Fail(credentialsResponse);
coreApiMock.Setup(target => target.RetrieveAwsCredentials(testProfileName))
.Returns(credentialsResponse)
.Verifiable();
var underTest = new CredentialsSetting(coreApiMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsFalse(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndRegionNotSaved_IsFalse()
{
const string testProfileName = "test-profile";
var coreApiMock = new Mock<CoreApi>();
var profileResponse = new GetSettingResponse() { Value = testProfileName };
profileResponse = Response.Ok(profileResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentProfileName))
.Returns(profileResponse)
.Verifiable();
var credentialsResponse = new RetriveAwsCredentialsResponse();
credentialsResponse = Response.Ok(credentialsResponse);
coreApiMock.Setup(target => target.RetrieveAwsCredentials(testProfileName))
.Returns(credentialsResponse)
.Verifiable();
var regionResponse = new GetSettingResponse();
regionResponse = Response.Fail(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.IsValidRegion(It.IsAny<string>()))
.Returns(false);
var underTest = new CredentialsSetting(coreApiMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsFalse(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndRegionSavedInvalid_IsFalse()
{
const bool isRegionValid = false;
const string testProfileName = "test-profile";
Mock<CoreApi> coreApiMock = SetUpCoreApiForRefreshSuccess(testProfileName, isRegionValid);
var underTest = new CredentialsSetting(coreApiMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsFalse(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndAllDataValid_IsTrue()
{
const bool isRegionValid = true;
const string testProfileName = "test-profile";
Mock<CoreApi> coreApiMock = SetUpCoreApiForRefreshSuccess(testProfileName, isRegionValid);
var underTest = new CredentialsSetting(coreApiMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsTrue(isConfigured);
}
private Mock<CoreApi> SetUpCoreApiForRefreshSuccess(string testProfileName, bool isRegionValid)
{
var coreApiMock = new Mock<CoreApi>();
var profileResponse = new GetSettingResponse() { Value = testProfileName };
profileResponse = Response.Ok(profileResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentProfileName))
.Returns(profileResponse)
.Verifiable();
var credentialsResponse = new RetriveAwsCredentialsResponse();
credentialsResponse = Response.Ok(credentialsResponse);
coreApiMock.Setup(target => target.RetrieveAwsCredentials(testProfileName))
.Returns(credentialsResponse)
.Verifiable();
var regionResponse = new GetSettingResponse();
regionResponse = Response.Ok(regionResponse);
coreApiMock.Setup(target => target.GetSetting(SettingsKeys.CurrentRegion))
.Returns(regionResponse)
.Verifiable();
coreApiMock.Setup(target => target.IsValidRegion(It.IsAny<string>()))
.Returns(isRegionValid)
.Verifiable();
return coreApiMock;
}
}
}
| 167 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Threading;
using AmazonGameLift.Editor;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Editor.UnitTests
{
public class JavaSettingTests
{
[Test]
public void IsConfigured_WhenRefreshAndApiCheckIsFalseAndCancelled_IsFalse()
{
// API mock
var coreApiMock = new Mock<CoreApi>();
var cancellationTokenSource = new CancellationTokenSource();
coreApiMock.Setup(target => target.CheckInstalledJavaVersion())
.Returns(false)
.Verifiable();
var underTest = new JavaSetting(coreApiMock.Object);
// Act
cancellationTokenSource.Cancel();
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
// Assert
Assert.IsFalse(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndApiCheckIsTrueAndCancelled_IsTrue()
{
// API mock
var coreApiMock = new Mock<CoreApi>();
var cancellationTokenSource = new CancellationTokenSource();
coreApiMock.Setup(target => target.CheckInstalledJavaVersion())
.Returns(true)
.Verifiable();
var underTest = new JavaSetting(coreApiMock.Object);
// Act
cancellationTokenSource.Cancel();
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsTrue(isConfigured);
}
[Test]
public void IsConfigured_WhenRefreshAndApiCheckIsTrue_IsTrue()
{
// API mock
var coreApiMock = new Mock<CoreApi>();
coreApiMock.Setup(target => target.CheckInstalledJavaVersion())
.Returns(true)
.Verifiable();
var underTest = new JavaSetting(coreApiMock.Object);
// Act
underTest.Refresh();
bool isConfigured = underTest.IsConfigured;
// Assert
coreApiMock.Verify();
Assert.IsTrue(isConfigured);
}
}
}
| 79 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.SecurityToken;
using AmazonGameLiftPlugin.Core.AccountManagement;
using AmazonGameLiftPlugin.Core.AccountManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Core.Tests.AccountManagement
{
[TestFixture]
public class AccountManagerTests
{
[Test]
public void RetrieveAccountIdByCredentials_WhenCredentialsIsCorrect_IsSuccessful()
{
string secretKey = "nonEmptySecretKey";
string accessKey = "nonemptyAccessKey";
string account = "123";
var mock = new Mock<IAmazonSecurityTokenServiceClientWrapper>();
mock.Setup(x => x.GetCallerIdentity(accessKey, secretKey)).Returns(
new Amazon.SecurityToken.Model.GetCallerIdentityResponse
{
HttpStatusCode = System.Net.HttpStatusCode.OK,
Account = account
});
var accountManager = new AccountManager(mock.Object);
RetrieveAccountIdByCredentialsResponse response = accountManager
.RetrieveAccountIdByCredentials(new RetrieveAccountIdByCredentialsRequest
{
SecretKey = secretKey,
AccessKey = accessKey
});
mock.Verify();
Assert.IsTrue(response.Success);
Assert.AreEqual(account, response.AccountId);
}
[Test]
public void RetrieveAccountIdByCredentials_WhenExternalApiReturnsFail_IsNotSuccessful()
{
string secretKey = "nonEmptySecretKey";
string accessKey = "nonemptyAccessKey";
var mock = new Mock<IAmazonSecurityTokenServiceClientWrapper>();
mock.Setup(x => x.GetCallerIdentity(accessKey, secretKey)).Returns(
new Amazon.SecurityToken.Model.GetCallerIdentityResponse
{
HttpStatusCode = System.Net.HttpStatusCode.BadRequest
});
var accountManager = new AccountManager(mock.Object);
RetrieveAccountIdByCredentialsResponse response = accountManager
.RetrieveAccountIdByCredentials(new RetrieveAccountIdByCredentialsRequest
{
SecretKey = secretKey,
AccessKey = accessKey
});
mock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(ErrorCode.AwsError, response.ErrorCode);
}
[Test]
public void RetrieveAccountIdByCredentials_WhenTokenClientThrowsException_IsNotSuccessful()
{
string secretKey = "nonEmptySecretKey";
string accessKey = "nonemptyAccessKey";
string exceptionMessage = "ErrorMessage";
var mock = new Mock<IAmazonSecurityTokenServiceClientWrapper>();
mock.Setup(x => x.GetCallerIdentity(accessKey, secretKey))
.Throws(new AmazonSecurityTokenServiceException(exceptionMessage));
var accountManager = new AccountManager(mock.Object);
RetrieveAccountIdByCredentialsResponse response = accountManager
.RetrieveAccountIdByCredentials(new RetrieveAccountIdByCredentialsRequest
{
AccessKey = accessKey,
SecretKey = secretKey
});
mock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(exceptionMessage, response.ErrorMessage);
}
[Test]
[TestCase("", "")]
[TestCase(null, null)]
[TestCase("nonempty", null)]
[TestCase(null, "nonEmpty")]
public void RetrieveAccountIdByCredentials_WhenCredentialsIsEmptyOrNull_IsNotSuccessful(string accessKey, string secretKey)
{
var mock = new Mock<IAmazonSecurityTokenServiceClientWrapper>();
var accountManager = new AccountManager(mock.Object);
RetrieveAccountIdByCredentialsResponse response = accountManager
.RetrieveAccountIdByCredentials(new RetrieveAccountIdByCredentialsRequest
{
AccessKey = accessKey,
SecretKey = secretKey
});
Assert.IsFalse(response.Success);
Assert.AreEqual(ErrorCode.InvalidParameters, response.ErrorCode);
}
}
}
| 115 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement.Models;
using AmazonGameLiftPlugin.Core.Shared;
using AmazonGameLiftPlugin.Core.UserIdentityManagement;
using Moq;
using Newtonsoft.Json;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Core.Tests.ApiGateWayManagement
{
[TestFixture]
public class ApiGatewayTests
{
[Test]
public void GetGameConnection_WhenValidParametersIsPassed_IsSuccessful()
{
var request = new GetGameConnectionRequest
{
ApiGatewayEndpoint = "http://test.com/stage",
ClientId = "NonEmpty",
IdToken = "NonEmpty",
RefreshToken = "NonEmpty"
};
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var httpClientMock = new Mock<IHttpClientWrapper>();
tokenHandler.Setup(x => x.RefreshTokenIfExpired(request, userIdentity.Object))
.Returns((true, string.Empty, "RefreshedIdToken"));
httpClientMock.Setup(x =>
x.Post(request.ApiGatewayEndpoint, "RefreshedIdToken", "get_game_connection", null))
.ReturnsAsync((HttpStatusCode.OK, @"{""port"":""1"",""ipAddress"":""1.1"", ""playerSessionId"": ""psess-123""}"));
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
GetGameConnectionResponse response = sut.GetGameConnection(request).Result;
Assert.IsTrue(response.Success);
Assert.AreEqual("1", response.Port);
Assert.AreEqual("1.1", response.IpAddress);
Assert.AreEqual("psess-123", response.PlayerSessionId);
Assert.AreEqual("RefreshedIdToken", response.IdToken);
tokenHandler.Verify();
httpClientMock.Verify();
}
[Test]
public void GetGameConnection_WhenLambdaReturnsNotReady_ReturnsNotReady()
{
var request = new GetGameConnectionRequest
{
ApiGatewayEndpoint = "http://test.com/stage",
ClientId = "NonEmpty",
IdToken = "NonEmpty",
RefreshToken = "NonEmpty"
};
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var httpClientMock = new Mock<IHttpClientWrapper>();
tokenHandler.Setup(x => x.RefreshTokenIfExpired(request, userIdentity.Object))
.Returns((true, string.Empty, "RefreshedIdToken"));
httpClientMock.Setup(
x => x.Post(request.ApiGatewayEndpoint, "RefreshedIdToken", "get_game_connection", null))
.ReturnsAsync((HttpStatusCode.NoContent, ""));
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
GetGameConnectionResponse response = sut.GetGameConnection(request).Result;
Assert.IsTrue(response.Success);
Assert.IsFalse(response.Ready);
tokenHandler.Verify();
httpClientMock.Verify();
}
[TestCase("", "NonEmpty", "NonEmpty", "NonEmpty")]
[TestCase("NonEmpty", "", "NonEmpty", "NonEmpty")]
[TestCase("NonEmpty", "NonEmpty", "", "NonEmpty")]
[TestCase("NonEmpty", "NonEmpty", "NonEmpty", "")]
public void GetGameConnection_WhenInValidParametersIsPassed_IsNotSuccessful(
string apiGatewayEndpoint,
string clientId,
string idToken,
string refreshToken
)
{
var request = new GetGameConnectionRequest
{
ApiGatewayEndpoint = apiGatewayEndpoint,
ClientId = clientId,
IdToken = idToken,
RefreshToken = refreshToken
};
var httpClientMock = new Mock<IHttpClientWrapper>();
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
GetGameConnectionResponse response = sut.GetGameConnection(request).Result;
Assert.IsFalse(response.Success);
Assert.AreEqual(ErrorCode.InvalidParameters, response.ErrorCode);
}
[Test]
public void GetGameConnection_WhenIdTokenIsInvalid_IsNotSuccessful()
{
var request = new GetGameConnectionRequest
{
ApiGatewayEndpoint = "NonEmpty",
ClientId = "NonEmpty",
IdToken = "NonEmpty",
RefreshToken = "NonEmpty"
};
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var httpClientMock = new Mock<IHttpClientWrapper>();
tokenHandler.Setup(x => x.RefreshTokenIfExpired(request, userIdentity.Object))
.Returns((false, ErrorCode.InvalidIdToken, string.Empty));
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
GetGameConnectionResponse response = sut.GetGameConnection(request).Result;
tokenHandler.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(ErrorCode.InvalidIdToken, response.ErrorCode);
}
[Test]
public void GetGameConnection_WhenApiGatewayReturnsFailure_IsNotSuccessful()
{
var request = new GetGameConnectionRequest
{
ApiGatewayEndpoint = "http://test.com/stage",
ClientId = "NonEmpty",
IdToken = "NonEmpty",
RefreshToken = "NonEmpty"
};
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var httpClientMock = new Mock<IHttpClientWrapper>();
tokenHandler.Setup(x => x.RefreshTokenIfExpired(request, userIdentity.Object))
.Returns((true, string.Empty, "nonEmpty"));
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
GetGameConnectionResponse response = sut.GetGameConnection(request).Result;
Assert.IsFalse(response.Success);
tokenHandler.Verify();
}
[Test]
public void StartGame_WhenValidParametersIsPassed_IsSuccessful()
{
var request = new StartGameRequest
{
ApiGatewayEndpoint = "http://test.com/stage",
ClientId = "NonEmpty",
IdToken = "NonEmpty",
RefreshToken = "NonEmpty"
};
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var httpClientMock = new Mock<IHttpClientWrapper>();
tokenHandler.Setup(x => x.RefreshTokenIfExpired(request, userIdentity.Object))
.Returns((true, string.Empty, "RefreshedIdToken"));
httpClientMock.Setup(x => x.Post(request.ApiGatewayEndpoint, "RefreshedIdToken", "start_game", null))
.ReturnsAsync((HttpStatusCode.Accepted, ""));
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
StartGameResponse response = sut.StartGame(request).Result;
Assert.IsTrue(response.Success);
Assert.AreEqual("RefreshedIdToken", response.IdToken);
tokenHandler.Verify();
httpClientMock.Verify();
}
[TestCase("", "NonEmpty", "NonEmpty", "NonEmpty")]
[TestCase("NonEmpty", "", "NonEmpty", "NonEmpty")]
[TestCase("NonEmpty", "NonEmpty", "", "NonEmpty")]
[TestCase("NonEmpty", "NonEmpty", "NonEmpty", "")]
public void StartGame_WhenInValidParametersIsPassed_IsNotSuccessful(
string apiGatewayEndpoint,
string clientId,
string idToken,
string refreshToken
)
{
var request = new StartGameRequest
{
ApiGatewayEndpoint = apiGatewayEndpoint,
ClientId = clientId,
IdToken = idToken,
RefreshToken = refreshToken
};
var httpClientMock = new Mock<IHttpClientWrapper>();
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
StartGameResponse response = sut.StartGame(request).Result;
Assert.IsFalse(response.Success);
Assert.AreEqual(ErrorCode.InvalidParameters, response.ErrorCode);
}
[Test]
public void StartGame_WhenIdTokenIsInvalid_IsNotSuccessful()
{
var request = new StartGameRequest
{
ApiGatewayEndpoint = "NonEmpty",
ClientId = "NonEmpty",
IdToken = "NonEmpty",
RefreshToken = "NonEmpty"
};
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var httpClientMock = new Mock<IHttpClientWrapper>();
tokenHandler.Setup(x => x.RefreshTokenIfExpired(request, userIdentity.Object))
.Returns((false, ErrorCode.InvalidIdToken, string.Empty));
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
StartGameResponse response = sut.StartGame(request).Result;
tokenHandler.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(ErrorCode.InvalidIdToken, response.ErrorCode);
}
[Test]
public void StartGame_WhenApiGatewayReturnsFailure_IsNotSuccessful()
{
var request = new StartGameRequest
{
ApiGatewayEndpoint = "http://test.com/stage",
ClientId = "NonEmpty",
IdToken = "NonEmpty",
RefreshToken = "NonEmpty"
};
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var httpClientMock = new Mock<IHttpClientWrapper>();
tokenHandler.Setup(x => x.RefreshTokenIfExpired(request, userIdentity.Object))
.Returns((true, string.Empty, "nonEmpty"));
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
StartGameResponse response = sut.StartGame(request).Result;
Assert.IsFalse(response.Success);
tokenHandler.Verify();
}
[Test]
public void StartGame_WhenApiGatewayReturnsConflict_IsNotSuccessfulAndCodeConflict()
{
var request = new StartGameRequest
{
ApiGatewayEndpoint = "http://test.com/stage",
ClientId = "NonEmpty",
IdToken = "NonEmpty",
RefreshToken = "NonEmpty"
};
var userIdentity = new Mock<IUserIdentity>();
var tokenHandler = new Mock<IJwtTokenExpirationCheck>();
var httpClientMock = new Mock<IHttpClientWrapper>();
httpClientMock.Setup(x => x.Post(request.ApiGatewayEndpoint, "RefreshedIdToken", "start_game", null))
.ReturnsAsync((HttpStatusCode.Conflict, ""));
tokenHandler.Setup(x => x.RefreshTokenIfExpired(request, userIdentity.Object))
.Returns((true, string.Empty, "RefreshedIdToken"));
var sut = new ApiGateway(
userIdentity.Object,
tokenHandler.Object,
httpClientMock.Object
);
StartGameResponse response = sut.StartGame(request).Result;
Assert.IsFalse(response.Success);
Assert.AreEqual(ErrorCode.ConflictError, response.ErrorCode);
tokenHandler.Verify();
}
}
}
| 359 |
amazon-gamelift-plugin-unity | aws | C# | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Amazon.GameLift.Model;
using AmazonGameLiftPlugin.Core.ApiGatewayManagement;
using AmazonGameLiftPlugin.Core.Shared;
using Moq;
using NUnit.Framework;
namespace AmazonGameLiftPlugin.Core.Tests.ApiGateWayManagement
{
[TestFixture]
public class LocalGameAdapterTests
{
[Test]
public void StartGame_WhenSearchGameSessionReturnsEmptySessions_IsSuccessful()
{
var amazonGameLiftClientWrapperMock = new Mock<IAmazonGameLiftClientWrapper>();
amazonGameLiftClientWrapperMock.Setup(x => x.CreateGameSessionAsync(It.IsAny<CreateGameSessionRequest>(), It.IsAny<CancellationToken>())).ReturnsAsync(new CreateGameSessionResponse { }).Verifiable();
amazonGameLiftClientWrapperMock.Setup(x => x.DescribeGameSessions(It.IsAny<DescribeGameSessionsRequest>())).ReturnsAsync(new DescribeGameSessionsResponse { }).Verifiable();
var adapter = new LocalGameAdapter(amazonGameLiftClientWrapperMock.Object);
ApiGatewayManagement.Models.StartGameResponse response = adapter.StartGame(new ApiGatewayManagement.Models.StartGameRequest()).Result;
amazonGameLiftClientWrapperMock.Verify();
Assert.IsTrue(response.Success);
}
[Test]
public void StartGame_WhenSearchGameSessionReturnsExistingSession_IsSuccessful()
{
var amazonGameLiftClientWrapperMock = new Mock<IAmazonGameLiftClientWrapper>();
amazonGameLiftClientWrapperMock.Setup(x => x.DescribeGameSessions(It.IsAny<DescribeGameSessionsRequest>())).ReturnsAsync(new DescribeGameSessionsResponse
{
GameSessions = new List<GameSession>()
{
new GameSession()
}
}).Verifiable();
var adapter = new LocalGameAdapter(amazonGameLiftClientWrapperMock.Object);
ApiGatewayManagement.Models.StartGameResponse response = adapter.StartGame(new ApiGatewayManagement.Models.StartGameRequest()).Result;
amazonGameLiftClientWrapperMock.Verify();
Assert.IsTrue(response.Success);
}
[Test]
public void StartGame_WhenExceptionThrows_IsNotSuccessful()
{
var amazonGameLiftClientWrapperMock = new Mock<IAmazonGameLiftClientWrapper>();
amazonGameLiftClientWrapperMock.Setup(x => x.DescribeGameSessions(It.IsAny<DescribeGameSessionsRequest>())).Throws(new Exception("Unknown Exception")).Verifiable();
var adapter = new LocalGameAdapter(amazonGameLiftClientWrapperMock.Object);
ApiGatewayManagement.Models.StartGameResponse response = adapter.StartGame(new ApiGatewayManagement.Models.StartGameRequest()).Result;
amazonGameLiftClientWrapperMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(response.ErrorCode, ErrorCode.UnknownError);
}
[Test]
public void GetGameConnection_WhenSearchGameSessionReturnsEmptySessions_IsNotSuccessful()
{
var amazonGameLiftClientWrapperMock = new Mock<IAmazonGameLiftClientWrapper>();
amazonGameLiftClientWrapperMock.Setup(x => x.DescribeGameSessions(It.IsAny<DescribeGameSessionsRequest>())).ReturnsAsync(new DescribeGameSessionsResponse { }).Verifiable();
var adapter = new LocalGameAdapter(amazonGameLiftClientWrapperMock.Object);
ApiGatewayManagement.Models.GetGameConnectionResponse response = adapter.GetGameConnection(new ApiGatewayManagement.Models.GetGameConnectionRequest()).Result;
amazonGameLiftClientWrapperMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(response.ErrorCode, ErrorCode.NoGameSessionWasFound);
}
[Test]
public void GetGameConnection_WhenSearchGameSessionReturnsSession_IsSuccessful()
{
var amazonGameLiftClientWrapperMock = new Mock<IAmazonGameLiftClientWrapper>();
amazonGameLiftClientWrapperMock.Setup(x => x.DescribeGameSessions(It.IsAny<DescribeGameSessionsRequest>())).ReturnsAsync(new DescribeGameSessionsResponse
{
GameSessions = new List<GameSession>
{
new GameSession
{
IpAddress = "NonEmptyIp",
DnsName = "NonEmptyDns",
Port = 1
}
}
}).Verifiable();
amazonGameLiftClientWrapperMock.Setup(x => x.CreatePlayerSession(It.IsAny<CreatePlayerSessionRequest>())).ReturnsAsync(new CreatePlayerSessionResponse
{
PlayerSession = new PlayerSession
{
IpAddress = "NonEmptyIp",
DnsName = "NonEmptyDns",
Port = 1,
PlayerSessionId = "NonEmptyPlayerSessionId"
}
}).Verifiable();
var adapter = new LocalGameAdapter(amazonGameLiftClientWrapperMock.Object);
ApiGatewayManagement.Models.GetGameConnectionResponse response = adapter.GetGameConnection(new ApiGatewayManagement.Models.GetGameConnectionRequest()).Result;
amazonGameLiftClientWrapperMock.VerifyAll();
Assert.IsTrue(response.Success);
Assert.AreEqual(response.IpAddress, "NonEmptyIp");
Assert.AreEqual(response.DnsName, "NonEmptyDns");
Assert.AreEqual(response.PlayerSessionId, "NonEmptyPlayerSessionId");
}
[Test]
public void GetGameConnection_WhenDescribeGameSessionsThrowsException_IsNotSuccessful()
{
var amazonGameLiftClientWrapperMock = new Mock<IAmazonGameLiftClientWrapper>();
amazonGameLiftClientWrapperMock.Setup(x => x.DescribeGameSessions(It.IsAny<DescribeGameSessionsRequest>())).Throws(new Exception("Unknown Exception")).Verifiable();
var adapter = new LocalGameAdapter(amazonGameLiftClientWrapperMock.Object);
ApiGatewayManagement.Models.GetGameConnectionResponse response = adapter.GetGameConnection(new ApiGatewayManagement.Models.GetGameConnectionRequest()).Result;
amazonGameLiftClientWrapperMock.Verify();
Assert.IsFalse(response.Success);
Assert.AreEqual(response.ErrorCode, ErrorCode.UnknownError);
}
[Test]
public void GetGameConnection_WhenCreatePlayerSessionThrowsException_IsNotSuccessful()
{
var amazonGameLiftClientWrapperMock = new Mock<IAmazonGameLiftClientWrapper>();
amazonGameLiftClientWrapperMock.Setup(x => x.DescribeGameSessions(It.IsAny<DescribeGameSessionsRequest>())).ReturnsAsync(new DescribeGameSessionsResponse
{
GameSessions = new List<GameSession>
{
new GameSession
{
IpAddress = "NonEmptyIp",
DnsName = "NonEmptyDns",
Port = 1
}
}
}).Verifiable();
amazonGameLiftClientWrapperMock.Setup(x => x.CreatePlayerSession(It.IsAny<CreatePlayerSessionRequest>())).Throws(new Exception("Unknown Exception")).Verifiable();
var adapter = new LocalGameAdapter(amazonGameLiftClientWrapperMock.Object);
ApiGatewayManagement.Models.GetGameConnectionResponse response = adapter.GetGameConnection(new ApiGatewayManagement.Models.GetGameConnectionRequest()).Result;
amazonGameLiftClientWrapperMock.VerifyAll();
Assert.IsFalse(response.Success);
Assert.AreEqual(response.ErrorCode, ErrorCode.UnknownError);
}
}
}
| 174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.