Missing files + start working on offline patcher

This commit is contained in:
2025-06-23 13:42:14 +02:00
parent 058d48196a
commit 2d36fecb45
70 changed files with 11475 additions and 12 deletions

View File

@@ -0,0 +1,8 @@
<linker>
<assembly fullname="System.Diagnostics.DiagnosticSource">
<type fullname="System.Diagnostics.Metrics.MetricsEventSource">
<!-- Used by System.Private.CoreLib via reflection to init the EventSource -->
<method name="GetInstance" />
</type>
</assembly>
</linker>

View File

@@ -0,0 +1,53 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Applications.Contracts;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class ApplicationResponsibilityTests
{
private ClientContext context;
private ApplicationsResponsibility sut;
[TestInitialize]
public void Initialize()
{
var logger = new Mock<ILogger>();
context = new ClientContext();
sut = new ApplicationsResponsibility(context, logger.Object);
}
[TestMethod]
public void MustAutoStartApplications()
{
var application1 = new Mock<IApplication<IApplicationWindow>>();
var application2 = new Mock<IApplication<IApplicationWindow>>();
var application3 = new Mock<IApplication<IApplicationWindow>>();
application1.SetupGet(a => a.AutoStart).Returns(true);
application2.SetupGet(a => a.AutoStart).Returns(false);
application3.SetupGet(a => a.AutoStart).Returns(true);
context.Applications.Add(application1.Object);
context.Applications.Add(application2.Object);
context.Applications.Add(application3.Object);
sut.Assume(ClientTask.AutoStartApplications);
application1.Verify(a => a.Start(), Times.Once);
application2.Verify(a => a.Start(), Times.Never);
application3.Verify(a => a.Start(), Times.Once);
}
}
}

View File

@@ -0,0 +1,350 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Browser.Contracts;
using SafeExamBrowser.Browser.Contracts.Events;
using SafeExamBrowser.Client.Contracts;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Configuration.Contracts;
using SafeExamBrowser.Core.Contracts.ResponsibilityModel;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Server.Contracts;
using SafeExamBrowser.Server.Contracts.Data;
using SafeExamBrowser.Settings;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
using SafeExamBrowser.UserInterface.Contracts.Shell;
using SafeExamBrowser.UserInterface.Contracts.Windows;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class BrowserResponsibilityTests
{
private AppConfig appConfig;
private Mock<IBrowserApplication> browser;
private ClientContext context;
private Mock<ICoordinator> coordinator;
private Mock<IMessageBox> messageBox;
private Mock<IRuntimeProxy> runtime;
private Mock<IServerProxy> server;
private AppSettings settings;
private Mock<ISplashScreen> splashScreen;
private Mock<ITaskbar> taskbar;
private BrowserResponsibility sut;
[TestInitialize]
public void Initialize()
{
var logger = new Mock<ILogger>();
var responsibilities = new Mock<IResponsibilityCollection<ClientTask>>();
appConfig = new AppConfig();
browser = new Mock<IBrowserApplication>();
context = new ClientContext();
coordinator = new Mock<ICoordinator>();
messageBox = new Mock<IMessageBox>();
runtime = new Mock<IRuntimeProxy>();
server = new Mock<IServerProxy>();
settings = new AppSettings();
splashScreen = new Mock<ISplashScreen>();
taskbar = new Mock<ITaskbar>();
context.AppConfig = appConfig;
context.Browser = browser.Object;
context.Responsibilities = responsibilities.Object;
context.Runtime = runtime.Object;
context.Server = server.Object;
context.Settings = settings;
sut = new BrowserResponsibility(
context,
coordinator.Object,
logger.Object,
messageBox.Object,
runtime.Object,
splashScreen.Object,
taskbar.Object);
sut.Assume(ClientTask.RegisterEvents);
}
[TestMethod]
public void MustAutoStartBrowser()
{
settings.Browser.EnableBrowser = true;
browser.SetupGet(b => b.AutoStart).Returns(true);
sut.Assume(ClientTask.AutoStartApplications);
browser.Verify(b => b.Start(), Times.Once);
browser.Reset();
browser.SetupGet(b => b.AutoStart).Returns(false);
sut.Assume(ClientTask.AutoStartApplications);
browser.Verify(b => b.Start(), Times.Never);
}
[TestMethod]
public void MustNotAutoStartBrowserIfNotEnabled()
{
settings.Browser.EnableBrowser = false;
browser.SetupGet(b => b.AutoStart).Returns(true);
sut.Assume(ClientTask.AutoStartApplications);
browser.Verify(b => b.Start(), Times.Never);
}
[TestMethod]
public void Browser_MustHandleUserIdentifierDetection()
{
var counter = 0;
var identifier = "abc123";
settings.SessionMode = SessionMode.Server;
server.Setup(s => s.SendUserIdentifier(It.IsAny<string>())).Returns(() => new ServerResponse(++counter == 3));
browser.Raise(b => b.UserIdentifierDetected += null, identifier);
server.Verify(s => s.SendUserIdentifier(It.Is<string>(id => id == identifier)), Times.Exactly(3));
}
[TestMethod]
public void Browser_MustTerminateIfRequested()
{
runtime.Setup(p => p.RequestShutdown()).Returns(new CommunicationResult(true));
browser.Raise(b => b.TerminationRequested += null);
runtime.Verify(p => p.RequestShutdown(), Times.Once);
}
[TestMethod]
public void Reconfiguration_MustAllowIfNoQuitPasswordSet()
{
var args = new DownloadEventArgs();
appConfig.TemporaryDirectory = @"C:\Folder\Does\Not\Exist";
coordinator.Setup(c => c.RequestReconfigurationLock()).Returns(true);
runtime.Setup(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>())).Returns(new CommunicationResult(true));
browser.Raise(b => b.ConfigurationDownloadRequested += null, "filepath.seb", args);
args.Callback(true, string.Empty);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Once);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Never);
runtime.Verify(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
Assert.IsTrue(args.AllowDownload);
}
[TestMethod]
public void Reconfiguration_MustNotAllowWithQuitPasswordAndNoUrl()
{
var args = new DownloadEventArgs();
appConfig.TemporaryDirectory = @"C:\Folder\Does\Not\Exist";
settings.Security.AllowReconfiguration = true;
settings.Security.QuitPasswordHash = "abc123";
runtime.Setup(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>())).Returns(new CommunicationResult(true));
browser.Raise(b => b.ConfigurationDownloadRequested += null, "filepath.seb", args);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Never);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Never);
runtime.Verify(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
Assert.IsFalse(args.AllowDownload);
}
[TestMethod]
public void Reconfiguration_MustNotAllowConcurrentExecution()
{
var args = new DownloadEventArgs();
appConfig.TemporaryDirectory = @"C:\Folder\Does\Not\Exist";
coordinator.Setup(c => c.RequestReconfigurationLock()).Returns(false);
runtime.Setup(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>())).Returns(new CommunicationResult(true));
browser.Raise(b => b.ConfigurationDownloadRequested += null, "filepath.seb", args);
args.Callback?.Invoke(true, string.Empty);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Once);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Never);
runtime.Verify(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
Assert.IsFalse(args.AllowDownload);
}
[TestMethod]
public void Reconfiguration_MustAllowIfUrlMatches()
{
var args = new DownloadEventArgs { Url = "sebs://www.somehost.org/some/path/some_configuration.seb?query=123" };
appConfig.TemporaryDirectory = @"C:\Folder\Does\Not\Exist";
coordinator.Setup(c => c.RequestReconfigurationLock()).Returns(true);
settings.Security.AllowReconfiguration = true;
settings.Security.QuitPasswordHash = "abc123";
settings.Security.ReconfigurationUrl = "sebs://www.somehost.org/some/path/*.seb?query=123";
runtime.Setup(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>())).Returns(new CommunicationResult(true));
browser.Raise(b => b.ConfigurationDownloadRequested += null, "filepath.seb", args);
args.Callback(true, string.Empty);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Once);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Never);
runtime.Verify(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
Assert.IsTrue(args.AllowDownload);
}
[TestMethod]
public void Reconfiguration_MustDenyIfNotAllowed()
{
var args = new DownloadEventArgs();
settings.Security.AllowReconfiguration = false;
settings.Security.QuitPasswordHash = "abc123";
browser.Raise(b => b.ConfigurationDownloadRequested += null, "filepath.seb", args);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Never);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Never);
runtime.Verify(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
Assert.IsFalse(args.AllowDownload);
}
[TestMethod]
public void Reconfiguration_MustDenyIfUrlDoesNotMatch()
{
var args = new DownloadEventArgs { Url = "sebs://www.somehost.org/some/path/some_configuration.seb?query=123" };
settings.Security.AllowReconfiguration = false;
settings.Security.QuitPasswordHash = "abc123";
settings.Security.ReconfigurationUrl = "sebs://www.somehost.org/some/path/other_configuration.seb?query=123";
browser.Raise(b => b.ConfigurationDownloadRequested += null, "filepath.seb", args);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Never);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Never);
runtime.Verify(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
Assert.IsFalse(args.AllowDownload);
}
[TestMethod]
public void Reconfiguration_MustCorrectlyHandleDownload()
{
var downloadPath = @"C:\Folder\Does\Not\Exist\filepath.seb";
var downloadUrl = @"https://www.host.abc/someresource.seb";
var filename = "filepath.seb";
var args = new DownloadEventArgs();
appConfig.TemporaryDirectory = @"C:\Folder\Does\Not\Exist";
coordinator.Setup(c => c.RequestReconfigurationLock()).Returns(true);
messageBox.Setup(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>())).Returns(MessageBoxResult.Yes);
runtime.Setup(r => r.RequestReconfiguration(
It.Is<string>(p => p == downloadPath),
It.Is<string>(u => u == downloadUrl))).Returns(new CommunicationResult(true));
settings.Security.AllowReconfiguration = true;
browser.Raise(b => b.ConfigurationDownloadRequested += null, filename, args);
args.Callback(true, downloadUrl, downloadPath);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Once);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Never);
runtime.Verify(r => r.RequestReconfiguration(It.Is<string>(p => p == downloadPath), It.Is<string>(u => u == downloadUrl)), Times.Once);
Assert.AreEqual(downloadPath, args.DownloadPath);
Assert.IsTrue(args.AllowDownload);
}
[TestMethod]
public void Reconfiguration_MustCorrectlyHandleFailedDownload()
{
var downloadPath = @"C:\Folder\Does\Not\Exist\filepath.seb";
var downloadUrl = @"https://www.host.abc/someresource.seb";
var filename = "filepath.seb";
var args = new DownloadEventArgs();
appConfig.TemporaryDirectory = @"C:\Folder\Does\Not\Exist";
coordinator.Setup(c => c.RequestReconfigurationLock()).Returns(true);
messageBox.Setup(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>())).Returns(MessageBoxResult.Yes);
runtime.Setup(r => r.RequestReconfiguration(
It.Is<string>(p => p == downloadPath),
It.Is<string>(u => u == downloadUrl))).Returns(new CommunicationResult(true));
settings.Security.AllowReconfiguration = true;
browser.Raise(b => b.ConfigurationDownloadRequested += null, filename, args);
args.Callback(false, downloadPath);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Once);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Once);
runtime.Verify(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
[TestMethod]
public void Reconfiguration_MustCorrectlyHandleFailedRequest()
{
var downloadPath = @"C:\Folder\Does\Not\Exist\filepath.seb";
var downloadUrl = @"https://www.host.abc/someresource.seb";
var filename = "filepath.seb";
var args = new DownloadEventArgs();
appConfig.TemporaryDirectory = @"C:\Folder\Does\Not\Exist";
coordinator.Setup(c => c.RequestReconfigurationLock()).Returns(true);
messageBox.Setup(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>())).Returns(MessageBoxResult.Yes);
runtime.Setup(r => r.RequestReconfiguration(
It.Is<string>(p => p == downloadPath),
It.Is<string>(u => u == downloadUrl))).Returns(new CommunicationResult(false));
settings.Security.AllowReconfiguration = true;
browser.Raise(b => b.ConfigurationDownloadRequested += null, filename, args);
args.Callback(true, downloadUrl, downloadPath);
coordinator.Verify(c => c.RequestReconfigurationLock(), Times.Once);
coordinator.Verify(c => c.ReleaseReconfigurationLock(), Times.Once);
messageBox.Verify(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.Is<MessageBoxIcon>(i => i == MessageBoxIcon.Error),
It.IsAny<IWindow>()), Times.Once);
runtime.Verify(r => r.RequestReconfiguration(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
[TestMethod]
public void MustNotFailIfDependencyIsNull()
{
context.Browser = null;
sut.Assume(ClientTask.DeregisterEvents);
}
}
}

View File

@@ -0,0 +1,212 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Client.Contracts;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.Communication.Contracts.Data;
using SafeExamBrowser.Communication.Contracts.Events;
using SafeExamBrowser.Communication.Contracts.Hosts;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Server.Contracts.Data;
using SafeExamBrowser.UserInterface.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
using SafeExamBrowser.UserInterface.Contracts.Windows;
using SafeExamBrowser.UserInterface.Contracts.Windows.Data;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class CommunicationResponsibilityTests
{
private Mock<IClientHost> clientHost;
private ClientContext context;
private Mock<ICoordinator> coordinator;
private Mock<IMessageBox> messageBox;
private Mock<IRuntimeProxy> runtimeProxy;
private Mock<Action> shutdown;
private Mock<ISplashScreen> splashScreen;
private Mock<IText> text;
private Mock<IUserInterfaceFactory> uiFactory;
private CommunicationResponsibility sut;
[TestInitialize]
public void Initialize()
{
var logger = new Mock<ILogger>();
clientHost = new Mock<IClientHost>();
context = new ClientContext();
coordinator = new Mock<ICoordinator>();
messageBox = new Mock<IMessageBox>();
runtimeProxy = new Mock<IRuntimeProxy>();
shutdown = new Mock<Action>();
splashScreen = new Mock<ISplashScreen>();
text = new Mock<IText>();
uiFactory = new Mock<IUserInterfaceFactory>();
context.ClientHost = clientHost.Object;
sut = new CommunicationResponsibility(
context,
coordinator.Object,
logger.Object,
messageBox.Object,
runtimeProxy.Object,
shutdown.Object,
splashScreen.Object,
text.Object,
uiFactory.Object);
sut.Assume(ClientTask.RegisterEvents);
}
[TestMethod]
public void Communication_MustCorrectlyHandleExamSelection()
{
var args = new ExamSelectionRequestEventArgs
{
Exams = new List<(string id, string lms, string name, string url)> { ("", "", "", "") },
RequestId = Guid.NewGuid()
};
var dialog = new Mock<IExamSelectionDialog>();
dialog.Setup(d => d.Show(It.IsAny<IWindow>())).Returns(new ExamSelectionDialogResult { Success = true });
uiFactory.Setup(f => f.CreateExamSelectionDialog(It.IsAny<IEnumerable<Exam>>())).Returns(dialog.Object);
clientHost.Raise(c => c.ExamSelectionRequested += null, args);
runtimeProxy.Verify(p => p.SubmitExamSelectionResult(It.Is<Guid>(g => g == args.RequestId), true, null), Times.Once);
uiFactory.Verify(f => f.CreateExamSelectionDialog(It.IsAny<IEnumerable<Exam>>()), Times.Once);
}
[TestMethod]
public void Communication_MustCorrectlyHandleMessageBoxRequest()
{
var args = new MessageBoxRequestEventArgs
{
Action = (int) MessageBoxAction.YesNo,
Icon = (int) MessageBoxIcon.Question,
Message = "Some question to be answered",
RequestId = Guid.NewGuid(),
Title = "A Title"
};
messageBox.Setup(m => m.Show(
It.Is<string>(s => s == args.Message),
It.Is<string>(s => s == args.Title),
It.Is<MessageBoxAction>(a => a == (MessageBoxAction) args.Action),
It.Is<MessageBoxIcon>(i => i == (MessageBoxIcon) args.Icon),
It.IsAny<IWindow>())).Returns(MessageBoxResult.No);
clientHost.Raise(c => c.MessageBoxRequested += null, args);
runtimeProxy.Verify(p => p.SubmitMessageBoxResult(
It.Is<Guid>(g => g == args.RequestId),
It.Is<int>(r => r == (int) MessageBoxResult.No)), Times.Once);
}
[TestMethod]
public void Communication_MustCorrectlyHandlePasswordRequest()
{
var args = new PasswordRequestEventArgs
{
Purpose = PasswordRequestPurpose.LocalSettings,
RequestId = Guid.NewGuid()
};
var dialog = new Mock<IPasswordDialog>();
var result = new PasswordDialogResult { Password = "blubb", Success = true };
dialog.Setup(d => d.Show(It.IsAny<IWindow>())).Returns(result);
uiFactory.Setup(f => f.CreatePasswordDialog(It.IsAny<string>(), It.IsAny<string>())).Returns(dialog.Object);
clientHost.Raise(c => c.PasswordRequested += null, args);
runtimeProxy.Verify(p => p.SubmitPassword(
It.Is<Guid>(g => g == args.RequestId),
It.Is<bool>(b => b == result.Success),
It.Is<string>(s => s == result.Password)), Times.Once);
}
[TestMethod]
public void Communication_MustCorrectlyHandleAbortedReconfiguration()
{
clientHost.Raise(c => c.ReconfigurationAborted += null);
splashScreen.Verify(s => s.Hide(), Times.AtLeastOnce);
}
[TestMethod]
public void Communication_MustInformUserAboutDeniedReconfiguration()
{
var args = new ReconfigurationEventArgs
{
ConfigurationPath = @"C:\Some\File\Path.seb"
};
clientHost.Raise(c => c.ReconfigurationDenied += null, args);
messageBox.Verify(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>()), Times.Once);
}
[TestMethod]
public void Communication_MustCorrectlyHandleServerCommunicationFailure()
{
var args = new ServerFailureActionRequestEventArgs { RequestId = Guid.NewGuid() };
var dialog = new Mock<IServerFailureDialog>();
dialog.Setup(d => d.Show(It.IsAny<IWindow>())).Returns(new ServerFailureDialogResult());
uiFactory.Setup(f => f.CreateServerFailureDialog(It.IsAny<string>(), It.IsAny<bool>())).Returns(dialog.Object);
clientHost.Raise(c => c.ServerFailureActionRequested += null, args);
runtimeProxy.Verify(r => r.SubmitServerFailureActionResult(It.Is<Guid>(g => g == args.RequestId), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<bool>()), Times.Once);
uiFactory.Verify(f => f.CreateServerFailureDialog(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
}
[TestMethod]
public void Communication_MustCorrectlyInitiateShutdown()
{
clientHost.Raise(c => c.Shutdown += null);
shutdown.Verify(s => s(), Times.Once);
}
[TestMethod]
public void Communication_MustShutdownOnLostConnection()
{
runtimeProxy.Raise(p => p.ConnectionLost += null);
messageBox.Verify(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>()), Times.Once);
shutdown.Verify(s => s(), Times.Once);
}
[TestMethod]
public void MustNotFailIfDependencyIsNull()
{
context.ClientHost = null;
sut.Assume(ClientTask.DeregisterEvents);
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.Configuration.Contracts.Integrity;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class IntegrityResponsibilityTests
{
private Mock<IText> text;
private Mock<IIntegrityModule> integrityModule;
[TestInitialize]
public void Initialize()
{
var context = new ClientContext();
var logger = new Mock<ILogger>();
var valid = true;
text = new Mock<IText>();
integrityModule = new Mock<IIntegrityModule>();
integrityModule.Setup(m => m.TryVerifySessionIntegrity(It.IsAny<string>(), It.IsAny<string>(), out valid)).Returns(true);
var sut = new IntegrityResponsibility(context, logger.Object, text.Object);
}
}
}

View File

@@ -0,0 +1,414 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Client.Contracts;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Configuration.Contracts.Cryptography;
using SafeExamBrowser.Core.Contracts.ResponsibilityModel;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Monitoring.Contracts.Applications;
using SafeExamBrowser.Monitoring.Contracts.Display;
using SafeExamBrowser.Monitoring.Contracts.System;
using SafeExamBrowser.Settings;
using SafeExamBrowser.Settings.Monitoring;
using SafeExamBrowser.Settings.UserInterface;
using SafeExamBrowser.UserInterface.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
using SafeExamBrowser.UserInterface.Contracts.Shell;
using SafeExamBrowser.UserInterface.Contracts.Windows;
using SafeExamBrowser.UserInterface.Contracts.Windows.Data;
using SafeExamBrowser.WindowsApi.Contracts;
using IWindow = SafeExamBrowser.UserInterface.Contracts.Windows.IWindow;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class MonitoringResponsibilityTests
{
private Mock<IActionCenter> actionCenter;
private Mock<IApplicationMonitor> applicationMonitor;
private ClientContext context;
private Mock<ICoordinator> coordinator;
private Mock<IDisplayMonitor> displayMonitor;
private Mock<IExplorerShell> explorerShell;
private Mock<IHashAlgorithm> hashAlgorithm;
private Mock<IMessageBox> messageBox;
private Mock<IRuntimeProxy> runtime;
private Mock<ISystemSentinel> sentinel;
private AppSettings settings;
private Mock<ITaskbar> taskbar;
private Mock<IText> text;
private Mock<IUserInterfaceFactory> uiFactory;
private MonitoringResponsibility sut;
[TestInitialize]
public void Initialize()
{
var logger = new Mock<ILogger>();
var responsibilities = new Mock<IResponsibilityCollection<ClientTask>>();
actionCenter = new Mock<IActionCenter>();
applicationMonitor = new Mock<IApplicationMonitor>();
context = new ClientContext();
coordinator = new Mock<ICoordinator>();
displayMonitor = new Mock<IDisplayMonitor>();
explorerShell = new Mock<IExplorerShell>();
hashAlgorithm = new Mock<IHashAlgorithm>();
messageBox = new Mock<IMessageBox>();
runtime = new Mock<IRuntimeProxy>();
sentinel = new Mock<ISystemSentinel>();
settings = new AppSettings();
taskbar = new Mock<ITaskbar>();
text = new Mock<IText>();
uiFactory = new Mock<IUserInterfaceFactory>();
context.HashAlgorithm = hashAlgorithm.Object;
context.MessageBox = messageBox.Object;
context.Responsibilities = responsibilities.Object;
context.Runtime = runtime.Object;
context.Settings = settings;
context.UserInterfaceFactory = uiFactory.Object;
sut = new MonitoringResponsibility(
actionCenter.Object,
applicationMonitor.Object,
context,
coordinator.Object,
displayMonitor.Object,
explorerShell.Object,
logger.Object,
sentinel.Object,
taskbar.Object,
text.Object);
sut.Assume(ClientTask.RegisterEvents);
sut.Assume(ClientTask.StartMonitoring);
}
[TestMethod]
public void ApplicationMonitor_MustCorrectlyHandleExplorerStartWithTaskbar()
{
var boundsActionCenter = 0;
var boundsTaskbar = 0;
var height = 30;
var order = 0;
var shell = 0;
var workingArea = 0;
settings.UserInterface.Taskbar.EnableTaskbar = true;
actionCenter.Setup(a => a.InitializeBounds()).Callback(() => boundsActionCenter = ++order);
explorerShell.Setup(e => e.Terminate()).Callback(() => shell = ++order);
displayMonitor.Setup(w => w.InitializePrimaryDisplay(It.Is<int>(h => h == height))).Callback(() => workingArea = ++order);
taskbar.Setup(t => t.GetAbsoluteHeight()).Returns(height);
taskbar.Setup(t => t.InitializeBounds()).Callback(() => boundsTaskbar = ++order);
applicationMonitor.Raise(a => a.ExplorerStarted += null);
actionCenter.Verify(a => a.InitializeBounds(), Times.Once);
explorerShell.Verify(e => e.Terminate(), Times.Once);
displayMonitor.Verify(d => d.InitializePrimaryDisplay(It.Is<int>(h => h == 0)), Times.Never);
displayMonitor.Verify(d => d.InitializePrimaryDisplay(It.Is<int>(h => h == height)), Times.Once);
taskbar.Verify(t => t.InitializeBounds(), Times.Once);
taskbar.Verify(t => t.GetAbsoluteHeight(), Times.Once);
Assert.IsTrue(shell == 1);
Assert.IsTrue(workingArea == 2);
Assert.IsTrue(boundsActionCenter == 3);
Assert.IsTrue(boundsTaskbar == 4);
}
[TestMethod]
public void ApplicationMonitor_MustCorrectlyHandleExplorerStartWithoutTaskbar()
{
var boundsActionCenter = 0;
var boundsTaskbar = 0;
var height = 30;
var order = 0;
var shell = 0;
var workingArea = 0;
settings.UserInterface.Taskbar.EnableTaskbar = false;
actionCenter.Setup(a => a.InitializeBounds()).Callback(() => boundsActionCenter = ++order);
explorerShell.Setup(e => e.Terminate()).Callback(() => shell = ++order);
displayMonitor.Setup(w => w.InitializePrimaryDisplay(It.Is<int>(h => h == 0))).Callback(() => workingArea = ++order);
taskbar.Setup(t => t.GetAbsoluteHeight()).Returns(height);
taskbar.Setup(t => t.InitializeBounds()).Callback(() => boundsTaskbar = ++order);
applicationMonitor.Raise(a => a.ExplorerStarted += null);
actionCenter.Verify(a => a.InitializeBounds(), Times.Once);
explorerShell.Verify(e => e.Terminate(), Times.Once);
displayMonitor.Verify(d => d.InitializePrimaryDisplay(It.Is<int>(h => h == 0)), Times.Once);
displayMonitor.Verify(d => d.InitializePrimaryDisplay(It.Is<int>(h => h == height)), Times.Never);
taskbar.Verify(t => t.InitializeBounds(), Times.Once);
taskbar.Verify(t => t.GetAbsoluteHeight(), Times.Never);
Assert.IsTrue(shell == 1);
Assert.IsTrue(workingArea == 2);
Assert.IsTrue(boundsActionCenter == 3);
Assert.IsTrue(boundsTaskbar == 4);
}
[TestMethod]
public void ApplicationMonitor_MustPermitApplicationIfChosenByUserAfterFailedTermination()
{
var lockScreen = new Mock<ILockScreen>();
var result = new LockScreenResult();
lockScreen.Setup(l => l.WaitForResult()).Returns(result);
runtime.Setup(p => p.RequestShutdown()).Returns(new CommunicationResult(true));
uiFactory
.Setup(f => f.CreateLockScreen(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<LockScreenOption>>(), It.IsAny<LockScreenSettings>()))
.Returns(lockScreen.Object)
.Callback<string, string, IEnumerable<LockScreenOption>, LockScreenSettings>((m, t, o, s) => result.OptionId = o.First().Id);
applicationMonitor.Raise(m => m.TerminationFailed += null, new List<RunningApplication>());
runtime.Verify(p => p.RequestShutdown(), Times.Never);
}
[TestMethod]
public void ApplicationMonitor_MustRequestShutdownIfChosenByUserAfterFailedTermination()
{
var lockScreen = new Mock<ILockScreen>();
var result = new LockScreenResult();
lockScreen.Setup(l => l.WaitForResult()).Returns(result);
runtime.Setup(p => p.RequestShutdown()).Returns(new CommunicationResult(true));
uiFactory
.Setup(f => f.CreateLockScreen(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<LockScreenOption>>(), It.IsAny<LockScreenSettings>()))
.Returns(lockScreen.Object)
.Callback<string, string, IEnumerable<LockScreenOption>, LockScreenSettings>((m, t, o, s) => result.OptionId = o.Last().Id);
applicationMonitor.Raise(m => m.TerminationFailed += null, new List<RunningApplication>());
runtime.Verify(p => p.RequestShutdown(), Times.Once);
}
[TestMethod]
public void ApplicationMonitor_MustShowLockScreenIfTerminationFailed()
{
var activator1 = new Mock<IActivator>();
var activator2 = new Mock<IActivator>();
var activator3 = new Mock<IActivator>();
var lockScreen = new Mock<ILockScreen>();
var result = new LockScreenResult();
var order = 0;
var pause = 0;
var show = 0;
var wait = 0;
var close = 0;
var resume = 0;
activator1.Setup(a => a.Pause()).Callback(() => pause = ++order);
activator1.Setup(a => a.Resume()).Callback(() => resume = ++order);
context.Activators.Add(activator1.Object);
context.Activators.Add(activator2.Object);
context.Activators.Add(activator3.Object);
lockScreen.Setup(l => l.Show()).Callback(() => show = ++order);
lockScreen.Setup(l => l.WaitForResult()).Callback(() => wait = ++order).Returns(result);
lockScreen.Setup(l => l.Close()).Callback(() => close = ++order);
uiFactory
.Setup(f => f.CreateLockScreen(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<LockScreenOption>>(), It.IsAny<LockScreenSettings>()))
.Returns(lockScreen.Object);
applicationMonitor.Raise(m => m.TerminationFailed += null, new List<RunningApplication>());
activator1.Verify(a => a.Pause(), Times.Once);
activator1.Verify(a => a.Resume(), Times.Once);
activator2.Verify(a => a.Pause(), Times.Once);
activator2.Verify(a => a.Resume(), Times.Once);
activator3.Verify(a => a.Pause(), Times.Once);
activator3.Verify(a => a.Resume(), Times.Once);
lockScreen.Verify(l => l.Show(), Times.Once);
lockScreen.Verify(l => l.WaitForResult(), Times.Once);
lockScreen.Verify(l => l.Close(), Times.Once);
Assert.IsTrue(pause == 1);
Assert.IsTrue(show == 2);
Assert.IsTrue(wait == 3);
Assert.IsTrue(close == 4);
Assert.IsTrue(resume == 5);
}
[TestMethod]
public void ApplicationMonitor_MustValidateQuitPasswordIfTerminationFailed()
{
var hash = "12345";
var lockScreen = new Mock<ILockScreen>();
var result = new LockScreenResult { Password = "test" };
var attempt = 0;
var correct = new Random().Next(1, 50);
var lockScreenResult = new Func<LockScreenResult>(() => ++attempt == correct ? result : new LockScreenResult());
context.Settings.Security.QuitPasswordHash = hash;
hashAlgorithm.Setup(a => a.GenerateHashFor(It.Is<string>(p => p == result.Password))).Returns(hash);
lockScreen.Setup(l => l.WaitForResult()).Returns(lockScreenResult);
uiFactory
.Setup(f => f.CreateLockScreen(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<LockScreenOption>>(), It.IsAny<LockScreenSettings>()))
.Returns(lockScreen.Object);
applicationMonitor.Raise(m => m.TerminationFailed += null, new List<RunningApplication>());
hashAlgorithm.Verify(a => a.GenerateHashFor(It.Is<string>(p => p == result.Password)), Times.Once);
hashAlgorithm.Verify(a => a.GenerateHashFor(It.Is<string>(p => p != result.Password)), Times.Exactly(attempt - 1));
messageBox.Verify(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.Is<IWindow>(w => w == lockScreen.Object)), Times.Exactly(attempt - 1));
}
[TestMethod]
public void DisplayMonitor_MustCorrectlyHandleDisplayChangeWithTaskbar()
{
var boundsActionCenter = 0;
var boundsTaskbar = 0;
var height = 25;
var order = 0;
var workingArea = 0;
settings.UserInterface.Taskbar.EnableTaskbar = true;
actionCenter.Setup(t => t.InitializeBounds()).Callback(() => boundsActionCenter = ++order);
displayMonitor.Setup(m => m.InitializePrimaryDisplay(It.Is<int>(h => h == height))).Callback(() => workingArea = ++order);
displayMonitor.Setup(m => m.ValidateConfiguration(It.IsAny<DisplaySettings>())).Returns(new ValidationResult { IsAllowed = true });
taskbar.Setup(t => t.GetAbsoluteHeight()).Returns(height);
taskbar.Setup(t => t.InitializeBounds()).Callback(() => boundsTaskbar = ++order);
displayMonitor.Raise(d => d.DisplayChanged += null);
actionCenter.Verify(a => a.InitializeBounds(), Times.Once);
displayMonitor.Verify(d => d.InitializePrimaryDisplay(It.Is<int>(h => h == 0)), Times.Never);
displayMonitor.Verify(d => d.InitializePrimaryDisplay(It.Is<int>(h => h == height)), Times.Once);
taskbar.Verify(t => t.GetAbsoluteHeight(), Times.Once);
taskbar.Verify(t => t.InitializeBounds(), Times.Once);
Assert.IsTrue(workingArea == 1);
Assert.IsTrue(boundsActionCenter == 2);
Assert.IsTrue(boundsTaskbar == 3);
}
[TestMethod]
public void DisplayMonitor_MustCorrectlyHandleDisplayChangeWithoutTaskbar()
{
var boundsActionCenter = 0;
var boundsTaskbar = 0;
var height = 25;
var order = 0;
var workingArea = 0;
settings.UserInterface.Taskbar.EnableTaskbar = false;
actionCenter.Setup(t => t.InitializeBounds()).Callback(() => boundsActionCenter = ++order);
displayMonitor.Setup(w => w.InitializePrimaryDisplay(It.Is<int>(h => h == 0))).Callback(() => workingArea = ++order);
displayMonitor.Setup(m => m.ValidateConfiguration(It.IsAny<DisplaySettings>())).Returns(new ValidationResult { IsAllowed = true });
taskbar.Setup(t => t.GetAbsoluteHeight()).Returns(height);
taskbar.Setup(t => t.InitializeBounds()).Callback(() => boundsTaskbar = ++order);
displayMonitor.Raise(d => d.DisplayChanged += null);
actionCenter.Verify(a => a.InitializeBounds(), Times.Once);
displayMonitor.Verify(d => d.InitializePrimaryDisplay(It.Is<int>(h => h == 0)), Times.Once);
displayMonitor.Verify(d => d.InitializePrimaryDisplay(It.Is<int>(h => h == height)), Times.Never);
taskbar.Verify(t => t.GetAbsoluteHeight(), Times.Never);
taskbar.Verify(t => t.InitializeBounds(), Times.Once);
Assert.IsTrue(workingArea == 1);
Assert.IsTrue(boundsActionCenter == 2);
Assert.IsTrue(boundsTaskbar == 3);
}
[TestMethod]
public void DisplayMonitor_MustShowLockScreenOnDisplayChange()
{
var lockScreen = new Mock<ILockScreen>();
displayMonitor.Setup(m => m.ValidateConfiguration(It.IsAny<DisplaySettings>())).Returns(new ValidationResult { IsAllowed = false });
lockScreen.Setup(l => l.WaitForResult()).Returns(new LockScreenResult());
uiFactory
.Setup(f => f.CreateLockScreen(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<LockScreenOption>>(), It.IsAny<LockScreenSettings>()))
.Returns(lockScreen.Object);
displayMonitor.Raise(d => d.DisplayChanged += null);
lockScreen.Verify(l => l.Show(), Times.Once);
}
[TestMethod]
public void SystemMonitor_MustShowLockScreenOnSessionSwitch()
{
var lockScreen = new Mock<ILockScreen>();
coordinator.Setup(c => c.RequestSessionLock()).Returns(true);
lockScreen.Setup(l => l.WaitForResult()).Returns(new LockScreenResult());
settings.Service.IgnoreService = true;
uiFactory
.Setup(f => f.CreateLockScreen(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<LockScreenOption>>(), It.IsAny<LockScreenSettings>()))
.Returns(lockScreen.Object);
sentinel.Raise(s => s.SessionChanged += null);
coordinator.Verify(c => c.RequestSessionLock(), Times.Once);
coordinator.Verify(c => c.ReleaseSessionLock(), Times.Once);
lockScreen.Verify(l => l.Show(), Times.Once);
}
[TestMethod]
public void SystemMonitor_MustTerminateIfRequestedByUser()
{
var lockScreen = new Mock<ILockScreen>();
var result = new LockScreenResult();
coordinator.Setup(c => c.RequestSessionLock()).Returns(true);
lockScreen.Setup(l => l.WaitForResult()).Returns(result);
runtime.Setup(r => r.RequestShutdown()).Returns(new CommunicationResult(true));
settings.Service.IgnoreService = true;
uiFactory
.Setup(f => f.CreateLockScreen(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<LockScreenOption>>(), It.IsAny<LockScreenSettings>()))
.Callback(new Action<string, string, IEnumerable<LockScreenOption>, LockScreenSettings>((message, title, options, settings) => result.OptionId = options.Last().Id))
.Returns(lockScreen.Object);
sentinel.Raise(s => s.SessionChanged += null);
coordinator.Verify(c => c.RequestSessionLock(), Times.Once);
coordinator.Verify(c => c.ReleaseSessionLock(), Times.Once);
lockScreen.Verify(l => l.Show(), Times.Once);
runtime.Verify(p => p.RequestShutdown(), Times.Once);
}
[TestMethod]
public void SystemMonitor_MustDoNothingIfSessionSwitchAllowed()
{
var lockScreen = new Mock<ILockScreen>();
settings.Service.IgnoreService = false;
settings.Service.DisableUserLock = false;
settings.Service.DisableUserSwitch = false;
lockScreen.Setup(l => l.WaitForResult()).Returns(new LockScreenResult());
uiFactory
.Setup(f => f.CreateLockScreen(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<LockScreenOption>>(), It.IsAny<LockScreenSettings>()))
.Returns(lockScreen.Object);
sentinel.Raise(s => s.SessionChanged += null);
lockScreen.Verify(l => l.Show(), Times.Never);
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.SystemComponents.Contracts.Network;
using SafeExamBrowser.UserInterface.Contracts;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class NetworkResponsibilityTests
{
private Mock<INetworkAdapter> networkAdapter;
private Mock<IText> text;
private Mock<IUserInterfaceFactory> uiFactory;
[TestInitialize]
public void Initialize()
{
var context = new ClientContext();
var logger = new Mock<ILogger>();
networkAdapter = new Mock<INetworkAdapter>();
text = new Mock<IText>();
uiFactory = new Mock<IUserInterfaceFactory>();
var sut = new NetworkResponsibility(context, logger.Object, networkAdapter.Object, text.Object, uiFactory.Object);
}
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.UserInterface.Contracts;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class ProctoringResponsibilityTests
{
private ClientContext context;
private Mock<IUserInterfaceFactory> uiFactory;
private ProctoringResponsibility sut;
[TestInitialize]
public void Initialize()
{
var logger = new Mock<ILogger>();
context = new ClientContext();
logger = new Mock<ILogger>();
uiFactory = new Mock<IUserInterfaceFactory>();
sut = new ProctoringResponsibility(context, logger.Object, uiFactory.Object);
}
[TestMethod]
public void MustNotFailIfDependencyIsNull()
{
context.Proctoring = null;
sut.Assume(ClientTask.PrepareShutdown_Wave1);
}
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Client.Contracts;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Core.Contracts.ResponsibilityModel;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Server.Contracts;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class ServerResponsibilityTests
{
private ClientContext context;
private Mock<ICoordinator> coordinator;
private Mock<IRuntimeProxy> runtime;
private Mock<IServerProxy> server;
private Mock<IText> text;
private ServerResponsibility sut;
[TestInitialize]
public void Initialize()
{
var logger = new Mock<ILogger>();
var responsibilities = new Mock<IResponsibilityCollection<ClientTask>>();
context = new ClientContext();
coordinator = new Mock<ICoordinator>();
runtime = new Mock<IRuntimeProxy>();
server = new Mock<IServerProxy>();
text = new Mock<IText>();
context.Responsibilities = responsibilities.Object;
context.Runtime = runtime.Object;
context.Server = server.Object;
sut = new ServerResponsibility(context, coordinator.Object, logger.Object, text.Object);
sut.Assume(ClientTask.RegisterEvents);
}
[TestMethod]
public void Server_MustInitiateShutdownOnEvent()
{
runtime.Setup(r => r.RequestShutdown()).Returns(new CommunicationResult(true));
server.Raise(s => s.TerminationRequested += null);
runtime.Verify(p => p.RequestShutdown(), Times.Once);
}
[TestMethod]
public void MustNotFailIfDependencyIsNull()
{
context.Server = null;
sut.Assume(ClientTask.DeregisterEvents);
}
}
}

View File

@@ -0,0 +1,284 @@
/*
* Copyright (c) 2025 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SafeExamBrowser.Client.Responsibilities;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Configuration.Contracts.Cryptography;
using SafeExamBrowser.Core.Contracts.ResponsibilityModel;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Settings;
using SafeExamBrowser.UserInterface.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
using SafeExamBrowser.UserInterface.Contracts.Shell;
using SafeExamBrowser.UserInterface.Contracts.Windows;
using SafeExamBrowser.UserInterface.Contracts.Windows.Data;
namespace SafeExamBrowser.Client.UnitTests.Responsibilities
{
[TestClass]
public class ShellResponsibilityTests
{
private Mock<IActionCenter> actionCenter;
private ClientContext context;
private Mock<IHashAlgorithm> hashAlgorithm;
private Mock<IMessageBox> messageBox;
private Mock<IRuntimeProxy> runtime;
private AppSettings settings;
private Mock<ITaskbar> taskbar;
private Mock<IUserInterfaceFactory> uiFactory;
private ShellResponsibility sut;
[TestInitialize]
public void Initialize()
{
var logger = new Mock<ILogger>();
var responsibilities = new Mock<IResponsibilityCollection<ClientTask>>();
actionCenter = new Mock<IActionCenter>();
context = new ClientContext();
hashAlgorithm = new Mock<IHashAlgorithm>();
messageBox = new Mock<IMessageBox>();
runtime = new Mock<IRuntimeProxy>();
settings = new AppSettings();
taskbar = new Mock<ITaskbar>();
uiFactory = new Mock<IUserInterfaceFactory>();
context.MessageBox = messageBox.Object;
context.Responsibilities = responsibilities.Object;
context.Runtime = runtime.Object;
context.Settings = settings;
sut = new ShellResponsibility(
actionCenter.Object,
context,
hashAlgorithm.Object,
logger.Object,
messageBox.Object,
taskbar.Object,
uiFactory.Object);
sut.Assume(ClientTask.RegisterEvents);
}
[TestMethod]
public void Shutdown_MustAskUserToConfirm()
{
var args = new System.ComponentModel.CancelEventArgs();
messageBox.Setup(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>())).Returns(MessageBoxResult.Yes);
runtime.Setup(r => r.RequestShutdown()).Returns(new CommunicationResult(true));
taskbar.Raise(t => t.QuitButtonClicked += null, args as object);
runtime.Verify(p => p.RequestShutdown(), Times.Once);
Assert.IsFalse(args.Cancel);
}
[TestMethod]
public void Shutdown_MustNotInitiateIfNotWishedByUser()
{
var args = new System.ComponentModel.CancelEventArgs();
messageBox.Setup(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>())).Returns(MessageBoxResult.No);
taskbar.Raise(t => t.QuitButtonClicked += null, args as object);
runtime.Verify(p => p.RequestShutdown(), Times.Never);
Assert.IsTrue(args.Cancel);
}
[TestMethod]
public void Shutdown_MustCloseActionCenterAndTaskbarIfEnabled()
{
settings.UserInterface.ActionCenter.EnableActionCenter = true;
settings.UserInterface.Taskbar.EnableTaskbar = true;
sut.Assume(ClientTask.CloseShell);
actionCenter.Verify(a => a.Close(), Times.Once);
taskbar.Verify(o => o.Close(), Times.Once);
}
[TestMethod]
public void Shutdown_MustNotCloseActionCenterAndTaskbarIfNotEnabled()
{
settings.UserInterface.ActionCenter.EnableActionCenter = false;
settings.UserInterface.Taskbar.EnableTaskbar = false;
sut.Assume(ClientTask.CloseShell);
actionCenter.Verify(a => a.Close(), Times.Never);
taskbar.Verify(o => o.Close(), Times.Never);
}
[TestMethod]
public void Shutdown_MustShowErrorMessageOnCommunicationFailure()
{
var args = new System.ComponentModel.CancelEventArgs();
messageBox.Setup(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>())).Returns(MessageBoxResult.Yes);
runtime.Setup(r => r.RequestShutdown()).Returns(new CommunicationResult(false));
taskbar.Raise(t => t.QuitButtonClicked += null, args as object);
messageBox.Verify(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.Is<MessageBoxIcon>(i => i == MessageBoxIcon.Error),
It.IsAny<IWindow>()), Times.Once);
runtime.Verify(p => p.RequestShutdown(), Times.Once);
}
[TestMethod]
public void Shutdown_MustAskUserForQuitPassword()
{
var args = new System.ComponentModel.CancelEventArgs();
var dialog = new Mock<IPasswordDialog>();
var dialogResult = new PasswordDialogResult { Password = "blobb", Success = true };
settings.Security.QuitPasswordHash = "1234";
dialog.Setup(d => d.Show(It.IsAny<IWindow>())).Returns(dialogResult);
hashAlgorithm.Setup(h => h.GenerateHashFor(It.Is<string>(s => s == dialogResult.Password))).Returns(settings.Security.QuitPasswordHash);
runtime.Setup(r => r.RequestShutdown()).Returns(new CommunicationResult(true));
uiFactory.Setup(u => u.CreatePasswordDialog(It.IsAny<TextKey>(), It.IsAny<TextKey>())).Returns(dialog.Object);
taskbar.Raise(t => t.QuitButtonClicked += null, args as object);
uiFactory.Verify(u => u.CreatePasswordDialog(It.IsAny<TextKey>(), It.IsAny<TextKey>()), Times.Once);
runtime.Verify(p => p.RequestShutdown(), Times.Once);
Assert.IsFalse(args.Cancel);
}
[TestMethod]
public void Shutdown_MustAbortAskingUserForQuitPassword()
{
var args = new System.ComponentModel.CancelEventArgs();
var dialog = new Mock<IPasswordDialog>();
var dialogResult = new PasswordDialogResult { Success = false };
settings.Security.QuitPasswordHash = "1234";
dialog.Setup(d => d.Show(It.IsAny<IWindow>())).Returns(dialogResult);
runtime.Setup(r => r.RequestShutdown()).Returns(new CommunicationResult(true));
uiFactory.Setup(u => u.CreatePasswordDialog(It.IsAny<TextKey>(), It.IsAny<TextKey>())).Returns(dialog.Object);
taskbar.Raise(t => t.QuitButtonClicked += null, args as object);
uiFactory.Verify(u => u.CreatePasswordDialog(It.IsAny<TextKey>(), It.IsAny<TextKey>()), Times.Once);
runtime.Verify(p => p.RequestShutdown(), Times.Never);
Assert.IsTrue(args.Cancel);
}
[TestMethod]
public void Shutdown_MustNotInitiateIfQuitPasswordIncorrect()
{
var args = new System.ComponentModel.CancelEventArgs();
var dialog = new Mock<IPasswordDialog>();
var dialogResult = new PasswordDialogResult { Password = "blobb", Success = true };
settings.Security.QuitPasswordHash = "1234";
dialog.Setup(d => d.Show(It.IsAny<IWindow>())).Returns(dialogResult);
hashAlgorithm.Setup(h => h.GenerateHashFor(It.IsAny<string>())).Returns("9876");
uiFactory.Setup(u => u.CreatePasswordDialog(It.IsAny<TextKey>(), It.IsAny<TextKey>())).Returns(dialog.Object);
taskbar.Raise(t => t.QuitButtonClicked += null, args as object);
messageBox.Verify(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.Is<MessageBoxIcon>(i => i == MessageBoxIcon.Warning),
It.IsAny<IWindow>()), Times.Once);
uiFactory.Verify(u => u.CreatePasswordDialog(It.IsAny<TextKey>(), It.IsAny<TextKey>()), Times.Once);
runtime.Verify(p => p.RequestShutdown(), Times.Never);
Assert.IsTrue(args.Cancel);
}
[TestMethod]
public void Startup_MustCorrectlyShowTaskbar()
{
settings.UserInterface.Taskbar.EnableTaskbar = true;
sut.Assume(ClientTask.ShowShell);
taskbar.Verify(t => t.Show(), Times.Once);
taskbar.Reset();
settings.UserInterface.Taskbar.EnableTaskbar = false;
sut.Assume(ClientTask.ShowShell);
taskbar.Verify(t => t.Show(), Times.Never);
}
[TestMethod]
public void Startup_MustCorrectlyShowActionCenter()
{
settings.UserInterface.ActionCenter.EnableActionCenter = true;
sut.Assume(ClientTask.ShowShell);
actionCenter.Verify(t => t.Promote(), Times.Once);
actionCenter.Verify(t => t.Show(), Times.Never);
actionCenter.Reset();
settings.UserInterface.ActionCenter.EnableActionCenter = false;
sut.Assume(ClientTask.ShowShell);
actionCenter.Verify(t => t.Promote(), Times.Never);
actionCenter.Verify(t => t.Show(), Times.Never);
}
[TestMethod]
public void TerminationActivator_MustCorrectlyInitiateShutdown()
{
var order = 0;
var pause = 0;
var resume = 0;
var terminationActivator = new Mock<ITerminationActivator>();
context.Activators.Add(terminationActivator.Object);
messageBox.Setup(m => m.Show(
It.IsAny<TextKey>(),
It.IsAny<TextKey>(),
It.IsAny<MessageBoxAction>(),
It.IsAny<MessageBoxIcon>(),
It.IsAny<IWindow>())).Returns(MessageBoxResult.Yes);
runtime.Setup(r => r.RequestShutdown()).Returns(new CommunicationResult(true));
terminationActivator.Setup(t => t.Pause()).Callback(() => pause = ++order);
terminationActivator.Setup(t => t.Resume()).Callback(() => resume = ++order);
sut.Assume(ClientTask.RegisterEvents);
terminationActivator.Raise(t => t.Activated += null);
Assert.AreEqual(1, pause);
Assert.AreEqual(2, resume);
terminationActivator.Verify(t => t.Pause(), Times.Once);
terminationActivator.Verify(t => t.Resume(), Times.Once);
runtime.Verify(p => p.RequestShutdown(), Times.Once);
}
}
}