[tests] Clean up Xamarin.MacDev.Tasks.Tests. (#9975)

* Remove a lot of dead code.
* Use TestBase.CreateTask<T> to create tasks (and set required properties for all
  tasks) instead of instantiating tasks directly. This required subclassing TestBase
  in a few places, as well as making a few helper methods instance methods instead
  of static methods.
* Bump to net472.
* A few other misc simplifications.
This commit is contained in:
Rolf Bjarne Kvinge 2020-10-28 08:13:18 +01:00 коммит произвёл GitHub
Родитель c72b320561
Коммит 9cf78cf399
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
10 изменённых файлов: 72 добавлений и 747 удалений

Просмотреть файл

@ -226,7 +226,7 @@ test-macdev-tests: verify-system-vsmac-xcode-match
test-macdev-tasks: verify-system-vsmac-xcode-match
$(SYSTEM_MSBUILD) $(TOP)/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj /p:Configuration=Debug /r
cd $(TOP)/tests/msbuild/Xamarin.MacDev.Tasks.Tests && $(SYSTEM_XIBUILD) -t -- $(abspath $(TOP)/tools/nunit3-console-3.11.1) $(abspath $(TOP)/tests/msbuild/Xamarin.MacDev.Tasks.Tests/bin/Debug/net461/Xamarin.MacDev.Tasks.Tests.dll) "--result=$(abspath $(CURDIR)/TestResults_Xamarin.MacDev.Tasks.Tests.xml);format=nunit2" -labels=Before $(TEST_FIXTURE)
cd $(TOP)/tests/msbuild/Xamarin.MacDev.Tasks.Tests && $(SYSTEM_XIBUILD) -t -- $(abspath $(TOP)/tools/nunit3-console-3.11.1) $(abspath $(TOP)/tests/msbuild/Xamarin.MacDev.Tasks.Tests/bin/Debug/net472/Xamarin.MacDev.Tasks.Tests.dll) "--result=$(abspath $(CURDIR)/TestResults_Xamarin.MacDev.Tasks.Tests.xml)" -labels=Before $(TEST_FIXTURE)
test-install-sources:
$(SYSTEM_XIBUILD) -- $(TOP)/tools/install-source/InstallSourcesTests/InstallSourcesTests.csproj

Просмотреть файл

@ -60,13 +60,6 @@ namespace Xamarin.iOS.Tasks
Assert.AreEqual ("Z8CSQKJE7R.com.xamarin.MySingleView", compiled.GetUbiquityKeyValueStore (), "#6");
Assert.AreEqual ("32UV7A8CDE.com.xamarin.MySingleView", compiled.GetKeychainAccessGroups ().ToStringArray ().First (), "#7");
}
public override void Teardown ()
{
base.Teardown ();
CleanUp ();
}
}
}

Просмотреть файл

@ -56,11 +56,6 @@ namespace Xamarin.iOS.Tasks
CompiledPlist = PDictionary.FromFile (Task.CompiledAppManifest.ItemSpec);
}
public override void Teardown ()
{
base.Teardown ();
}
#region General tests
[Test]
public void PlistMissing ()

Просмотреть файл

@ -9,16 +9,15 @@ using Microsoft.Build.Utilities;
using NUnit.Framework;
using Xamarin.MacDev;
using Xamarin.MacDev.Tasks;
using Xamarin.Tests;
using Xamarin.Utils;
namespace Xamarin.iOS.Tasks
{
[TestFixture]
public class IBToolTaskTests
public class IBToolTaskTests : TestBase
{
static IBTool CreateIBToolTask (ApplePlatform framework, string projectDir, string intermediateOutputPath)
IBTool CreateIBToolTask (ApplePlatform framework, string projectDir, string intermediateOutputPath)
{
var interfaceDefinitions = new List<ITaskItem> ();
var sdk = IPhoneSdks.GetSdk (framework);
@ -46,21 +45,20 @@ namespace Xamarin.iOS.Tasks
foreach (var item in Directory.EnumerateFiles (projectDir, "*.xib", SearchOption.AllDirectories))
interfaceDefinitions.Add (new TaskItem (item));
return new IBTool {
AppManifest = new TaskItem (Path.Combine (projectDir, "Info.plist")),
InterfaceDefinitions = interfaceDefinitions.ToArray (),
IntermediateOutputPath = intermediateOutputPath,
BuildEngine = new TestEngine (),
MinimumOSVersion = PDictionary.FromFile (Path.Combine (projectDir, "Info.plist")).GetMinimumOSVersion (),
ResourcePrefix = "Resources",
ProjectDir = projectDir,
SdkDevPath = Configuration.xcode_root,
SdkPlatform = platform,
SdkVersion = version.ToString (),
SdkUsrPath = usr,
SdkBinPath = bin,
SdkRoot = root,
};
var task = CreateTask<IBTool> ();
task.AppManifest = new TaskItem (Path.Combine (projectDir, "Info.plist"));
task.InterfaceDefinitions = interfaceDefinitions.ToArray ();
task.IntermediateOutputPath = intermediateOutputPath;
task.MinimumOSVersion = PDictionary.FromFile (Path.Combine (projectDir, "Info.plist")).GetMinimumOSVersion ();
task.ResourcePrefix = "Resources";
task.ProjectDir = projectDir;
task.SdkDevPath = Configuration.xcode_root;
task.SdkPlatform = platform;
task.SdkVersion = version.ToString ();
task.SdkUsrPath = usr;
task.SdkBinPath = bin;
task.SdkRoot = root;
return task;
}
[Test]
@ -171,7 +169,7 @@ namespace Xamarin.iOS.Tasks
Assert.That (unexpectedResource, Is.Empty, "No extra resources");
}
static IBTool CreateIBToolTask (ApplePlatform framework, string projectDir, string intermediateOutputPath, params string[] fileNames)
IBTool CreateIBToolTask (ApplePlatform framework, string projectDir, string intermediateOutputPath, params string[] fileNames)
{
var ibtool = CreateIBToolTask (framework, projectDir, intermediateOutputPath);
var interfaceDefinitions = new List<ITaskItem> ();
@ -184,7 +182,7 @@ namespace Xamarin.iOS.Tasks
return ibtool;
}
static void TestGenericAndDeviceSpecificXibsGeneric (params string [] fileNames)
void TestGenericAndDeviceSpecificXibsGeneric (params string[] fileNames)
{
var tmp = Cache.CreateTemporaryDirectory ("advanced-ibtool");
IBTool ibtool;

Просмотреть файл

@ -8,7 +8,7 @@ using Xamarin.MacDev.Tasks;
namespace Xamarin.iOS.Tasks
{
[TestFixture]
public class PropertyListEditorTaskTests
public class PropertyListEditorTaskTests : TestBase
{
static void CheckArray (PArray array, PArray expected)
{
@ -62,16 +62,14 @@ namespace Xamarin.iOS.Tasks
}
}
static void TestExecuteTask (PDictionary input, PropertyListEditorAction action, string entry, string type, string value, PObject expected)
void TestExecuteTask (PDictionary input, PropertyListEditorAction action, string entry, string type, string value, PObject expected)
{
var task = new PropertyListEditor {
PropertyList = Path.Combine (Cache.CreateTemporaryDirectory (), "propertyList.plist"),
BuildEngine = new TestEngine (),
Action = action.ToString (),
Entry = entry,
Type = type,
Value = value
};
var task = CreateTask<PropertyListEditor> ();
task.PropertyList = Path.Combine (Cache.CreateTemporaryDirectory (), "propertyList.plist");
task.Action = action.ToString ();
task.Entry = entry;
task.Type = type;
task.Value = value;
input.Save (task.PropertyList);
if (expected == null) {

Просмотреть файл

@ -1,12 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using Microsoft.Build.Framework;
using NUnit.Framework;
using Microsoft.Build.Utilities;
namespace Xamarin.iOS.Tasks
{
@ -34,16 +28,11 @@ namespace Xamarin.iOS.Tasks
ErrorEvents = new List<BuildErrorEventArgs> ();
MessageEvents = new List<BuildMessageEventArgs> ();
WarningsEvents = new List<BuildWarningEventArgs> ();
eventSource.CustomEventRaised += (object sender, CustomBuildEventArgs e) => CustomEvents.Add (e);
eventSource.ErrorRaised += (object sender, BuildErrorEventArgs e) => ErrorEvents.Add (e);
eventSource.MessageRaised += (object sender, BuildMessageEventArgs e) => MessageEvents.Add (e);
eventSource.WarningRaised += (object sender, BuildWarningEventArgs e) => WarningsEvents.Add (e);
}
public void Shutdown ()
{
throw new NotImplementedException ();
Clear ();
}
public string Parameters {
@ -62,159 +51,4 @@ namespace Xamarin.iOS.Tasks
WarningsEvents.Clear ();
}
}
// Stolen from xbuild.
class ConsoleReportPrinter
{
string prefix, postfix;
bool color_supported;
TextWriter writer;
string [] colorPrefixes;
public ConsoleReportPrinter ()
: this (Console.Out)
{
}
public ConsoleReportPrinter (TextWriter writer)
{
this.writer = writer;
string term = Environment.GetEnvironmentVariable ("TERM");
bool xterm_colors = false;
color_supported = false;
switch (term){
case "xterm":
case "rxvt":
case "rxvt-unicode":
if (Environment.GetEnvironmentVariable ("COLORTERM") != null){
xterm_colors = true;
}
break;
case "xterm-color":
case "xterm-256color":
xterm_colors = true;
break;
}
if (!xterm_colors)
return;
if (!(UnixUtils.isatty (1) && UnixUtils.isatty (2)))
return;
color_supported = true;
PopulateColorPrefixes ();
postfix = "\x001b[0m";
}
void PopulateColorPrefixes ()
{
colorPrefixes = new string [16];
colorPrefixes [(int)ConsoleColor.Black] = GetForeground ("black");
colorPrefixes [(int)ConsoleColor.DarkBlue] = GetForeground ("blue");
colorPrefixes [(int)ConsoleColor.DarkGreen] = GetForeground ("green");
colorPrefixes [(int)ConsoleColor.DarkCyan] = GetForeground ("cyan");
colorPrefixes [(int)ConsoleColor.DarkRed] = GetForeground ("red");
colorPrefixes [(int)ConsoleColor.DarkMagenta] = GetForeground ("magenta");
colorPrefixes [(int)ConsoleColor.DarkYellow] = GetForeground ("yellow");
colorPrefixes [(int)ConsoleColor.DarkGray] = GetForeground ("grey");
colorPrefixes [(int)ConsoleColor.Gray] = GetForeground ("brightgrey");
colorPrefixes [(int)ConsoleColor.Blue] = GetForeground ("brightblue");
colorPrefixes [(int)ConsoleColor.Green] = GetForeground ("brightgreen");
colorPrefixes [(int)ConsoleColor.Cyan] = GetForeground ("brightcyan");
colorPrefixes [(int)ConsoleColor.Red] = GetForeground ("brightred");
colorPrefixes [(int)ConsoleColor.Magenta] = GetForeground ("brightmagenta");
colorPrefixes [(int)ConsoleColor.Yellow] = GetForeground ("brightyellow");
colorPrefixes [(int)ConsoleColor.White] = GetForeground ("brightwhite");
}
public void SetForeground (ConsoleColor color)
{
if (color_supported)
prefix = colorPrefixes [(int)color];
}
public void ResetColor ()
{
prefix = "\x001b[0m";
}
static int NameToCode (string s)
{
switch (s) {
case "black":
return 0;
case "red":
return 1;
case "green":
return 2;
case "yellow":
return 3;
case "blue":
return 4;
case "magenta":
return 5;
case "cyan":
return 6;
case "grey":
case "white":
return 7;
}
return 7;
}
//
// maps a color name to its xterm color code
//
static string GetForeground (string s)
{
string highcode;
if (s.StartsWith ("bright")) {
highcode = "1;";
s = s.Substring (6);
} else
highcode = "";
return "\x001b[" + highcode + (30 + NameToCode (s)).ToString () + "m";
}
static string GetBackground (string s)
{
return "\x001b[" + (40 + NameToCode (s)).ToString () + "m";
}
string FormatText (string txt)
{
if (prefix != null && color_supported)
return prefix + txt + postfix;
return txt;
}
public void Print (string message)
{
writer.Write (FormatText (message));
}
}
class UnixUtils {
[System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
extern static int _isatty (int fd);
public static bool isatty (int fd)
{
try {
return _isatty (fd) == 1;
} catch {
return false;
}
}
}
}

Просмотреть файл

@ -1,320 +1,54 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Utilities;
using NUnit.Framework;
using Xamarin.MacDev;
using Xamarin.Tests;
using Xamarin.Utils;
namespace Xamarin.iOS.Tasks
{
public enum ExecutionMode {
InProcess,
MSBuild,
DotNet,
}
public abstract class TestBase
{
protected static class TargetName
{
public static string Build = "Build";
public static string Clean = "Clean";
public static string CollectBundleResources = "_CollectBundleResources";
public static string CompileImageAssets = "_CompileImageAssets";
public static string CompileInterfaceDefinitions = "_CompileInterfaceDefinitions";
public static string CopyResourcesToBundle = "_CopyResourcesToBundle";
public static string DetectAppManifest = "_DetectAppManifest";
public static string GenerateBundleName = "_GenerateBundleName";
public static string PackLibraryResources = "_PackLibraryResources";
public static string ResolveReferences = "ResolveReferences";
}
protected static string GetTestDirectory (string mode = null, ExecutionMode? executionMode = null)
{
var assembly_path = Assembly.GetExecutingAssembly ().Location;
if (string.IsNullOrEmpty (mode)) {
if (assembly_path.Contains ("netstandard2.0"))
mode = "netstandard2.0";
else if (assembly_path.Contains ("net461"))
mode = "net461";
else
mode = "unknown";
}
var rv = Configuration.CloneTestDirectory (Configuration.TestProjectsDirectory, mode);
if (executionMode == ExecutionMode.DotNet)
Configuration.CopyDotNetSupportingFiles (rv);
return rv;
}
public string [] ExpectedAppFiles = { };
public string [] UnexpectedAppFiles = { "monotouch.dll" };
public string[] GetCoreAppFiles (string platform, string config, string managedExe, string nativeExe)
{
var coreFiles = new List<string> ();
if (TargetFrameworkIdentifier == "Xamarin.WatchOS") {
coreFiles.Add ("Xamarin.WatchOS.dll");
if (config == "Debug")
coreFiles.Add ("Xamarin.WatchOS.pdb");
} else if (TargetFrameworkIdentifier == "Xamarin.TVOS") {
coreFiles.Add ("Xamarin.TVOS.dll");
if (config == "Debug")
coreFiles.Add ("Xamarin.TVOS.pdb");
} else {
coreFiles.Add ("Xamarin.iOS.dll");
if (config == "Debug")
coreFiles.Add ("Xamarin.iOS.pdb");
}
coreFiles.Add ("mscorlib.dll");
if (config == "Debug")
coreFiles.Add ("mscorlib.pdb");
coreFiles.Add (managedExe);
if (config == "Debug")
coreFiles.Add (Path.ChangeExtension (managedExe, ".pdb"));
coreFiles.Add (nativeExe);
return coreFiles.ToArray ();
}
public Logger Logger {
get; set;
}
TestEngine engine;
public TestEngine Engine {
get; private set;
}
public Project LibraryProject {
get; private set;
}
public ProjectInstance LibraryProjectInstance {
get; set;
}
public Project MonoTouchProject {
get; private set;
}
public ProjectInstance MonoTouchProjectInstance {
get; set;
}
public string LibraryProjectBinPath;
public string LibraryProjectObjPath;
public string LibraryProjectPath;
public string LibraryProjectCSProjPath;
public string MonoTouchProjectBinPath;
public string MonoTouchProjectObjPath;
public string MonoTouchProjectPath;
public string MonoTouchProjectCSProjPath;
public string AppBundlePath;
public ProjectPaths SetupProjectPaths (string projectName, string csprojName, string baseDir = "../", bool includePlatform = true, string platform = "iPhoneSimulator", string config = "Debug", string projectPath = null, bool is_dotnet = false)
{
var testsBase = GetTestDirectory ();
if (projectPath == null) {
if (Path.IsPathRooted (baseDir)) {
projectPath = Path.Combine (baseDir, projectName);
} else {
if (baseDir.StartsWith ("../", StringComparison.Ordinal))
baseDir = baseDir.Substring (3); // Tests have been relocated, which means the given relative base dir is not correct anymore, so fix it.
projectPath = Path.Combine (testsBase, baseDir, projectName);
get {
if (engine == null)
engine = new TestEngine ();
return engine;
}
}
string binPath;
string objPath;
if (is_dotnet) {
var targetPlatform = "net5.0";
var subdir = string.Empty;
var targetPlatformSuffix = string.Empty;
switch (TargetFrameworkIdentifier) {
case "Xamarin.iOS":
subdir = platform == "iPhone" ? "ios-arm64" : "ios-x64";
targetPlatformSuffix = "ios";
break;
case "Xamarin.TVOS":
subdir = platform == "iPhone" ? "tvos-arm64" : "tvos-x64";
targetPlatformSuffix = "tvos";
break;
case "Xamarin.WatchOS":
subdir = platform == "iPhone" ? "watchos-arm" : "watchos-x86";
targetPlatformSuffix = "watchos";
break;
default:
throw new NotImplementedException ($"Unknown TargetFrameworkIdentifier: {TargetFrameworkIdentifier}");
}
targetPlatform += "-" + targetPlatformSuffix;
binPath = Path.Combine (projectPath, "bin", platform, config, targetPlatform, subdir);
objPath = Path.Combine (projectPath, "obj", platform, config, targetPlatform, subdir);
} else {
binPath = includePlatform ? Path.Combine (projectPath, "bin", platform, config) : Path.Combine (projectPath, "bin", config);
objPath = includePlatform ? Path.Combine (projectPath, "obj", platform, config) : Path.Combine (projectPath, "obj", config);
}
ProjectPaths paths;
ProjectPaths MonoTouchProject {
get {
if (paths == null) {
var platform = "iPhoneSimulator";
var config = "Debug";
var projectPath = Path.Combine (Configuration.TestProjectsDirectory, "MySingleView");
var binPath = Path.Combine (projectPath, "bin", platform, config);
var objPath = Path.Combine (projectPath, "obj", platform, config);
return new ProjectPaths {
paths = new ProjectPaths {
ProjectPath = projectPath,
ProjectBinPath = binPath,
ProjectObjPath = objPath,
ProjectCSProjPath = Path.Combine (projectPath, csprojName + ".csproj"),
AppBundlePath = Path.Combine (binPath, projectName.Replace (" ", "") + ".app"),
AppBundlePath = Path.Combine (binPath, "MySingleView.app"),
};
}
public ProjectPaths SetupProjectPaths (string projectName, string baseDir = "../", bool includePlatform = true, string platform = "iPhoneSimulator", string config = "Debug", string projectPath = null)
{
return SetupProjectPaths (projectName, projectName, baseDir, includePlatform, platform, config, projectPath);
return paths;
}
}
public string MonoTouchProjectObjPath => MonoTouchProject.ProjectObjPath;
public string MonoTouchProjectPath => MonoTouchProject.ProjectPath;
public string AppBundlePath => MonoTouchProject.AppBundlePath;
[SetUp]
public virtual void Setup ()
{
var mtouchPaths = SetupProjectPaths ("MySingleView");
MonoTouchProjectBinPath = mtouchPaths.ProjectBinPath;
MonoTouchProjectObjPath = mtouchPaths.ProjectObjPath;
MonoTouchProjectCSProjPath = mtouchPaths.ProjectCSProjPath;
MonoTouchProjectPath = mtouchPaths.ProjectPath;
AppBundlePath = mtouchPaths.AppBundlePath;
var libraryPaths = SetupProjectPaths ("MyLibrary", "../MySingleView/", false);
LibraryProjectBinPath = libraryPaths.ProjectBinPath;
LibraryProjectObjPath = libraryPaths.ProjectObjPath;
LibraryProjectPath = libraryPaths.ProjectPath;
LibraryProjectCSProjPath = libraryPaths.ProjectCSProjPath;
SetupEngine ();
MonoTouchProject = SetupProject (Engine, MonoTouchProjectCSProjPath);
MonoTouchProjectInstance = MonoTouchProject.CreateProjectInstance ();
LibraryProject = SetupProject (Engine, LibraryProjectCSProjPath);
LibraryProjectInstance = LibraryProject.CreateProjectInstance ();
CleanUp ();
}
public void SetupEngine ()
{
Engine = new TestEngine ();
}
public Project SetupProject (TestEngine engine, string projectPath)
{
return engine.ProjectCollection.LoadProject (projectPath);
}
public virtual string TargetFrameworkIdentifier {
get {
return "Xamarin.iOS";
}
}
public bool IsWatchOS {
get { return TargetFrameworkIdentifier == "Xamarin.WatchOS"; }
}
public bool IsTVOS {
get { return TargetFrameworkIdentifier == "Xamarin.TVOS"; }
}
public void CleanUp () {
var paths = SetupProjectPaths ("MySingleView");
MonoTouchProjectPath = paths.ProjectPath;
// Ensure the bin and obj directories are cleared
SafeDelete (Path.Combine (MonoTouchProjectPath, "bin"));
SafeDelete (Path.Combine (MonoTouchProjectPath, "obj"));
SafeDelete (Path.Combine (LibraryProjectPath, "bin"));
SafeDelete (Path.Combine (LibraryProjectPath, "obj"));
// Reset all the write times as we deliberately set some in the future for our tests
foreach (var file in Directory.GetFiles (MonoTouchProjectPath, "*.*", SearchOption.AllDirectories))
File.SetLastWriteTimeUtc (file, DateTime.UtcNow);
foreach (var file in Directory.GetFiles (LibraryProjectPath, "*.*", SearchOption.AllDirectories))
File.SetLastWriteTimeUtc (file, DateTime.UtcNow);
Engine.UnloadAllProjects ();
Engine = new TestEngine ();
}
protected void SafeDelete (string path)
{
try {
if (Directory.Exists (path))
Directory.Delete (path, true);
else if (File.Exists (path))
File.Delete (path);
} catch {
}
}
public void TestFilesDoNotExist(string baseDir, IEnumerable<string> files)
{
foreach (var v in files.Select (s => Path.Combine (baseDir, s)))
Assert.IsFalse (File.Exists (v) || Directory.Exists (v), "Unexpected file: {0} exists", v);
}
public void TestFilesExists (string baseDir, string[] files)
{
foreach (var v in files.Select (s => Path.Combine (baseDir, s)))
Assert.IsTrue (File.Exists (v) || Directory.Exists (v), "Expected file: {0} does not exist", v);
}
public void TestFilesExists (string [] baseDirs, string [] files)
{
if (baseDirs.Length == 1) {
TestFilesExists (baseDirs [0], files);
} else {
foreach (var file in files)
Assert.IsTrue (baseDirs.Select (s => File.Exists (Path.Combine (s, file))).Any (v => v), $"Expected file: {file} does not exist in any of the directories: {string.Join (", ", baseDirs)}");
}
}
public void TestStoryboardC (string path)
{
Assert.IsTrue (Directory.Exists (path), "Storyboard {0} does not exist", path);
Assert.IsTrue (File.Exists (Path.Combine (path, "Info.plist")));
TestPList (path, new string [] {"CFBundleVersion", "CFBundleExecutable"});
}
public void TestPList (string path, string[] keys)
{
var plist = PDictionary.FromFile (Path.Combine (path, "Info.plist"));
foreach (var x in keys) {
Assert.IsTrue (plist.ContainsKey (x), "Key {0} is not present in {1} Info.plist", x, path);
Assert.IsNotEmpty (((PString)plist[x]).Value, "Key {0} is empty in {1} Info.plist", x, path);
}
}
[TearDown]
public virtual void Teardown ()
{
engine = null;
paths = null;
}
public T CreateTask<T> () where T : Task, new()
@ -332,7 +66,7 @@ namespace Xamarin.iOS.Tasks
/// <param name="expectedErrorCount">Expected error count. 0 by default.</param>
public void ExecuteTask (Task task, int expectedErrorCount = 0)
{
task.Execute ();
var rv = task.Execute ();
if (expectedErrorCount != Engine.Logger.ErrorEvents.Count) {
string messages = string.Empty;
if (Engine.Logger.ErrorEvents.Count > 0) {
@ -340,210 +74,20 @@ namespace Xamarin.iOS.Tasks
}
Assert.AreEqual (expectedErrorCount, Engine.Logger.ErrorEvents.Count, "#RunTask-ErrorCount" + messages);
}
Assert.AreEqual (expectedErrorCount == 0, rv, "Failure");
}
protected string CreateTempFile (string path)
{
return Path.Combine (Cache.CreateTemporaryDirectory (), path);
}
protected DateTime GetLastModified (string file)
{
if (Path.GetExtension (file) == ".nib" && !File.Exists (file))
file = Path.Combine (file, "runtime.nib");
if (!File.Exists (file))
Assert.Fail ("Expected file '{0}' did not exist", file);
return File.GetLastWriteTimeUtc (file);
}
protected void RemoveItemsByName (Project project, string itemName)
{
project.RemoveItems (project.GetItems (itemName));
}
protected string SetPListKey (string key, PObject value)
{
var paths = SetupProjectPaths ("MySingleView");
var plist = PDictionary.FromFile (Path.Combine (paths.ProjectPath, "Info.plist"));
if (value == null)
plist.Remove (key);
else
plist [key] = value;
var modifiedPListPath = Path.Combine (Cache.CreateTemporaryDirectory (), "modified.plist");
plist.Save (modifiedPListPath);
return modifiedPListPath;
}
protected void Touch (string file)
{
if (!File.Exists (file))
Assert.Fail ("Expected file '{0}' did not exist", file);
EnsureFilestampChange ();
File.SetLastWriteTimeUtc (file, DateTime.UtcNow);
EnsureFilestampChange ();
}
static bool? is_apfs;
public static bool IsAPFS {
get {
if (!is_apfs.HasValue) {
var exit_code = ExecutionHelper.Execute ("/bin/df", new string[] { "-t", "apfs", "/" }, out var output, TimeSpan.FromSeconds (10));
is_apfs = exit_code == 0 && output.Trim ().Split ('\n').Length >= 2;
}
return is_apfs.Value;
path = Path.Combine (Cache.CreateTemporaryDirectory ("msbuild-tests"), path);
using (new FileStream (path, FileMode.CreateNew)) {}
return path;
}
}
public static void EnsureFilestampChange ()
{
if (IsAPFS)
return;
Thread.Sleep (1000);
}
public void RunTarget (Project project, string target, int expectedErrorCount = 0)
{
RunTarget (project, null, target, ExecutionMode.InProcess, expectedErrorCount);
}
public void RunTarget (Project project, string project_path, string target, ExecutionMode executionMode = ExecutionMode.InProcess, int expectedErrorCount = 0)
{
if (executionMode == ExecutionMode.InProcess) {
RunTargetOnInstance (project.CreateProjectInstance (), target, expectedErrorCount);
return;
}
var platform = Engine.ProjectCollection.GetGlobalProperty ("Platform")?.EvaluatedValue;
var configuration = Engine.ProjectCollection.GetGlobalProperty ("Configuration")?.EvaluatedValue;
var dict = new Dictionary<string, string> ();
if (!string.IsNullOrEmpty (platform))
dict ["Platform"] = platform;
if (!string.IsNullOrEmpty (configuration))
dict ["Configuration"] = configuration;
ExecutionResult rv;
switch (executionMode) {
case ExecutionMode.DotNet:
rv = Dotnet (target, project_path, dict, assert_success: expectedErrorCount == 0);
break;
case ExecutionMode.MSBuild:
rv = MSBuild (project_path, target, dict, assert_success: expectedErrorCount == 0);
break;
default:
throw new NotImplementedException ($"Unknown excecution mode: {executionMode}");
}
Assert.AreEqual (expectedErrorCount, rv.ExitCode, "ExitCode/ExpectedErrorCount");
}
public ExecutionResult Dotnet (string command, string project, Dictionary<string, string> properties, bool assert_success = true)
{
return DotNet.Execute (command, project, properties, assert_success: assert_success);
}
public ExecutionResult MSBuild (string project, string target, Dictionary<string, string> properties, string verbosity = "diagnostic", bool assert_success = true)
{
if (!File.Exists (project))
throw new FileNotFoundException ($"The project file '{project}' does not exist.");
var args = new List<string> ();
args.Add ("--");
args.Add ($"/t:{target}");
args.Add (project);
if (properties != null) {
foreach (var prop in properties)
args.Add ($"/p:{prop.Key}={prop.Value}");
}
if (!string.IsNullOrEmpty (verbosity))
args.Add ($"/verbosity:{verbosity}");
args.Add ($"/bl:{Path.Combine (Path.GetDirectoryName (project), "log.binlog")}");
var output = new StringBuilder ();
var executable = Configuration.XIBuildPath;
var rv = ExecutionHelper.Execute (executable, args, null, output, output, workingDirectory: Path.GetDirectoryName (project), timeout: TimeSpan.FromMinutes (10));
if (assert_success && rv != 0) {
Console.WriteLine ($"'{executable} {StringUtils.FormatArguments (args)}' failed with exit code {rv}.");
Console.WriteLine (output);
Assert.AreEqual (0, rv, $"Exit code: {executable} {StringUtils.FormatArguments (args)}");
}
return new ExecutionResult {
StandardOutput = output,
StandardError = output,
ExitCode = rv,
};
}
public void RunTargetOnInstance (ProjectInstance instance, string target, int expectedErrorCount = 0)
{
Engine.BuildProject (instance, new [] { target }, new Hashtable { {"Platform", "iPhone"} });
if (expectedErrorCount != Engine.Logger.ErrorEvents.Count) {
string messages = string.Empty;
if (Engine.Logger.ErrorEvents.Count > 0) {
messages = "\n\t" + string.Join ("\n\t", Engine.Logger.ErrorEvents.Select ((v) => v.Message).ToArray ());
}
Assert.AreEqual (expectedErrorCount, Engine.Logger.ErrorEvents.Count, "#RunTarget-ErrorCount" + messages);
}
}
public void RunTarget_WithErrors (Project project, string target)
{
RunTarget_WithErrors (project.CreateProjectInstance (), target);
}
public void RunTarget_WithErrors (ProjectInstance instance, string target)
{
Engine.BuildProject (instance, new [] { target }, new Hashtable ());
Assert.IsTrue (Engine.Logger.ErrorEvents.Count > 0, "#RunTarget-HasExpectedErrors");
}
protected void AssertValidDeviceBuild (string platform)
{
if (!Xamarin.Tests.Configuration.include_device && platform == "iPhone")
Assert.Ignore ("This build does not include device support.");
}
public static void NugetRestore (string project)
{
var rv = ExecutionHelper.Execute ("nuget", new string[] { "restore", project }, out var output);
if (rv != 0) {
Console.WriteLine ("nuget restore failed:");
Console.WriteLine (output);
Assert.Fail ($"'nuget restore' failed for {project}");
}
}
/// <summary>
/// Returns true if a target was skipped.
/// Originally from: https://github.com/xamarin/xamarin-android/blob/320cb0f66730e7107cc17310b99cd540605a234d/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/BuildOutput.cs#L48-L62
/// </summary>
public bool IsTargetSkipped (string target)
{
foreach (var line in Engine.Logger.MessageEvents.Select (m => m.Message)) {
if (line.Contains ($"Building target \"{target}\" completely")
|| line.Contains ($"Done building target \"{target}\""))
return false;
if (line.Contains ($"Target {target} skipped due to ")
|| line.Contains ($"Skipping target \"{target}\" because it has no ") //NOTE: message can say `inputs` or `outputs`
|| line.Contains ($"Target \"{target}\" skipped, due to")
|| line.Contains ($"Skipping target \"{target}\" because its outputs are up-to-date")
|| line.Contains ($"target {target}, skipping")
|| line.Contains ($"Skipping target \"{target}\" because all output files are up-to-date"))
return true;
}
return false;
}
}
public class ProjectPaths {
class ProjectPaths {
public string ProjectPath { get; set; }
public string ProjectBinPath { get; set; }
public string ProjectObjPath { get; set; }
public string ProjectCSProjPath { get; set; }
public string AppBundlePath { get; set; }
}
}

Просмотреть файл

@ -1,15 +1,10 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Logging;
using NUnit.Framework;
using Microsoft.Build.Utilities;
namespace Xamarin.iOS.Tasks
{
@ -24,12 +19,7 @@ namespace Xamarin.iOS.Tasks
{
Logger = new Logger ();
ProjectCollection = new ProjectCollection ();
ProjectCollection.RegisterLogger (Logger);
var printer = new ConsoleReportPrinter ();
var cl = new ConsoleLogger (LoggerVerbosity.Diagnostic, printer.Print, printer.SetForeground, printer.ResetColor);
ProjectCollection.RegisterLogger (cl);
}
public bool BuildProjectFile (string projectFileName, string [] targetNames, IDictionary globalProperties, IDictionary targetOutputs)
@ -37,20 +27,6 @@ namespace Xamarin.iOS.Tasks
throw new NotImplementedException ();
}
public bool BuildProject (ProjectInstance instance, string [] targetNames, IDictionary globalProperties)
{
if (globalProperties != null) {
foreach (DictionaryEntry de in globalProperties) {
//Note: trying to set this on the project causes the project to be added to the PC
// again, which of course, fails
instance.SetProperty ((string)de.Key, (string)de.Value);
}
}
//FIXME: assumption that we are still using the same PC!
return instance.Build (targetNames, ProjectCollection.Loggers);
}
public void LogCustomEvent (CustomBuildEventArgs e)
{
Logger.CustomEvents.Add (e);
@ -68,11 +44,6 @@ namespace Xamarin.iOS.Tasks
Logger.WarningsEvents.Add (e);
}
public void UnloadAllProjects ()
{
ProjectCollection.UnloadAllProjects ();
}
public int ColumnNumberOfTaskNode {
get { return 0; }
}
@ -123,7 +94,5 @@ namespace Xamarin.iOS.Tasks
bool IBuildEngine2.BuildProjectFilesInParallel (string [] projectFileNames, string [] targetNames, IDictionary [] globalProperties, IDictionary [] targetOutputsPerProject, string [] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion) => true;
bool IBuildEngine2.IsRunningMultipleNodes => false;
}
}

Просмотреть файл

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
<TargetFramework>net472</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<DisableTransitiveProjectReferences>true</DisableTransitiveProjectReferences>
<LangVersion>latest</LangVersion>
@ -28,22 +28,16 @@
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit.ConsoleRunner" Version="3.11.1" />
<PackageReference Include="NUnit.Extension.NUnitV2ResultWriter" Version="3.6.0" />
<PackageReference Include="Microsoft.Build" Version="15.9.20" />
<PackageReference Include="Microsoft.Build.Framework" Version="15.9.20" />
<PackageReference Include="Microsoft.Build.Tasks.Core" Version="15.9.20" />
<PackageReference Include="Microsoft.Build.Utilities.Core" Version="15.9.20" />
</ItemGroup>
<Target Name="BuildTasksAssembly" AfterTargets="BeforeBuild">
<MSBuild Projects="..\..\..\msbuild\Xamarin.iOS.Tasks\Xamarin.iOS.Tasks.csproj" />
</Target>
<ItemGroup>
<!-- Copy system Microsoft.Build*.dll and dependencies for tests to run against. We can remove this
and rely entirely on NuGet assets when mono/msbuild is merged into microsoft/msbuild. -->
<None Include="$(MSBuildToolsPath)\Microsoft.Build*.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="$(MSBuildToolsPath)\System.*.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\mtouch\Cache.cs">
<Link>external\Cache.cs</Link>

Просмотреть файл

@ -30,7 +30,7 @@ namespace Xharness.Jenkins {
SupportsParallelExecution = false,
};
var nunitExecutioniOSMSBuild = new NUnitExecuteTask (jenkins, buildiOSMSBuild, processManager) {
TestLibrary = Path.Combine (HarnessConfiguration.RootDirectory, "msbuild", "Xamarin.MacDev.Tasks.Tests", "bin", "Debug", "net461", "Xamarin.MacDev.Tasks.Tests.dll"),
TestLibrary = Path.Combine (HarnessConfiguration.RootDirectory, "msbuild", "Xamarin.MacDev.Tasks.Tests", "bin", "Debug", "net472", "Xamarin.MacDev.Tasks.Tests.dll"),
TestProject = netstandard2Project,
ProjectConfiguration = "Debug",
Platform = TestPlatform.iOS,