diff --git a/.gitignore b/.gitignore index e3605d7e1..0cd48026b 100644 --- a/.gitignore +++ b/.gitignore @@ -68,3 +68,5 @@ Tests/TestResults/ ThirdParty/gendarme.zip ThirdParty/gendarme/ Sample4/TestResults/ +Sample18/TestResults/ +*.user diff --git a/AltCover.CSApi/Definitions.cs b/AltCover.CSApi/Definitions.cs index c05593fff..5969377bd 100644 --- a/AltCover.CSApi/Definitions.cs +++ b/AltCover.CSApi/Definitions.cs @@ -301,14 +301,18 @@ namespace AltCover public static class CSApi { - public static int Prepare(IPrepareArgs p, ILogArgs l) + public static int Prepare(IPrepareArgs prepareArgs, ILogArgs log) { - return Api.Prepare(p.ToParameters(), l.ToParameters()); + if (prepareArgs == null) throw new ArgumentNullException(nameof(prepareArgs)); + if (log == null) throw new ArgumentNullException(nameof(log)); + return Api.Prepare(prepareArgs.ToParameters(), log.ToParameters()); } - public static int Collect(ICollectArgs c, ILogArgs l) + public static int Collect(ICollectArgs collectArgs, ILogArgs log) { - return Api.Collect(c.ToParameters(), l.ToParameters()); + if (collectArgs == null) throw new ArgumentNullException(nameof(collectArgs)); + if (log == null) throw new ArgumentNullException(nameof(log)); + return Api.Collect(collectArgs.ToParameters(), log.ToParameters()); } public static string Ipmo() @@ -329,22 +333,26 @@ private static DotNet.CLIArgs ToCLIArgs(ICLIArg args) return DotNet.CLIArgs.NewMany(new[] { force, failfast, showsummary }); } - public static string ToTestArguments(IPrepareArgs p, - ICollectArgs c, - ICLIArg force) + public static string ToTestArguments(IPrepareArgs prepareArgs, + ICollectArgs collectArgs, + ICLIArg control) { - return DotNet.ToTestArguments(p.ToParameters(), - c.ToParameters(), - ToCLIArgs(force)); + if (prepareArgs == null) throw new ArgumentNullException(nameof(prepareArgs)); + if (collectArgs == null) throw new ArgumentNullException(nameof(collectArgs)); + return DotNet.ToTestArguments(prepareArgs.ToParameters(), + collectArgs.ToParameters(), + ToCLIArgs(control)); } - public static string[] ToTestArgumentList(IPrepareArgs p, - ICollectArgs c, - ICLIArg force) + public static string[] ToTestArgumentList(IPrepareArgs prepareArgs, + ICollectArgs collectArgs, + ICLIArg control) { - return DotNet.ToTestArgumentList(p.ToParameters(), - c.ToParameters(), - ToCLIArgs(force)). + if (prepareArgs == null) throw new ArgumentNullException(nameof(prepareArgs)); + if (collectArgs == null) throw new ArgumentNullException(nameof(collectArgs)); + return DotNet.ToTestArgumentList(prepareArgs.ToParameters(), + collectArgs.ToParameters(), + ToCLIArgs(control)). ToArray(); } } diff --git a/AltCover.CSApi/Properties/AssemblyInfo.cs b/AltCover.CSApi/Properties/AssemblyInfo.cs index 35533fe87..72d37dea2 100644 --- a/AltCover.CSApi/Properties/AssemblyInfo.cs +++ b/AltCover.CSApi/Properties/AssemblyInfo.cs @@ -8,6 +8,7 @@ [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] +[assembly: System.CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/AltCover.CSApi/altcover.csapi.core.csproj b/AltCover.CSApi/altcover.csapi.core.csproj index bd047be4e..59999d057 100644 --- a/AltCover.CSApi/altcover.csapi.core.csproj +++ b/AltCover.CSApi/altcover.csapi.core.csproj @@ -11,6 +11,7 @@ true true $(ProjectDir)..\Build\Infrastructure.snk + $(ProjectDir)../ diff --git a/AltCover.Cake/Cake.cs b/AltCover.Cake/Cake.cs index b6cfe50c6..8d35bb942 100644 --- a/AltCover.Cake/Cake.cs +++ b/AltCover.Cake/Cake.cs @@ -1,4 +1,5 @@ -using Cake.Core; +using System.Diagnostics.CodeAnalysis; +using Cake.Core; using Cake.Core.Annotations; using LogLevel = Cake.Core.Diagnostics.LogLevel; using Verbosity = Cake.Core.Diagnostics.Verbosity; @@ -7,53 +8,55 @@ namespace AltCover.Cake { - public static class Api + public static class Api + { + private static ILogArgs MakeLog(ICakeContext context, ILogArgs log) { - private static ILogArgs MakeLog(ICakeContext context, ILogArgs l) - { - if (l != null) - return l; + if (log != null) + return log; - if (context != null) - return new LogArgs() - { - Info = x => context.Log.Write(Verbosity.Normal, LogLevel.Information, x), - Warn = x => context.Log.Write(Verbosity.Normal, LogLevel.Warning, x), - Echo = x => context.Log.Write(Verbosity.Normal, LogLevel.Error, x), - Error = x => context.Log.Write(Verbosity.Verbose, LogLevel.Information, x), - }; + if (context != null) + return new LogArgs() + { + Info = x => context.Log.Write(Verbosity.Normal, LogLevel.Information, x), + Warn = x => context.Log.Write(Verbosity.Normal, LogLevel.Warning, x), + Echo = x => context.Log.Write(Verbosity.Normal, LogLevel.Error, x), + Error = x => context.Log.Write(Verbosity.Verbose, LogLevel.Information, x), + }; - return new LogArgs() - { - Info = x => { }, - Warn = x => { }, - Echo = x => { }, - Error = x => { } - }; - } + return new LogArgs() + { + Info = x => { }, + Warn = x => { }, + Echo = x => { }, + Error = x => { } + }; + } - [CakeMethodAlias] - public static int Prepare(this ICakeContext context, IPrepareArgs p, ILogArgs l = null) - { - return CSApi.Prepare(p, MakeLog(context, l)); - } + [CakeMethodAlias] + public static int Prepare(this ICakeContext context, IPrepareArgs prepareArgs, ILogArgs log = null) + { + return CSApi.Prepare(prepareArgs, MakeLog(context, log)); + } - [CakeMethodAlias] - public static int Collect(this ICakeContext context, ICollectArgs c, ILogArgs l = null) - { - return CSApi.Collect(c, MakeLog(context, l)); - } + [CakeMethodAlias] + public static int Collect(this ICakeContext context, ICollectArgs collectArgs, ILogArgs log = null) + { + return CSApi.Collect(collectArgs, MakeLog(context, log)); + } - [CakeMethodAlias] - public static string Ipmo(this ICakeContext context) - { - return CSApi.Ipmo(); - } + [CakeMethodAlias] + public static string Ipmo(this ICakeContext context) + { + if (context == null) throw new System.ArgumentNullException(nameof(context)); + return CSApi.Ipmo(); + } - [CakeMethodAlias] - public static string Version(this ICakeContext context) - { - return CSApi.Version(); - } + [CakeMethodAlias] + public static string Version(this ICakeContext context) + { + if (context == null) throw new System.ArgumentNullException(nameof(context)); + return CSApi.Version(); } + } } \ No newline at end of file diff --git a/AltCover.Cake/DotNet.cs b/AltCover.Cake/DotNet.cs index 54d7a72cb..1434ecd82 100644 --- a/AltCover.Cake/DotNet.cs +++ b/AltCover.Cake/DotNet.cs @@ -9,60 +9,67 @@ namespace AltCover.Cake { - public class AltCoverSettings - { - public IPrepareArgs PreparationPhase { get; set; } - public ICollectArgs CollectionPhase { get; set; } + public class AltCoverSettings + { + public IPrepareArgs PreparationPhase { get; set; } + public ICollectArgs CollectionPhase { get; set; } public ICLIArg Control { get; set; } - public Func Customize() - { + public Func Customize() + { return pabIn => { - var pabOut = new ProcessArgumentBuilder(); - if (pabIn != null) + var pabOut = new ProcessArgumentBuilder(); + if (pabIn != null) + { + pabIn.CopyTo(pabOut); + } + var args = CSApi.ToTestArgumentList( + this.PreparationPhase, + this.CollectionPhase, + this.Control); + Array.Reverse(args); + Array.ForEach( + args, + t => pabOut.Prepend(t)); + return pabOut; + }; + } + + public Func Concatenate(Func customIn) { - pabIn.CopyTo(pabOut); + var altcover = Customize(); + if (customIn == null) + { + return altcover; + } + else + { + return args => altcover(customIn(args)); + } } - var args = CSApi.ToTestArgumentList( - this.PreparationPhase, - this.CollectionPhase, - this.Control); - Array.Reverse(args); - Array.ForEach( - args, - t => pabOut.Prepend(t)); - return pabOut; - }; } - public Func Concatenate(Func customIn) + [CakeAliasCategory("DotNetCore")] + public static class DotNet { - var altcover = Customize(); - if (customIn == null) - { - return altcover; - } - else - { - return args => altcover(customIn(args)); - } - } - } + [CakeMethodAlias] + [CakeAliasCategory("Test")] + [System.Diagnostics.CodeAnalysis.SuppressMessage( + "Gendarme.Rules.Maintainability", "AvoidUnnecessarySpecializationRule", + Justification = "AvoidSpeculativeGenerality too")] + public static void DotNetCoreTest( + this ICakeContext context, + FilePath project, + DotNetCoreTestSettings settings, + AltCoverSettings altcover) + { + if (project == null) throw new ArgumentNullException(nameof(project)); + if (settings == null) throw new ArgumentNullException(nameof(settings)); + if (altcover == null) throw new ArgumentNullException(nameof(altcover)); - [CakeAliasCategory("DotNetCore")] - public static class DotNet - { - [CakeMethodAlias] - [CakeAliasCategory("Test")] - public static void DotNetCoreTest( - this ICakeContext context, - FilePath project, - DotNetCoreTestSettings settings, - AltCoverSettings altcover) - { - settings.ArgumentCustomization = altcover.Concatenate(settings.ArgumentCustomization); - context.DotNetCoreTest(project.FullPath, settings); + settings.ArgumentCustomization = altcover.Concatenate(settings.ArgumentCustomization); + context.DotNetCoreTest(project.GetFilename().FullPath, settings); + } } - } } \ No newline at end of file diff --git a/AltCover.Cake/Properties/AssemblyInfo.cs b/AltCover.Cake/Properties/AssemblyInfo.cs index 261cb1289..61c0ee3b5 100644 --- a/AltCover.Cake/Properties/AssemblyInfo.cs +++ b/AltCover.Cake/Properties/AssemblyInfo.cs @@ -8,6 +8,7 @@ [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] +[assembly: System.CLSCompliant(true)] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/AltCover.Cake/altcover.cake.core.csproj b/AltCover.Cake/altcover.cake.core.csproj index 82477c67c..063edbdd8 100644 --- a/AltCover.Cake/altcover.cake.core.csproj +++ b/AltCover.Cake/altcover.cake.core.csproj @@ -9,6 +9,7 @@ true true true + $(ProjectDir)../ diff --git a/AltCover.FSApi/CoverageFormats.fs b/AltCover.FSApi/CoverageFormats.fs index d16f3d09d..771428d04 100644 --- a/AltCover.FSApi/CoverageFormats.fs +++ b/AltCover.FSApi/CoverageFormats.fs @@ -117,7 +117,8 @@ module CoverageFormats = transform.Transform(navigable, output) XmlUtilities.PrependDeclaration rewrite - rewrite.SelectNodes("//method").OfType() + use methods = rewrite.SelectNodes("//method") + methods.OfType() |> Seq.iter (fun m -> let c = m.GetAttribute("class") m.SetAttribute("class", c.Replace('/', '+')) @@ -125,7 +126,8 @@ module CoverageFormats = let lead = name.Substring(name.LastIndexOf("::", StringComparison.Ordinal) + 2) m.SetAttribute("name", lead.Substring(0, lead.IndexOf('(')))) - rewrite.SelectNodes("//module").OfType() + use modules = rewrite.SelectNodes("//module") + modules.OfType() |> Seq.iter (fun m -> let path = m.GetAttribute("name") let info = System.IO.FileInfo path @@ -137,7 +139,8 @@ module CoverageFormats = let culture = System.Threading.Thread.CurrentThread.CurrentCulture try System.Threading.Thread.CurrentThread.CurrentCulture <- CultureInfo.InvariantCulture - rewrite.SelectNodes("//coverage").OfType() + use coverage = rewrite.SelectNodes("//coverage") + coverage.OfType() |> Seq.iter (fun c -> let now = DateTime.UtcNow.ToLongDateString() + ":" + DateTime.UtcNow.ToLongTimeString() diff --git a/AltCover.FSApi/Definitions.fs b/AltCover.FSApi/Definitions.fs index 52db3cafd..a94735552 100644 --- a/AltCover.FSApi/Definitions.fs +++ b/AltCover.FSApi/Definitions.fs @@ -17,7 +17,7 @@ module DotNet = [] type CLIArgs = | Force of bool diff --git a/AltCover.FSApi/OpenCover.fs b/AltCover.FSApi/OpenCover.fs index f2d6441c6..7c3e041a2 100644 --- a/AltCover.FSApi/OpenCover.fs +++ b/AltCover.FSApi/OpenCover.fs @@ -11,8 +11,10 @@ open System.Xml.XPath module OpenCoverUtilities = let private CompressMethod withinSequencePoint sameSpan (m : XmlElement) = - let sp = m.GetElementsByTagName("SequencePoint").OfType() |> Seq.toList - let bp = m.GetElementsByTagName("BranchPoint").OfType() |> Seq.toList + use sp0 = m.GetElementsByTagName("SequencePoint") + let sp = sp0.OfType() |> Seq.toList + use bp0 =m.GetElementsByTagName("BranchPoint") + let bp = bp0.OfType() |> Seq.toList if sp |> List.isEmpty |> not @@ -108,11 +110,13 @@ module OpenCoverUtilities = let CompressBranching (navigable : IXPathNavigable) withinSequencePoint sameSpan = // Validate let xmlDocument = new XmlDocument() - navigable.CreateNavigator().ReadSubtree() |> xmlDocument.Load + use reader = navigable.CreateNavigator().ReadSubtree() + reader |> xmlDocument.Load xmlDocument.Schemas <- XmlUtilities.LoadSchema AltCover.Base.ReportFormat.OpenCover xmlDocument.Validate(null) // Get all the methods - xmlDocument.SelectNodes("//Method") + use methods = xmlDocument.SelectNodes("//Method") + methods |> Seq.cast |> Seq.iter (CompressMethod withinSequencePoint sameSpan) // tidy up here diff --git a/AltCover.FSApi/Xhtml.fs b/AltCover.FSApi/Xhtml.fs index e026ac227..c055d1efb 100644 --- a/AltCover.FSApi/Xhtml.fs +++ b/AltCover.FSApi/Xhtml.fs @@ -33,7 +33,8 @@ module Xhtml = do use output = rewrite.CreateNavigator().AppendChild() transform.Transform(intermediate, output) - rewrite.DocumentElement.SelectNodes("//script[@language='JavaScript']").OfType + use scripts = rewrite.DocumentElement.SelectNodes("//script[@language='JavaScript']") + scripts.OfType () |> Seq.iter (fun n -> let text = n.InnerText diff --git a/AltCover.FSApi/Xml.fs b/AltCover.FSApi/Xml.fs index e25456ab6..c7902b642 100644 --- a/AltCover.FSApi/Xml.fs +++ b/AltCover.FSApi/Xml.fs @@ -10,6 +10,8 @@ open System.Xml.Linq open System.Xml.Schema open System.Xml.Xsl +open Augment + [] module XmlUtilities = [ isNull - |> not + if xDeclaration.IsNotNull then let xmlDeclaration = xmlDocument.CreateXmlDeclaration @@ -33,6 +33,9 @@ module XmlUtilities = [] + [] let ToXDocument(xmlDocument : XmlDocument) = use nodeReader = new XmlNodeReader(xmlDocument) nodeReader.MoveToContent() |> ignore // skips leading comments @@ -101,6 +104,6 @@ module XmlUtilities = | :? FileLoadException -> fallback [] - let PrependDeclaration(x : XmlDocument) = + let internal PrependDeclaration(x : XmlDocument) = let xmlDeclaration = x.CreateXmlDeclaration("1.0", "utf-8", null) x.InsertBefore(xmlDeclaration, x.FirstChild) |> ignore \ No newline at end of file diff --git a/AltCover.NetCoreApp/Program.fs b/AltCover.NetCoreApp/Program.fs index 70bd23190..c00bf7f7c 100644 --- a/AltCover.NetCoreApp/Program.fs +++ b/AltCover.NetCoreApp/Program.fs @@ -1,13 +1,24 @@ namespace AltCover +open System +open System.Runtime.InteropServices + +[] +[] +() + module DotNetAltCover = let internal ToConsole() = Output.Error <- CommandLine.WriteErr - Output.Usage <- CommandLine.Usage + Output.Usage <- CommandLine.UsageBase Output.Echo <- CommandLine.WriteErr Output.Info <- CommandLine.WriteOut [] + [] let private Main arguments = ToConsole() AltCover.Main.EffectiveMain arguments \ No newline at end of file diff --git a/AltCover.NetCoreApp/altcover.netcoreapp.core.fsproj b/AltCover.NetCoreApp/altcover.netcoreapp.core.fsproj index 2f6656e32..b6e7653f6 100644 --- a/AltCover.NetCoreApp/altcover.netcoreapp.core.fsproj +++ b/AltCover.NetCoreApp/altcover.netcoreapp.core.fsproj @@ -9,6 +9,7 @@ true true $(SolutionDir)AltCover/AltCover.ico + $(ProjectDir)../ @@ -25,6 +26,7 @@ 4 true + TRACE;DEBUG;CODE_ANALYSIS diff --git a/AltCover.PowerShell/Command.fs b/AltCover.PowerShell/Command.fs index a2fa9f4f9..c9ae26a82 100644 --- a/AltCover.PowerShell/Command.fs +++ b/AltCover.PowerShell/Command.fs @@ -20,6 +20,9 @@ type ShowHidden = [] [] +[] [] @@ -280,7 +283,7 @@ type InvokeAltCoverCommand(runner : bool) = let where = self.SessionState.Path.CurrentLocation.Path Directory.SetCurrentDirectory where let makeError s = - ErrorRecord(InvalidOperationException(), s, ErrorCategory.InvalidOperation, self) + ErrorRecord(InvalidOperationException(s), s, ErrorCategory.InvalidOperation, self) |> self.WriteError let status = self.Dispatch() diff --git a/AltCover.Recorder/Adapter.fs b/AltCover.Recorder/Adapter.fs index 1d385ecab..333cf0ebb 100644 --- a/AltCover.Recorder/Adapter.fs +++ b/AltCover.Recorder/Adapter.fs @@ -25,21 +25,25 @@ module Adapter = let entry = Dictionary() Instance.Visits.Add(name, entry) + let internal Init n l = let tmp = { PointVisit.Create() with Count = n } + tmp.Tracks.AddRange l + tmp + let VisitsAdd name line number = prepareName name - let v = PointVisit.Init number [] + let v = Init number [] Instance.Visits.[name].Add(line, v) let VisitsAddTrack name line number = prepareName name let v1 = - PointVisit.Init number + Init number [ Call 17 Call 42 ] Instance.Visits.[name].Add(line, v1) let v2 = - PointVisit.Init (number + 1L) + Init (number + 1L) [ Time 17L Both { Time = 42L diff --git a/AltCover.Recorder/Base.fs b/AltCover.Recorder/Base.fs index 32dcef0f5..d2efe6021 100644 --- a/AltCover.Recorder/Base.fs +++ b/AltCover.Recorder/Base.fs @@ -76,19 +76,10 @@ and [] } with static member Create () = { Count = 0L; Tracks = List() } - static member Init n l = let tmp = { PointVisit.Create() with Count = n } - tmp.Tracks.AddRange l - tmp member self.Step() = System.Threading.Interlocked.Increment(&self.Count) |> ignore member self.Track something = lock self.Tracks (fun () -> self.Tracks.Add something) member self.Total() = self.Count + int64 self.Tracks.Count -module internal Assist = - let internal SafeDispose x = - try - (x :> IDisposable).Dispose() - with :? ObjectDisposedException -> () - module internal Counter = /// /// The offset flag for branch counts @@ -168,6 +159,8 @@ module internal Counter = /// /// The coverage results to incorporate /// The coverage file to update as a stream + [] let internal UpdateReport (postProcess : XmlDocument -> unit) (pointProcess : XmlElement -> List -> unit) own (counts : Dictionary>) format coverageFile @@ -199,7 +192,13 @@ module internal Counter = let (m, i, m', s, v) = XmlByFormat format - coverageDocument.SelectNodes(m) +#if NET2 + let +#else + use +#endif + moduleNodes = coverageDocument.SelectNodes(m) + moduleNodes |> Seq.cast |> Seq.map (fun el -> el.GetAttribute(i), el) |> Seq.filter (fun (k, _) -> counts.ContainsKey k) @@ -209,13 +208,24 @@ module internal Counter = // affectedModule.Descendants(XName.Get("seqpnt")) // Get the methods, then flip their // contents before concatenating - let nn = affectedModule.SelectNodes(m') +#if NET2 + let +#else + use +#endif + nn = affectedModule.SelectNodes(m') nn |> Seq.cast |> Seq.collect (fun (method : XmlElement) -> s |> Seq.collect (fun (name, flag) -> - method.SelectNodes(name) +#if NET2 + let +#else + use +#endif + nodes = method.SelectNodes(name) + nodes |> Seq.cast |> Seq.map (fun x -> (x, flag)) |> Seq.toList @@ -251,6 +261,8 @@ module internal Counter = [] + [] let internal DoFlush postProcess pointProcess own counts format report output = use coverageFile = new FileStream(report, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 4096, @@ -284,6 +296,7 @@ module internal Counter = if not (counts.ContainsKey hitPointId) then counts.Add(hitPointId, PointVisit.Create())) +#if RUNNER let internal AddTable (counts : Dictionary>) (t : Dictionary>) = let mutable hitcount = 0L @@ -300,6 +313,7 @@ module internal Counter = v.Tracks.AddRange(add.Tracks) ))) hitcount + #endif let internal AddSingleVisit (counts : Dictionary>) moduleId hitPointId context = diff --git a/AltCover.Recorder/Recorder.fs b/AltCover.Recorder/Recorder.fs index 4d9550658..39c00fa2d 100644 --- a/AltCover.Recorder/Recorder.fs +++ b/AltCover.Recorder/Recorder.fs @@ -6,6 +6,7 @@ namespace AltCover.Recorder open System open System.Collections.Generic open System.Diagnostics +open System.Diagnostics.CodeAnalysis open System.IO open System.Reflection @@ -67,6 +68,9 @@ module Instance = /// This property's IL code is modified to store the user chosen override if applicable /// [] + [] let mutable internal CoverageFormat = ReportFormat.NCover /// @@ -86,12 +90,18 @@ module Instance = /// /// Gets or sets the current test method /// + [] type private CallStack = [] static val mutable private instance : Option val mutable private caller : int list private new(x : int) = { caller = [ x ] } + [] static member Instance = match CallStack.instance with | None -> CallStack.instance <- Some(CallStack(0)) @@ -144,7 +154,7 @@ module Instance = let InitialiseTrace(t : Tracer) = WithMutex(fun _ -> trace <- t.OnStart() - IsRunner <- IsRunner || trace.IsConnected()) + IsRunner <- IsRunner || trace.IsConnected) let internal Watcher = new FileSystemWatcher() let mutable internal Recording = true @@ -213,6 +223,8 @@ module Instance = use writer = new StreamWriter(file) text |> Seq.iter (fun line -> writer.WriteLine("{0}", line)) + [] let #if DEBUG #else @@ -257,7 +269,7 @@ module Instance = let internal VisitImpl moduleId hitPointId context = if (Sample = Sampling.All || TakeSample Sample moduleId hitPointId) then let adder = - if Defer || Supervision || (trace.IsConnected() |> not) + if Defer || Supervision || (trace.IsConnected |> not) then AddVisit else TraceVisit adder moduleId hitPointId context diff --git a/AltCover.Recorder/Tracer.fs b/AltCover.Recorder/Tracer.fs index 4471ac273..4070c0153 100644 --- a/AltCover.Recorder/Tracer.fs +++ b/AltCover.Recorder/Tracer.fs @@ -25,34 +25,43 @@ type Tracer = Stream : System.IO.Stream Formatter : System.IO.BinaryWriter } - static member Create(name : string) = + static member internal Create(name : string) = { Tracer = name Runner = false Definitive = false Stream = null Formatter = null } - member this.IsConnected() = - match this.Stream with - | null -> false - | _ -> this.Runner + member internal this.IsConnected + with get() = + match this.Stream with + | null -> false + | _ -> this.Runner - member this.Connect() = + [] + [] + member private this.MakeConnection f = + let fs = File.OpenWrite f + let s = new DeflateStream(fs, CompressionMode.Compress) + { this with + Stream = s + Formatter = new BinaryWriter(s) + Runner = true } + + member internal this.Connect() = if File.Exists this.Tracer then Seq.initInfinite (fun i -> Path.ChangeExtension(this.Tracer, sprintf ".%d.acv" i)) |> Seq.filter (File.Exists >> not) - |> Seq.map (fun f -> - let fs = File.OpenWrite f - let s = new DeflateStream(fs, CompressionMode.Compress) - { this with - Stream = s - Formatter = new BinaryWriter(s) - Runner = true }) + |> Seq.map this.MakeConnection |> Seq.head else this - member this.Close() = + member internal this.Close() = try this.Stream.Flush() this.Formatter.Close() @@ -97,15 +106,15 @@ type Tracer = |> Table |> this.Push String.Empty 0 - member this.OnStart() = + member internal this.OnStart() = let running = if this.Tracer <> "Coverage.Default.xml.acv" then this.Connect() else this { running with Definitive = true } - member this.OnConnected f g = - if this.IsConnected() then f() else g() + member internal this.OnConnected f g = + if this.IsConnected then f() else g() member internal this.OnFinish visits = this.CatchUp visits diff --git a/AltCover.Visualizer/CoverageFile.fs b/AltCover.Visualizer/CoverageFile.fs index 8d2c3e357..8a4164442 100644 --- a/AltCover.Visualizer/CoverageFile.fs +++ b/AltCover.Visualizer/CoverageFile.fs @@ -23,39 +23,51 @@ type InvalidFile = module Transformer = let internal DefaultHelper (_ : XDocument) (document : XDocument) = document + [] let internal LoadTransform(path : string) = - let stylesheet = - XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(path)) + use str = Assembly.GetExecutingAssembly().GetManifestResourceStream(path) + use stylesheet = + XmlReader.Create(str) let xmlTransform = new XslCompiledTransform() xmlTransform.Load(stylesheet, new XsltSettings(false, true), null) xmlTransform + [] let internal TransformFromOtherCover (document : XNode) (path : string) = let xmlTransform = LoadTransform path use buffer = new MemoryStream() - let sw = new StreamWriter(buffer) + use sw = new StreamWriter(buffer) // transform the document: xmlTransform.Transform(document.CreateReader(), null, sw) buffer.Position <- 0L - XDocument.Load(XmlReader.Create(buffer)) + use reader = XmlReader.Create(buffer) + XDocument.Load(reader) let internal TransformFromOpenCover(document : XNode) = let report = TransformFromOtherCover document "AltCover.Visualizer.OpenCoverToNCoverEx.xsl" report + [] // PartCover to NCover style sheet let internal ConvertFile (helper : CoverageTool -> XDocument -> XDocument -> XDocument) (document : XDocument) = let schemas = new XmlSchemaSet() + use sr1 = new StreamReader(Assembly.GetExecutingAssembly() + .GetManifestResourceStream("AltCover.Visualizer.OpenCover.xsd")) + use ocreader = XmlReader.Create(sr1) + use sr2 = new StreamReader(Assembly.GetExecutingAssembly() + .GetManifestResourceStream("AltCover.Visualizer.NCover.xsd")) + + use ncreader = XmlReader.Create(sr2) try match document.XPathSelectElements("/CoverageSession").Count() with | 1 -> schemas.Add - (String.Empty, - XmlReader.Create - (new StreamReader(Assembly.GetExecutingAssembly() - .GetManifestResourceStream("AltCover.Visualizer.OpenCover.xsd")))) + (String.Empty, ocreader) |> ignore document.Validate(schemas, null) let report = TransformFromOpenCover document @@ -63,19 +75,13 @@ module Transformer = // Consistency check our XSLT let schemas2 = new XmlSchemaSet() schemas2.Add - (String.Empty, - XmlReader.Create - (new StreamReader(Assembly.GetExecutingAssembly() - .GetManifestResourceStream("AltCover.Visualizer.NCover.xsd")))) + (String.Empty, ncreader) |> ignore fixedup.Validate(schemas2, null) Right fixedup | _ -> schemas.Add - (String.Empty, - XmlReader.Create - (new StreamReader(Assembly.GetExecutingAssembly() - .GetManifestResourceStream("AltCover.Visualizer.NCover.xsd")))) + (String.Empty, ncreader) |> ignore document.Validate(schemas, null) Right document diff --git a/AltCover.Visualizer/Visualizer.fs b/AltCover.Visualizer/Visualizer.fs index c9835f974..26f3c1f46 100644 --- a/AltCover.Visualizer/Visualizer.fs +++ b/AltCover.Visualizer/Visualizer.fs @@ -26,6 +26,7 @@ open Microsoft.Win32 open Mono.Options +[] type internal Handler() = class #if NETCOREAPP2_1 @@ -123,6 +124,9 @@ type internal Handler() = DefaultValue(true)>] val mutable classStructureTree : TreeView + [] + val mutable auxModel : TreeStore + [< #if NETCOREAPP2_1 Builder.Object; @@ -145,7 +149,7 @@ type internal Handler() = val mutable activeRow : int end -module Persistence = +module internal Persistence = let mutable internal save = true #if NETCOREAPP2_1 @@ -155,6 +159,11 @@ module Persistence = doc.Add(XElement(XName.Get "AltCover.Visualizer")) doc + [] let private EnsureFile() = let profileDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) let dir = Directory.CreateDirectory(Path.Combine(profileDir, ".altcover")) @@ -168,10 +177,12 @@ module Persistence = let doc = XDocument.Load(file) try let schemas = new XmlSchemaSet() - use xsd = - new StreamReader(Assembly.GetExecutingAssembly() - .GetManifestResourceStream("AltCover.Visualizer.config.xsd")) - schemas.Add(String.Empty, XmlReader.Create xsd) |> ignore + use str = Assembly.GetExecutingAssembly() + .GetManifestResourceStream("AltCover.Visualizer.config.xsd") + use xr = new StreamReader(str) + use xsd = xr |> XmlReader.Create + + schemas.Add(String.Empty, xsd) |> ignore doc.Validate(schemas, null) (file, doc) with xx -> // DoNotSwallowErrorsCatchingNonSpecificExceptionsRule @@ -246,7 +257,7 @@ module Persistence = | [] -> System.IO.Directory.GetCurrentDirectory() | x :: _ -> x.FirstNode.ToString() - let internal saveCoverageFiles (coverageFiles : string list) = + let internal saveCoverageFiles (coverageFiles : string seq) = let file, config = EnsureFile() config.XPathSelectElements("//RecentlyOpened") |> Seq.toList @@ -494,8 +505,8 @@ module Gui = (if special = MethodType.Property then PropertyIcon else EventIcon) .Force() :> obj |]) keys - |> Seq.sortBy (fun key -> key.name |> DisplayName) - |> Seq.iter (ApplyMethod theModel newrow) + |> Seq.sortBy (fun key -> key.name |> DisplayName) + |> Seq.iter (ApplyMethod theModel newrow) else ApplyMethod theModel theRow (keys |> Seq.head) @@ -507,16 +518,22 @@ module Gui = |> HandleSpecialName) |> Seq.toArray - methods - |> Array.sortInPlaceWith (fun ((l, lb), _) ((r, rb), _) -> - let sort1 = String.Compare(l, r, StringComparison.OrdinalIgnoreCase) + let orderMethods array = + array + |> Array.sortInPlaceWith (fun ((l, (lb : MethodType)), _) ((r, rb), _) -> + let sort1 = String.Compare(l, r, StringComparison.OrdinalIgnoreCase) + + let sort2 = + if sort1 = 0 + then String.Compare(l, r, StringComparison.Ordinal) + else sort1 + if sort2 = 0 then lb.CompareTo rb else sort2) + + let applyMethods array = + array |> Array.iter (ApplyToModel model row) - let sort2 = - if sort1 = 0 - then String.Compare(l, r, StringComparison.Ordinal) - else sort1 - if sort2 = 0 then lb.CompareTo rb else sort2) - methods |> Array.iter (ApplyToModel model row) + methods |> orderMethods + methods |> applyMethods let private PopulateNamespaceNode (model : TreeStore) (row : TreeIter) (nodes : seq) = @@ -655,32 +672,30 @@ module Gui = x.Fault.Message) ShowMessageOnGuiThread parent MessageType.Error message - let private OutdatedCoverageFileMessage (parent : Window) (x : FileInfo) = - let format = GetResourceString("CoverageOutOfDate") - let message = - String.Format(System.Globalization.CultureInfo.CurrentCulture, format, x.FullName) + [] + let private showMessageResourceFileWarning rn (parent : Window) (x : FileInfo) + (s : Source) = + let format = GetResourceString(rn) + let message = // rely of the format to drop the source file if not needed + String.Format(System.Globalization.CultureInfo.CurrentCulture, format, x.FullName, s.FullName) ShowMessageOnGuiThread parent MessageType.Warning message + let private OutdatedCoverageFileMessage (parent : Window) (x : FileInfo) = + showMessageResourceFileWarning "CoverageOutOfDate" parent x + (Source.File null) + let private MissingSourceFileMessage (parent : Window) (x : FileInfo) = - let format = GetResourceString("MissingSourceFile") - let message = - String.Format(System.Globalization.CultureInfo.CurrentCulture, format, x.FullName) - ShowMessageOnGuiThread parent MessageType.Warning message + showMessageResourceFileWarning "MissingSourceFile" parent x + (Source.File null) let private OutdatedCoverageThisFileMessage (parent : Window) (c : FileInfo) (s : Source) = - let format = GetResourceString("CoverageOutOfDateThisFile") - let message = - String.Format - (System.Globalization.CultureInfo.CurrentCulture, format, c.FullName, s.FullName) - ShowMessageOnGuiThread parent MessageType.Warning message + showMessageResourceFileWarning "CoverageOutOfDateThisFile" parent c s let private MissingSourceThisFileMessage (parent : Window) (c : FileInfo) (s : Source) = - let format = GetResourceString("MissingSourceThisFile") - let message = - String.Format - (System.Globalization.CultureInfo.CurrentCulture, format, c.FullName, s.FullName) - ShowMessageOnGuiThread parent MessageType.Warning message + showMessageResourceFileWarning "MissingSourceThisFile" parent c s // -------------------------- UI set-up --------------------------- let private InitializeHandler() = @@ -722,7 +737,8 @@ module Gui = let private PrepareAboutDialog(handler : Handler) = let ShowUrl(link : string) = match System.Environment.GetEnvironmentVariable("OS") with - | "Windows_NT" -> System.Diagnostics.Process.Start(link) |> ignore + | "Windows_NT" -> use browser = System.Diagnostics.Process.Start(link) + () // TODO -- other OS types | _ -> ShowMessage handler.aboutVisualizer link MessageType.Info // The first gets the display right, the second the browser launch @@ -770,6 +786,16 @@ module Gui = handler.classStructureTree.AppendColumn(column) |> ignore column.AddAttribute(cell, "text", 2 * i) column.AddAttribute(icon, "pixbuf", 1 + (2 * i))) + handler.classStructureTree.Model <- + new TreeStore(typeof, typeof, typeof, + typeof, typeof, typeof, + typeof, typeof, typeof, + typeof) + handler.auxModel <- + new TreeStore(typeof, typeof, typeof, + typeof, typeof, typeof, + typeof, typeof, typeof, + typeof) #if NETCOREAPP2_1 let private PrepareOpenFileDialog(handler : Handler) = @@ -1017,9 +1043,7 @@ module Gui = let internal ScrollToRow (h : Handler) _ = let buff = h.codeView.Buffer - if buff - |> isNull - |> not + if buff.IsNotNull && h.activeRow > 0 then let iter = buff.GetIterAtLine(h.activeRow - 1) @@ -1294,11 +1318,8 @@ module Gui = // warn if not if not (Seq.isEmpty newer) then OutdatedCoverageFileMessage h.mainWindow current - let model = - new TreeStore(typeof, typeof, typeof, - typeof, typeof, typeof, - typeof, typeof, typeof, - typeof) + let model = handler.auxModel + model.Clear() Mappings.Clear() let toprow = model.AppendValues(current.Name, XmlIcon.Force()) @@ -1334,12 +1355,13 @@ module Gui = // File is good so enable the refresh button h.refreshButton.Sensitive <- true // Do real UI work here + h.auxModel <- h.classStructureTree.Model :?> TreeStore h.classStructureTree.Model <- theModel h.codeView.Buffer.Clear() h.mainWindow.Title <- "AltCover.Visualizer" updateMRU h info.FullName true ////ShowMessage h.mainWindow (sprintf "%s\r\n>%A" info.FullName h.coverageFiles) MessageType.Info - InvokeOnGuiThread(UpdateUI model current) + InvokeOnGuiThread(UpdateUI h.auxModel current) } |> Async.Start) handler.fontButton.Clicked diff --git a/AltCover.Visualizer/altcover.visualizer.core.fsproj b/AltCover.Visualizer/altcover.visualizer.core.fsproj index 83350b118..79f416b65 100644 --- a/AltCover.Visualizer/altcover.visualizer.core.fsproj +++ b/AltCover.Visualizer/altcover.visualizer.core.fsproj @@ -16,6 +16,7 @@ $(AssemblySearchPaths);{GAC} + GUI $(ProjectDir)../ $(SolutionDir)_Binaries/$(AssemblyName)/$(Configuration)+$(Platform)/ $(SolutionDir)_Intermediate/$(AssemblyName)/$(Configuration)+$(Platform)/ diff --git a/AltCover/AltCover.fs b/AltCover/AltCover.fs index 7a2fb6cce..244ef2d4c 100644 --- a/AltCover/AltCover.fs +++ b/AltCover/AltCover.fs @@ -302,7 +302,7 @@ module internal Main = CommandLine.resources.GetString "MultiplesNotAllowed", "--showstatic") :: CommandLine.error)) (CommandLine.ddFlag "showGenerated" Visitor.showGenerated) - ("?|help|h", (fun x -> CommandLine.help <- not (isNull x))) + ("?|help|h", (fun x -> CommandLine.help <- x.IsNotNull)) ("<>", (fun x -> @@ -585,4 +585,7 @@ module internal Main = | _ -> DoInstrumentation arguments // mocking point + [] let mutable internal EffectiveMain = Main \ No newline at end of file diff --git a/AltCover/Api.fs b/AltCover/Api.fs index e50674154..e9e4af317 100644 --- a/AltCover/Api.fs +++ b/AltCover/Api.fs @@ -21,7 +21,7 @@ open Fake.DotNet [] type CollectParams = | Primitive of Primitive.CollectParams @@ -142,7 +142,7 @@ type CollectParams = [] type PrepareParams = | Primitive of Primitive.PrepareParams @@ -395,7 +395,10 @@ type PrepareParams = finally CommandLine.error <- saved -[] +[] type Logging = | Primitive of Primitive.Logging @@ -430,7 +433,7 @@ type Logging = #else #endif [] module private ArgsHelper = let Item a x = @@ -607,6 +610,8 @@ type Params = /// Command arguments Args : ArgType } + [] static member Create(a : ArgType) = { ToolPath = "altcover" ToolType = ToolType.CreateGlobalTool() @@ -661,10 +666,8 @@ let composeCommandLine parameters = [] -[] -let runCore parameters modifyCommand = + +let internal runCore parameters modifyCommand = use __ = Trace.traceTask "AltCover" String.Empty let command = (composeCommandLine parameters) |> modifyCommand let run = command |> Proc.run diff --git a/AltCover/Augment.fs b/AltCover/Augment.fs index 307827649..4101835c1 100644 --- a/AltCover/Augment.fs +++ b/AltCover/Augment.fs @@ -6,15 +6,27 @@ module Augment = #else module internal Augment = #endif + type System.Object with + member self.IsNotNull + with get() = + self |> isNull |> not +#if GUI +#else type Microsoft.FSharp.Core.Option<'T> with static member getOrElse (fallback : 'T) (x : option<'T>) = defaultArg x fallback - static member nullable (x : 'a when 'a : null) : option<'a> = - if isNull x then None else Some x - + static member nullable (x : 'T) : option<'T> = + if isNull (x :> obj) then None else Some x +#endif type Either<'a, 'b> = Choice<'b, 'a> + [] let Right x : Either<'a, 'b> = Choice1Of2 x + [] let Left x : Either<'a, 'b> = Choice2Of2 x let (|Right|Left|) = diff --git a/AltCover/Cobertura.fs b/AltCover/Cobertura.fs index 1b6afb2d7..cd1c5418a 100644 --- a/AltCover/Cobertura.fs +++ b/AltCover/Cobertura.fs @@ -17,6 +17,9 @@ module internal Cobertura = let ratio = (float hits) / (float total) target.SetAttributeValue(X rate, String.Format("{0:0.##}", ratio)) + [] let AddSources (report : XDocument) (target : XElement) tag attribute = report.Descendants(X tag) |> Seq.map (fun s -> s.Attribute(X attribute).Value |> Path.GetDirectoryName) diff --git a/AltCover/CommandLine.fs b/AltCover/CommandLine.fs index 803ee20c0..5918a89d8 100644 --- a/AltCover/CommandLine.fs +++ b/AltCover/CommandLine.fs @@ -45,7 +45,7 @@ module internal Process = open Process #endif -type internal StringSink = delegate of string -> unit +type internal StringSink = Action // delegate of string -> unit [] type internal UsageInfo = @@ -59,9 +59,6 @@ module internal Output = let mutable internal Echo : String -> unit = ignore let mutable internal Error : String -> unit = ignore let mutable internal Usage : UsageInfo -> unit = ignore - let internal SetInfo(x : StringSink) = Info <- x.Invoke - let internal SetError(x : StringSink) = Error <- x.Invoke - let internal SetWarn(x : StringSink) = Warn <- x.Invoke let internal WarnOn x = if x then Warn else Info @@ -123,7 +120,7 @@ module internal CommandLine = let enquotes = Map.empty |> Map.add "Windows_NT" "\"" - let internal Usage u = + let internal UsageBase u = WriteColoured Console.Error ConsoleColor.Yellow (fun w -> if u.Options.Any() || u.Options2.Any() then w.WriteLine(resources.GetString u.Intro) if u.Options.Any() then u.Options.WriteOptionDescriptions(w) @@ -233,6 +230,9 @@ module internal CommandLine = if help then Left("HelpText", options) else parse | fail -> fail + [] let internal ProcessTrailingArguments (rest : string list) (toInfo : DirectoryInfo) = // If we have some arguments in rest execute that command line match rest |> Seq.toList with @@ -285,7 +285,7 @@ module internal CommandLine = String.Join(" ", arguments |> Seq.map (sprintf "%A")) |> Output.Echo Output.Echo String.Empty ReportErrors String.Empty extend - Usage info + Output.Usage info let internal ValidateFileSystemEntity exists message key x = doPathOperation (fun () -> @@ -350,7 +350,7 @@ module internal CommandLine = else (StrongNameKeyData.Empty(), false) - let internal ValidateRegexes(x : String) = + let private stripNulls (x : String) = let descape (s : string) = s.Replace(char 0, ';') let qRegex (s : String) = @@ -361,13 +361,19 @@ module internal CommandLine = { Regex = Regex s Sense = Exclude } - doPathOperation (fun () -> - x.Replace(";;", "\u0000").Split([| ";" |], StringSplitOptions.RemoveEmptyEntries) - |> Array.map (descape >> qRegex)) [||] false + let transform array = + array + |> Array.map (descape >> qRegex) + + x.Replace(";;", "\u0000").Split([| ";" |], StringSplitOptions.RemoveEmptyEntries) + |> transform + + let internal ValidateRegexes(x : String) = + doPathOperation (fun () -> stripNulls x) [||] false let internal ddFlag (name : string) flag = (name, - (fun _ -> + (fun (_:string) -> if !flag then error <- String.Format diff --git a/AltCover/Filter.fs b/AltCover/Filter.fs index 4dcfdd594..324f1805b 100644 --- a/AltCover/Filter.fs +++ b/AltCover/Filter.fs @@ -32,7 +32,8 @@ type internal StaticFilter = | AsCovered | Hidden -[] +[] type internal FilterRegex = { Regex : Regex Sense : FilterSense } diff --git a/AltCover/Instrument.fs b/AltCover/Instrument.fs index 5d54b6a18..83fd31d8e 100644 --- a/AltCover/Instrument.fs +++ b/AltCover/Instrument.fs @@ -56,11 +56,12 @@ module internal Instrument = ResourceManager("AltCover.JSONFragments", Assembly.GetExecutingAssembly()) let version = typeof.Assembly.GetName().Version.ToString() +#if NETCOREAPP2_0 +#else let monoRuntime = - "Mono.Runtime" - |> Type.GetType - |> isNull - |> not + ("Mono.Runtime" + |> Type.GetType).IsNotNull +#endif let dependencies = (resources.GetString "frameworkDependencies").Replace("version", version) @@ -111,6 +112,9 @@ module internal Instrument = /// /// The name of the assembly /// A key, if we have a match. + [] let internal KnownKey(name : AssemblyNameDefinition) = if not name.HasPublicKey then None @@ -138,6 +142,9 @@ module internal Instrument = // This trivial extraction appeases Gendarme let private extractName (assembly : AssemblyDefinition) = assembly.Name.Name + [] let Guard (assembly : AssemblyDefinition) (f : unit -> unit) = try f() @@ -150,6 +157,9 @@ module internal Instrument = /// Create the new assembly that will record visits, based on the prototype. /// /// A representation of the assembly used to record all coverage visits. + [] let internal PrepareAssembly(location : string) = let definition = AssemblyDefinition.ReadAssembly(location) Guard definition (fun () -> // set the timer interval in ticks @@ -234,7 +244,7 @@ module internal Instrument = let share = "|usr|share".Replace('|', Path.DirectorySeparatorChar) let shared = "dotnet|shared".Replace('|', Path.DirectorySeparatorChar) - let candidate = + let sources = [ Environment.GetEnvironmentVariable "NUGET_PACKAGES" Path.Combine (Environment.GetEnvironmentVariable "ProgramFiles" @@ -242,6 +252,9 @@ module internal Instrument = |> (Option.getOrElse share), shared) Path.Combine(share, shared) nugetCache ] + + let candidate source = + source |> List.filter (String.IsNullOrWhiteSpace >> not) |> List.filter Directory.Exists |> Seq.distinct @@ -256,7 +269,7 @@ module internal Instrument = |> Seq.filter (fun f -> y.ToString().Equals(CommandLine.FindAssemblyName f, StringComparison.Ordinal)) |> Seq.tryHead - match candidate with + match candidate sources with | None -> null | Some x -> String.Format @@ -270,9 +283,7 @@ module internal Instrument = let internal HookResolveHandler = new AssemblyResolveEventHandler(ResolveFromNugetCache) let internal HookResolver(resolver : IAssemblyResolver) = - if resolver - |> isNull - |> not + if resolver.IsNotNull then let hook = resolver.GetType().GetMethod("add_ResolveFailure") hook.Invoke(resolver, [| HookResolveHandler :> obj |]) |> ignore @@ -345,6 +356,10 @@ module internal Instrument = finally Directory.SetCurrentDirectory(here) + [] type internal SubstituteInstruction(oldValue : Instruction, newValue : Instruction) = /// /// Adjust the IL for exception handling @@ -494,7 +509,7 @@ module internal Instrument = let private VisitModule (state : InstrumentContext) (m : ModuleDefinition) included = let restate = - match included <> Inspect.Ignore with + match included <> Inspections.Ignore with | true -> let recordingMethod = match state.RecordingMethod with @@ -539,9 +554,7 @@ module internal Instrument = state let internal VisitBranchPoint (state : InstrumentContext) branch = - if branch.Included && state.MethodWorker - |> isNull - |> not + if branch.Included && state.MethodWorker.IsNotNull then let point = (branch.Uid ||| Base.Counter.BranchFlag) @@ -703,12 +716,18 @@ module internal Instrument = Track state m included track state + [] let private VisitAfterAssembly state (assembly : AssemblyDefinition) (paths : string list) = let originalFileName = Path.GetFileName assembly.MainModule.FileName WriteAssemblies assembly originalFileName paths Output.Info state + [] let private VisitStart state = let recorder = typeof let recordingAssembly = PrepareAssembly(recorder.Assembly.Location) @@ -725,7 +744,7 @@ module internal Instrument = | Start _ -> VisitStart state | Assembly(assembly, included, _) -> UpdateStrongReferences assembly state.InstrumentedAssemblies |> ignore - if included <> Inspect.Ignore then + if included <> Inspections.Ignore then assembly.MainModule.AssemblyReferences.Add(state.RecordingAssembly.Name) state | Module(m, included) -> VisitModule state m included diff --git a/AltCover/LCov.fs b/AltCover/LCov.fs index 9a1674fb6..e5b8d51d4 100644 --- a/AltCover/LCov.fs +++ b/AltCover/LCov.fs @@ -14,6 +14,9 @@ module internal LCov = let X = OpenCover.X + [] let lineOfMethod (m : XElement) = (m.Descendants(X "seqpnt") |> Seq.head).Attribute(X "line").Value |> Int32.TryParse diff --git a/AltCover/Main.fs b/AltCover/Main.fs index 3d00d77d7..6a2a639ea 100644 --- a/AltCover/Main.fs +++ b/AltCover/Main.fs @@ -3,12 +3,16 @@ namespace AltCover module internal AltCover = let internal ToConsole() = Output.Error <- CommandLine.WriteErr - Output.Usage <- CommandLine.Usage + Output.Usage <- CommandLine.UsageBase Output.Echo <- CommandLine.WriteErr Output.Info <- CommandLine.WriteOut Output.Warn <- CommandLine.WriteOut [] + [] let private Main arguments = ToConsole() AltCover.Main.EffectiveMain arguments \ No newline at end of file diff --git a/AltCover/Naming.fs b/AltCover/Naming.fs index 868f9ec19..ec69cc7ed 100644 --- a/AltCover/Naming.fs +++ b/AltCover/Naming.fs @@ -13,7 +13,13 @@ module internal Naming = let suffixIfNotIsNullOrWhiteSpace name suffix = if String.IsNullOrWhiteSpace name then String.Empty else (name + suffix) + [] let TypeName(def : TypeDefinition) = emptyIfIsNullOrWhiteSpace def.Name + [] let TypeRefName(def : TypeReference) = emptyIfIsNullOrWhiteSpace def.Name let rec FullTypeName(def : TypeDefinition) = @@ -69,4 +75,4 @@ module internal Naming = (if generic then ">" else String.Empty) "(" parameters - ")" ]) + ")" ]) \ No newline at end of file diff --git a/AltCover/OpenCover.fs b/AltCover/OpenCover.fs index 56c1255fa..36efd6f75 100644 --- a/AltCover/OpenCover.fs +++ b/AltCover/OpenCover.fs @@ -139,7 +139,7 @@ module internal OpenCover = let VisitType (s : OpenCoverContext) (typeDef : TypeDefinition) included = let instrumented = Visitor.IsInstrumented included let methods = XElement(X "Methods") - if included <> Inspect.TrackOnly then + if included <> Inspections.TrackOnly then let element = XElement(X "Class") if not instrumented then element.SetAttributeValue(X "skippedDueTo", "Filter") let head = s.Stack |> Seq.head @@ -186,7 +186,7 @@ module internal OpenCover = seqpnts let VisitMethod (s : OpenCoverContext) (methodDef : MethodDefinition) included = - if s.Excluded = Nothing && included <> Inspect.TrackOnly then + if s.Excluded = Nothing && included <> Inspections.TrackOnly then let instrumented = Visitor.IsInstrumented included let cc, element = methodElement methodDef if instrumented then element.SetAttributeValue(X "skippedDueTo", "File") @@ -381,7 +381,7 @@ module internal OpenCover = let VisitAfterMethod (s : OpenCoverContext) methodDef track included = AddTracking s methodDef track - if s.Excluded = Nothing && included <> Inspect.TrackOnly then + if s.Excluded = Nothing && included <> Inspections.TrackOnly then let tail, skipped = VisitAfterMethodIncluded s if skipped |> not then UpdateClassCountsByMethod s tail diff --git a/AltCover/ProgramDatabase.fs b/AltCover/ProgramDatabase.fs index 8c056e23c..43825c59d 100644 --- a/AltCover/ProgramDatabase.fs +++ b/AltCover/ProgramDatabase.fs @@ -4,6 +4,7 @@ open System open System.Collections.Generic open System.IO +open Augment open Mono.Cecil open Mono.Cecil.Cil open Mono.Cecil.Mdb @@ -39,9 +40,7 @@ module internal ProgramDatabase = |> Option.filter (fun s -> s.Length > 0) |> Option.filter (fun s -> File.Exists s || (s = (assembly.Name.Name + ".pdb") && (assembly - |> GetEmbeddedPortablePdbEntry - |> isNull - |> not))) + |> GetEmbeddedPortablePdbEntry).IsNotNull)) let GetSymbolsByFolder fileName folderName = let name = Path.Combine(folderName, fileName) diff --git a/AltCover/Runner.fs b/AltCover/Runner.fs index 9c4820376..241d06a72 100644 --- a/AltCover/Runner.fs +++ b/AltCover/Runner.fs @@ -90,6 +90,9 @@ module internal Runner = let line = String.Format(CultureInfo.InvariantCulture, template, what, value) Write line + [] let NCoverSummary(report : XDocument) = let makepc v n = if n = 0 then @@ -158,6 +161,9 @@ module internal Runner = makepc vpoints points.Length + [] let AltSummary(report : XDocument) = "Alternative" |> CommandLine.resources.GetString @@ -483,8 +489,14 @@ module internal Runner = | fail -> fail // mocking point + [] let mutable internal RecorderName = "AltCover.Recorder.g.dll" + [] let RecorderInstance() = let recorderPath = Path.Combine(Option.get recordingDirectory, RecorderName) let definition = AssemblyDefinition.ReadAssembly recorderPath @@ -663,6 +675,9 @@ module internal Runner = |> Seq.collect (fun p -> p.Attributes |> Seq.cast) |> Seq.iter (fun a -> m.SetAttribute(a.Name, a.Value))) + [] let internal LookUpVisitsByToken token (dict : Dictionary) = let (ok, index) = Int32.TryParse @@ -698,6 +713,9 @@ module internal Runner = <> 0L) |> Seq.length + [] let internal TryGetValue (d : Dictionary<'a, 'b>) (key : 'a) = match d with | null -> (false, Unchecked.defaultof<'b>) @@ -910,8 +928,17 @@ module internal Runner = report = AltCover.Base.Counter.DoFlush (PostProcess hits report) PointProcess true hits report // mocking points + [] let mutable internal GetPayload = PayloadBase + [] let mutable internal GetMonitor = MonitorBase + [] let mutable internal DoReport = WriteReportBase let DoSummaries (document : XDocument) (format : Base.ReportFormat) result = diff --git a/AltCover/Tasks.fs b/AltCover/Tasks.fs index 77a008e0b..cbe3680cc 100644 --- a/AltCover/Tasks.fs +++ b/AltCover/Tasks.fs @@ -52,6 +52,9 @@ module Api = [] type Prepare() = inherit Task(null) + [] member val internal ACLog : FSApi.Logging option = None with get, set member val InputDirectories : string array = [||] with get, set @@ -130,6 +133,9 @@ type Prepare() = type Collect() = inherit Task(null) + [] member val internal ACLog : FSApi.Logging option = None with get, set [] @@ -147,7 +153,9 @@ type Collect() = [] [] + "Instance property needed"); + System.Diagnostics.CodeAnalysis.SuppressMessage("Gendarme.Rules.Correctness", + "MethodCanBeMadeStaticRule")>] member self.Summary = Api.Summary() member self.Message x = base.Log.LogMessage(MessageImportance.High, x) @@ -178,6 +186,9 @@ type Collect() = type PowerShell() = inherit Task(null) + [] member val internal IO = FSApi.Logging.Primitive { Primitive.Logging.Create() with Error = base.Log.LogError @@ -192,6 +203,9 @@ type PowerShell() = type GetVersion() = inherit Task(null) + [] member val internal IO = FSApi.Logging.Primitive { Primitive.Logging.Create() with Error = base.Log.LogError @@ -233,6 +247,9 @@ type RunSettings() = [] member val Extended = String.Empty with get, set + [] member val internal DataCollector = "AltCover.DataCollector.dll" with get, set override self.Execute() = diff --git a/AltCover/Visitor.fs b/AltCover/Visitor.fs index fbe9681f6..15958f892 100644 --- a/AltCover/Visitor.fs +++ b/AltCover/Visitor.fs @@ -22,7 +22,11 @@ open Newtonsoft.Json.Linq open System.Net [] -type internal Inspect = +[] +type internal Inspections = | Ignore = 0 | Instrument = 1 | Track = 2 @@ -76,13 +80,13 @@ type internal GoTo = [] type internal Node = | Start of seq - | Assembly of AssemblyDefinition * Inspect * string list - | Module of ModuleDefinition * Inspect - | Type of TypeDefinition * Inspect * Exemption - | Method of MethodDefinition * Inspect * (int * string) option * Exemption + | Assembly of AssemblyDefinition * Inspections * string list + | Module of ModuleDefinition * Inspections + | Type of TypeDefinition * Inspections * Exemption + | Method of MethodDefinition * Inspections * (int * string) option * Exemption | MethodPoint of Instruction * SeqPnt option * int * bool * Exemption | BranchPoint of GoTo - | AfterMethod of MethodDefinition * Inspect * (int * string) option + | AfterMethod of MethodDefinition * Inspections * (int * string) option | AfterType | AfterModule | AfterAssembly of AssemblyDefinition * string list @@ -204,7 +208,9 @@ module internal KeyStore = |> hash.ComputeHash |> BitConverter.ToString -[] +[] type Fix<'T> = delegate of 'T -> Fix<'T> module internal Visitor = @@ -334,15 +340,15 @@ module internal Visitor = let IsIncluded(nameProvider : Object) = if (NameFilters |> Seq.exists (Filter.Match nameProvider)) || localFilter nameProvider then - Inspect.Ignore + Inspections.Ignore else - Inspect.Instrument + Inspections.Instrument - let Mask = ~~~Inspect.Instrument + let Mask = ~~~Inspections.Instrument let UpdateInspection before x = - (before &&& Mask) ||| (before &&& Inspect.Instrument &&& IsIncluded x) - let IsInstrumented x = (x &&& Inspect.Instrument) = Inspect.Instrument + (before &&& Mask) ||| (before &&& Inspections.Instrument &&& IsIncluded x) + let IsInstrumented x = (x &&& Inspections.Instrument) = Inspections.Instrument let ToSeq node = List.toSeq [ node ] let mutable private PointNumber : int = 0 @@ -449,11 +455,11 @@ module internal Visitor = let inspection = IsIncluded x let included = - inspection ||| if inspection = Inspect.Instrument + inspection ||| if inspection = Inspections.Instrument && ReportFormat() = Base.ReportFormat.OpenCoverWithTracking then - Inspect.Track + Inspections.Track else - Inspect.Ignore + Inspections.Ignore Assembly(x, included, targets) path @@ -461,7 +467,7 @@ module internal Visitor = >> makeInspection >> buildSequence)) - let private VisitAssembly (a : AssemblyDefinition) included buildSequence = + let private VisitAssembly (a : AssemblyDefinition) included (buildSequence : Node -> seq) = a.Modules |> Seq.cast |> Seq.collect @@ -469,7 +475,7 @@ module internal Visitor = let interim = UpdateInspection included x Module (x, - (if interim = Inspect.Track then Inspect.TrackOnly else interim))) + (if interim = Inspections.Track then Inspections.TrackOnly else interim))) >> buildSequence) let private ZeroPoints() = @@ -482,7 +488,7 @@ module internal Visitor = then Exemption.Automatic else exemption - let private VisitModule (x : ModuleDefinition) included buildSequence = + let private VisitModule (x : ModuleDefinition) included (buildSequence : Node -> seq) = ZeroPoints() SourceLinkDocuments <- Some x @@ -497,7 +503,7 @@ module internal Visitor = JsonConvert.DeserializeObject>(j.ToString())) [ x ] - |> Seq.takeWhile (fun _ -> included <> Inspect.Ignore) + |> Seq.takeWhile (fun _ -> included <> Inspections.Ignore) |> Seq.collect (fun x -> x.GetAllTypes() |> Seq.cast) |> Seq.collect ((fun t -> @@ -608,6 +614,9 @@ module internal Visitor = let tn = (i.Operand :?> MethodReference).DeclaringType SameType t tn) + [] let private FSharpContainingMethod (t : TypeDefinition) (tx : TypeReference) = let candidates = t.DeclaringType.Methods.Concat @@ -689,7 +698,7 @@ module internal Visitor = else if !showGenerated then SelectAutomatic items exemption else exemption - let private VisitType (t : TypeDefinition) included basevc buildSequence = + let private VisitType (t : TypeDefinition) included basevc (buildSequence : Node -> seq) = t.Methods |> Seq.cast |> Seq.filter (fun (m : MethodDefinition) -> @@ -720,17 +729,13 @@ module internal Visitor = >> buildSequence) let IsSequencePoint(s : SequencePoint) = - (s - |> isNull - |> not) + s.IsNotNull && s.IsHidden |> not let fakeSequencePoint genuine (seq : SequencePoint) (instruction : Instruction) = match seq with | null -> - if genuine = FakeAfterReturn && instruction - |> isNull - |> not + if genuine = FakeAfterReturn && instruction.IsNotNull && instruction.OpCode = OpCodes.Ret then SequencePoint(instruction, Document(null)) else @@ -913,9 +918,7 @@ module internal Visitor = |> indexList)) ([ rawInstructions |> Seq.cast ] |> Seq.filter (fun _ -> - dbg - |> isNull - |> not) + dbg.IsNotNull) |> Seq.concat |> Seq.filter (fun (i : Instruction) -> i.OpCode.FlowControl = FlowControl.Cond_Branch) @@ -950,16 +953,14 @@ module internal Visitor = |> Seq.map BranchPoint |> Seq.toList - let private VisitMethod (m : MethodDefinition) (included : Inspect) vc = + let private VisitMethod (m : MethodDefinition) (included : Inspections) vc = let rawInstructions = m.Body.Instructions let dbg = m.DebugInformation let instructions = [ rawInstructions |> Seq.cast ] |> Seq.filter (fun _ -> - dbg - |> isNull - |> not) + dbg.IsNotNull) |> Seq.concat |> Seq.filter (fun (x : Instruction) -> if dbg.HasSequencePoints then @@ -1052,7 +1053,7 @@ module internal Visitor = accumulator |> Seq.iter (fun a -> (a :> IDisposable).Dispose()) accumulator.Clear() - let EncloseState (visitor : 'State -> 'T -> 'State) (current : 'State) = + let EncloseState (visitor : 'TState -> 'T -> 'TState) (current : 'TState) = let rec stateful l = new Fix<'T>(fun (node : 'T) -> let next = visitor l node diff --git a/Build/Pester.Tests.ps1 b/Build/Pester.Tests.ps1 index aaaef2d1c..39491a193 100644 --- a/Build/Pester.Tests.ps1 +++ b/Build/Pester.Tests.ps1 @@ -32,25 +32,16 @@ Describe "Invoke-Altcover" { } It "Fails on garbage" { - $saved = [System.Console]::Error - $stderr = new-object System.IO.StringWriter @() - [System.Console]::SetError($stderr) try { $ev = "" Invoke-AltCover -XmlReport $x -OutputDirectory $o -InputDirectory "./NoneSuch/xunit-dotnet/bin/Debug/netcoreapp2.0" -InPlace -ErrorVariable ev -ErrorAction SilentlyContinue } - catch { - $ev | Should -BeTrue - $stderr.ToString() | Should -BeTrue - } finally { - [System.Console]::SetError($saved) - } - - $ev | Should -BeTrue - $stderr.ToString() | Should -BeTrue + $ev | Should -Be ("--inputDirectory : Directory ./NoneSuch/xunit-dotnet/bin/Debug/netcoreapp2.0 not found" + + [Environment]::NewLine +"255") + } } It "Reports the version" { diff --git a/Build/build.fsx.lock b/Build/build.fsx.lock index 63c582673..aa4459cc2 100644 --- a/Build/build.fsx.lock +++ b/Build/build.fsx.lock @@ -2,7 +2,11 @@ STORAGE: NONE RESTRICTION: == netstandard2.0 NUGET remote: https://api.nuget.org/v3/index.json - AltCode.Fake.DotNet.Gendarme (5.9.3.10) + AltCode.Fake.DotNet.Gendarme (5.18.1.24) + Fake.Core.Environment (>= 5.18.1) + Fake.DotNet.Cli (>= 5.18.1) + FSharp.Core (>= 4.7) + System.Collections.Immutable (>= 1.6) BlackFox.CommandLine (1.0) FSharp.Core (>= 4.2.3) BlackFox.VsWhere (1.0) @@ -157,12 +161,13 @@ NUGET FSharp.Core (>= 4.7) FParsec (1.1.1) FSharp.Core (>= 4.3.4) - FSharp.Compiler.Service (34.0.1) + FSharp.Compiler.Service (34.1) FSharp.Core (>= 4.6.2) System.Buffers (>= 4.5) System.Collections.Immutable (>= 1.5) System.Diagnostics.Process (>= 4.1) System.Diagnostics.TraceSource (>= 4.0) + System.Memory (>= 4.5.3) System.Reflection.Emit (>= 4.3) System.Reflection.Metadata (>= 1.6) System.Reflection.TypeExtensions (>= 4.3) @@ -172,10 +177,10 @@ NUGET FSharp.Core (>= 4.2.3) System.Reactive (>= 4.0) FSharp.Core (4.7) - FSharpLint.Core (0.12.10) + FSharpLint.Core (0.13.3) Dotnet.ProjInfo (>= 0.31) FParsec (>= 1.0.3) - FSharp.Compiler.Service (>= 33.0) + FSharp.Compiler.Service (>= 34.1) FSharp.Core (>= 4.6.2) Newtonsoft.Json (>= 12.0.2) Markdown (2.2.1) diff --git a/Build/rules.xml b/Build/common-rules.xml similarity index 50% rename from Build/rules.xml rename to Build/common-rules.xml index a35094fd9..723a59f48 100644 --- a/Build/rules.xml +++ b/Build/common-rules.xml @@ -1,45 +1,55 @@ + + + + + + + + + exclude="MonoCompatibilityReviewRule" + from="Gendarme.Rules.Portability.dll" /> + + diff --git a/Build/rules-posh.xml b/Build/csharp-rules.xml similarity index 64% rename from Build/rules-posh.xml rename to Build/csharp-rules.xml index efe3b36e2..5852a1e55 100644 --- a/Build/rules-posh.xml +++ b/Build/csharp-rules.xml @@ -1,14 +1,15 @@ + + @@ -19,27 +20,29 @@ + + + + - + \ No newline at end of file diff --git a/Build/dotnet-cli.csproj b/Build/dotnet-cli.csproj index 102c0cb40..ba16c4390 100644 --- a/Build/dotnet-cli.csproj +++ b/Build/dotnet-cli.csproj @@ -1,4 +1,4 @@ - + net47 @@ -9,13 +9,13 @@ - + all runtime; build; native; contentfiles; analyzers - + diff --git a/Build/rules-fake.xml b/Build/rules-fake.xml deleted file mode 100644 index 4900d8bc8..000000000 --- a/Build/rules-fake.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Build/rules-gtk.xml b/Build/rules-gtk.xml deleted file mode 100644 index 24a52284c..000000000 --- a/Build/rules-gtk.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Build/setup.fsx b/Build/setup.fsx index cc54c5e9d..6428f78d8 100644 --- a/Build/setup.fsx +++ b/Build/setup.fsx @@ -49,10 +49,10 @@ nuget Fake.DotNet.Testing.XUnit2 >= 5.19.1 nuget Fake.IO.FileSystem >= 5.19.1 nuget Fake.DotNet.Testing.Coverlet >= 5.19.1 nuget Fake.Testing.ReportGenerator >= 5.19.1 -nuget AltCode.Fake.DotNet.Gendarme >= 5.9.3.10 +nuget AltCode.Fake.DotNet.Gendarme >= 5.18.1.24 nuget BlackFox.CommandLine >= 1.0.0 nuget BlackFox.VsWhere >= 1.0.0 -nuget FSharpLint.Core >= 0.12.10 +nuget FSharpLint.Core >= 0.13.3 nuget Markdown >= 2.2.1 nuget NUnit >= 3.12.0 nuget YamlDotNet >= 8.1 //" diff --git a/Build/targets.fsx b/Build/targets.fsx index c3409d739..551488190 100644 --- a/Build/targets.fsx +++ b/Build/targets.fsx @@ -444,15 +444,10 @@ _Target "Lint" (fun _ -> let failOnIssuesFound (issuesFound: bool) = Assert.That(issuesFound, Is.False, "Lint issues were found") try - let settings = - Configuration.SettingsFileName - |> Path.getFullName - |> File.ReadAllText - - let lintConfig = - FSharpLint.Application.ConfigurationManagement.loadConfigurationFile settings let options = - { Lint.OptionalLintParameters.Default with Configuration = Some lintConfig } + { Lint.OptionalLintParameters.Default with Configuration = FromFile (Path.getFullName "./fsharplint.json") + //Configuration.SettingsFileName + } !!"**/*.fsproj" |> Seq.collect (fun n -> !!(Path.GetDirectoryName n @@ "*.fs")) @@ -460,15 +455,24 @@ _Target "Lint" (fun _ -> |> Seq.map (fun f -> match Lint.lintFile options f with | Lint.LintResult.Failure x -> failwithf "%A" x - | Lint.LintResult.Success w -> w) + | Lint.LintResult.Success w -> + w + |> Seq.filter (fun x -> + match x.Details.SuggestedFix with + | Some l -> match l.Force() with + | Some fix -> fix.FromText <> "AltCover_Fake" // special case + | _ -> false + | _ -> false)) |> Seq.concat |> Seq.fold (fun _ x -> - printfn "Info: %A\r\n Range: %A\r\n Fix: %A\r\n====" x.Info x.Range x.Fix + printfn "Info: %A\r\n Range: %A\r\n Fix: %A\r\n====" x.Details.Message x.Details.Range x.Details.SuggestedFix true) false |> failOnIssuesFound with - | :? System.MissingMethodException -> // TODO + | :? System.MissingMethodException -> printfn "MissingMethodException raised" + | :? System.ArgumentOutOfRangeException -> + printfn "ArgumentOutOfRangeException raised" | ex -> printfn "%A" ex reraise() @@ -484,6 +488,8 @@ _Target "Gendarme" (fun _ -> // Needs debug because release is compiled --standa ("_Binaries/AltCover.FSApi/Debug+AnyCPU/netstandard2.0/publish", "netstandard2.0", "./AltCover.FSApi/altcover.fsapi.core.fsproj") ("_Binaries/AltCover.Visualizer/Debug+AnyCPU/netcoreapp2.1/publish", "netcoreapp2.1", "./AltCover.Visualizer/altcover.visualizer.core.fsproj") ("_Binaries/AltCover.Fake.DotNet.Testing.AltCover/Debug+AnyCPU/netstandard2.0/publish", "netstandard2.0", "./AltCover.Fake.DotNet.Testing.AltCover/altcover.fake.dotnet.testing.altcover.core.fsproj") + ("_Binaries/AltCover.Cake/Debug+AnyCPU/netstandard2.0/publish", "netstandard2.0", "./AltCover.Cake/altcover.cake.core.csproj") + ("_Binaries/altcover.netcoreapp/Debug+AnyCPU/netcoreapp2.0/publish", "netcoreapp2.0", "./AltCover.NetCoreApp/altcover.netcoreapp.core.fsproj") ] |> Seq.iter (fun (pub, rt, proj) -> DotNet.publish (fun options -> { options with @@ -491,22 +497,23 @@ _Target "Gendarme" (fun _ -> // Needs debug because release is compiled --standa Configuration = DotNet.BuildConfiguration.Debug NoBuild = true MSBuildParams = { MSBuild.CliArguments.Create() with + DisableInternalBinLog = true Properties = [("AltCoverGendarme", "true")] } Framework = Some rt }) proj) - [ ("./Build/rules.xml", + [ ("./Build/common-rules.xml", [ "_Binaries/AltCover/Debug+AnyCPU/netcoreapp2.0/publish/AltCover.dll" - "_Binaries/AltCover.Shadow/Debug+AnyCPU/netstandard2.0/publish/AltCover.Shadow.dll" ]) - - ("./Build/rules-posh.xml", - [ "_Binaries/AltCover.PowerShell/Debug+AnyCPU/netstandard2.0/publish/AltCover.PowerShell.dll" - "_Binaries/AltCover.FSApi/Debug+AnyCPU/netstandard2.0/publish/AltCover.FSApi.dll" ]) - - ("./Build/rules-gtk.xml", - [ "_Binaries/AltCover.Visualizer/Debug+AnyCPU/netcoreapp2.1/publish/AltCover.Visualizer.dll" ]) - - ("./Build/rules-fake.xml", - [ "_Binaries/AltCover.Fake.DotNet.Testing.AltCover/Debug+AnyCPU/netstandard2.0/publish/AltCover.Fake.DotNet.Testing.AltCover.dll" ]) ] + "_Binaries/AltCover.Shadow/Debug+AnyCPU/netstandard2.0/publish/AltCover.Shadow.dll" + "_Binaries/AltCover.PowerShell/Debug+AnyCPU/netstandard2.0/publish/AltCover.PowerShell.dll" + "_Binaries/AltCover.FSApi/Debug+AnyCPU/netstandard2.0/publish/AltCover.FSApi.dll" + "_Binaries/AltCover.Visualizer/Debug+AnyCPU/netcoreapp2.1/publish/AltCover.Visualizer.dll" + "_Binaries/AltCover.Fake.DotNet.Testing.AltCover/Debug+AnyCPU/netstandard2.0/publish/AltCover.Fake.DotNet.Testing.AltCover.dll" + "_Binaries/altcover.netcoreapp/Debug+AnyCPU/netcoreapp2.0/publish/altcover.netcoreapp.dll" + ]) + ("./Build/csharp-rules.xml", + [ "_Binaries/AltCover.Cake/Debug+AnyCPU/netstandard2.0/publish/AltCover.Cake.dll" + "_Binaries/AltCover.Cake/Debug+AnyCPU/netstandard2.0/publish/AltCover.CSapi.dll" + ]) ] |> Seq.iter (fun (ruleset, files) -> Gendarme.run { Gendarme.Params.Create() with @@ -527,12 +534,12 @@ _Target "FxCop" (fun _ -> let rules = [ "-Microsoft.Design#CA1004" "-Microsoft.Design#CA1006" - "-Microsoft.Design#CA1011" // maybe sometimes + "-Microsoft.Design#CA1011" // reconsider @ Genbu; maybe sometimes "-Microsoft.Design#CA1062" // null checks, In F#! "-Microsoft.Maintainability#CA1506" - "-Microsoft.Naming#CA1704" - "-Microsoft.Naming#CA1707" - "-Microsoft.Naming#CA1709" + "-Microsoft.Naming#CA1704" // reconsider @ Genbu + "-Microsoft.Naming#CA1707" // reconsider @ Genbu + "-Microsoft.Naming#CA1709" // reconsider @ Genbu "-Microsoft.Naming#CA1715" "-Microsoft.Usage#CA2208" ] @@ -571,30 +578,30 @@ _Target "FxCop" (fun _ -> ([ "_Binaries/AltCover.PowerShell/Debug+AnyCPU/net47/AltCover.PowerShell.dll" ], [], [ "-Microsoft.Design#CA1059" "-Microsoft.Usage#CA2235" - "-Microsoft.Performance#CA1819" + "-Microsoft.Performance#CA1819" // reconsider @ genbu "-Microsoft.Design#CA1020" "-Microsoft.Design#CA1004" "-Microsoft.Design#CA1006" - "-Microsoft.Design#CA1011" + "-Microsoft.Design#CA1011" // reconsider @ Genbu "-Microsoft.Design#CA1062" "-Microsoft.Maintainability#CA1506" - "-Microsoft.Naming#CA1704" - "-Microsoft.Naming#CA1707" - "-Microsoft.Naming#CA1709" + "-Microsoft.Naming#CA1704" // reconsider @ Genbu + "-Microsoft.Naming#CA1707" // reconsider @ Genbu + "-Microsoft.Naming#CA1709" // reconsider @ Genbu "-Microsoft.Naming#CA1715" ]) ([ "_Binaries/AltCover.FSApi/Debug+AnyCPU/net45/AltCover.FSApi.dll" ], [], [ "-Microsoft.Usage#CA2235" - "-Microsoft.Performance#CA1819" + "-Microsoft.Performance#CA1819" // reconsider @ genbu "-Microsoft.Design#CA1020" "-Microsoft.Design#CA1034" "-Microsoft.Design#CA1004" "-Microsoft.Design#CA1006" - "-Microsoft.Design#CA1011" + "-Microsoft.Design#CA1011" // reconsider @ Genbu "-Microsoft.Design#CA1062" "-Microsoft.Maintainability#CA1506" - "-Microsoft.Naming#CA1704" - "-Microsoft.Naming#CA1707" - "-Microsoft.Naming#CA1709" + "-Microsoft.Naming#CA1704" // reconsider @ Genbu + "-Microsoft.Naming#CA1707" // reconsider @ Genbu + "-Microsoft.Naming#CA1709" // reconsider @ Genbu "-Microsoft.Naming#CA1715" ]) ([ "_Binaries/AltCover.Visualizer/Debug+AnyCPU/net45/AltCover.Visualizer.exe" ], [ "AltCover.Augment" @@ -623,14 +630,38 @@ _Target "FxCop" (fun _ -> "AltCover.Internals.DotNet" "AltCoverFake.DotNet.DotNet" ], [ "-Microsoft.Design#CA1006" - "-Microsoft.Design#CA1011" + "-Microsoft.Design#CA1011" // reconsider @ Genbu "-Microsoft.Design#CA1020" "-Microsoft.Design#CA1062" - "-Microsoft.Naming#CA1704" - "-Microsoft.Naming#CA1707" - "-Microsoft.Naming#CA1709" + "-Microsoft.Naming#CA1704" // reconsider @ Genbu + "-Microsoft.Naming#CA1707" // reconsider @ Genbu + "-Microsoft.Naming#CA1709" // reconsider @ Genbu "-Microsoft.Naming#CA1724" - "-Microsoft.Usage#CA2208" ]) ] + "-Microsoft.Usage#CA2208" ]) + ([ "_Binaries/AltCover.CSapi/Debug+AnyCPU/net45/AltCover.CSapi.dll" + //"_Binaries/altcover.netcoreapp/Debug+AnyCPU/netcoreapp2.0/altcover.netcoreapp.dll" + ], + [], + [ + "-Microsoft.Design#CA1011" // reconsider @ Genbu + "-Microsoft.Design#CA1020" + "-Microsoft.Naming#CA1704" // reconsider @ Genbu + "-Microsoft.Naming#CA1709" // reconsider @ Genbu + "-Microsoft.Performance#CA1819" // reconsider @ genbu + "-Microsoft.Naming#CA1716" // reconsider @ genbu + ]) + ([ "_Binaries/AltCover.Cake/Debug+AnyCPU/net46/AltCover.Cake.dll" + ], + [], + [ + "-Microsoft.Design#CA1011" // reconsider @ Genbu + "-Microsoft.Design#CA1020" + "-Microsoft.Design#CA1026" // can we suppress this one?? + "-Microsoft.Design#CA2210" // can't strongname this as Cake isn't strongnamed + "-Microsoft.Naming#CA1704" // reconsider @ Genbu + "-Microsoft.Naming#CA1709" // reconsider @ Genbu + "-Microsoft.Performance#CA1819" // reconsider @ genbu + ]) ] |> Seq.iter (fun (files, types, ruleset) -> files |> FxCop.run diff --git a/Recorder.Tests/Recorder.Tests.fs b/Recorder.Tests/Recorder.Tests.fs index 6e120d0fd..d42b66bb1 100644 --- a/Recorder.Tests/Recorder.Tests.fs +++ b/Recorder.Tests/Recorder.Tests.fs @@ -44,7 +44,7 @@ module AltCoverTests = let private UpdateReport a b = Adapter.UpdateReport(a, ReportFormat.NCover, b, b) |> ignore - let private PointVisitInit a b = PointVisit.Init(a, b) + let private PointVisitInit a b = Adapter.Init(a, b) let resource2 = Assembly.GetExecutingAssembly().GetManifestResourceNames() @@ -56,14 +56,6 @@ module AltCoverTests = let ShouldBeAbleToGetTheDefaultReportFileName() = Assert.True( Instance.ReportFile = "Coverage.Default.xml" ) - [] - let SafeDisposalProtects() = - let obj1 = - { new System.IDisposable with - member x.Dispose() = ObjectDisposedException("Bang!") |> raise } - Assist.SafeDispose obj1 - Assert.True( true ) - [] let DefaultAccessorsBehaveAsExpected() = let v1 = DateTime.UtcNow.Ticks @@ -355,31 +347,31 @@ module AltCoverTests = Instance.Visits.Clear()) GetMyMethodName "<=" - [] - let TabledVisitsShouldIncrementCount() = - GetMyMethodName "=>" - lock Instance.Visits (fun () -> - Adapter.Reset() - try - Instance.Visits.Clear() - let key = " " - Instance.VisitImpl(key, 23, (Adapter.Null())) - let table = Dictionary>() - table.Add(key, Dictionary()) - let payloads = - [ Adapter.Call 17 - Adapter.Time 23L - Adapter.NewBoth(5L, 42) ] - - let pv = PointVisitInit 42L payloads - table.[key].Add(23, pv) - let n = Counter.AddTable(Instance.Visits, table) - Assert.That(n, Is.EqualTo 45) - Assert.That(Instance.Visits.[key].[23].Count, Is.EqualTo 43) - Assert.That(Instance.Visits.[key].[23].Tracks, Is.EquivalentTo payloads) - finally - Instance.Visits.Clear()) - GetMyMethodName "<=" + //[] + //let TabledVisitsShouldIncrementCount() = + // GetMyMethodName "=>" + // lock Instance.Visits (fun () -> + // Adapter.Reset() + // try + // Instance.Visits.Clear() + // let key = " " + // Instance.VisitImpl(key, 23, (Adapter.Null())) + // let table = Dictionary>() + // table.Add(key, Dictionary()) + // let payloads = + // [ Adapter.Call 17 + // Adapter.Time 23L + // Adapter.NewBoth(5L, 42) ] + + // let pv = PointVisitInit 42L payloads + // table.[key].Add(23, pv) + // let n = Counter.AddTable(Instance.Visits, table) + // Assert.That(n, Is.EqualTo 45) + // Assert.That(Instance.Visits.[key].[23].Count, Is.EqualTo 43) + // Assert.That(Instance.Visits.[key].[23].Tracks, Is.EquivalentTo payloads) + // finally + // Instance.Visits.Clear()) + // GetMyMethodName "<=" [] let OldDocumentStartIsNotUpdated() = diff --git a/Recorder.Tests/Tracer.Tests.fs b/Recorder.Tests/Tracer.Tests.fs index 4c22012df..7f787c21a 100644 --- a/Recorder.Tests/Tracer.Tests.fs +++ b/Recorder.Tests/Tracer.Tests.fs @@ -30,7 +30,7 @@ module AltCoverCoreTests = let mutable client = Tracer.Create unique try client <- client.OnStart() - Assert.True(client.IsConnected() |> not) + Assert.True(client.IsConnected |> not) with _ -> client.Close() reraise() @@ -44,7 +44,7 @@ module AltCoverCoreTests = let mutable client = Tracer.Create unique try client <- client.OnStart() - Assert.True(client.IsConnected()) + Assert.True(client.IsConnected) finally client.Close() @@ -79,7 +79,7 @@ module AltCoverCoreTests = if pts > 0 then let p = formatter.ReadInt32() let n = formatter.ReadInt64() - let pv = PointVisit.Init(n, []) + let pv = Adapter.Init(n, []) t.[m].Add(p, pv) let rec tracking() = let track = formatter.ReadByte() |> int @@ -125,7 +125,7 @@ module AltCoverCoreTests = try Adapter.VisitsClear() Instance.trace <- client.OnStart() - Assert.True( Instance.trace.IsConnected(), "connection failed") + Assert.True( Instance.trace.IsConnected, "connection failed") Instance.IsRunner <- true Adapter.VisitImplNone("name", 23) finally @@ -157,8 +157,8 @@ module AltCoverCoreTests = [ Adapter.Time 17L Adapter.NewBoth(42L, 23) ] - t.["name"].[23] <- PointVisit.Init(1L, expect23) - t.["name"].[24] <- PointVisit.Init(2L, expect24) + t.["name"].[23] <- Adapter.Init(1L, expect23) + t.["name"].[24] <- Adapter.Init(2L, expect24) let expected = [ (String.Empty, 0, Adapter.Table t) @@ -169,7 +169,7 @@ module AltCoverCoreTests = let mutable client = Tracer.Create tag try Instance.trace <- client.OnStart() - Assert.True( Instance.trace.IsConnected(), "connection failed") + Assert.True( Instance.trace.IsConnected, "connection failed") Instance.IsRunner <- true Adapter.VisitsClear() @@ -258,7 +258,7 @@ module AltCoverCoreTests = Instance.trace <- client.OnStart() Assert.That(Instance.trace.Equals client, Is.False) Assert.That(Instance.trace.Equals expected, Is.False) - Assert.True(Instance.trace.IsConnected(), "connection failed") + Assert.True(Instance.trace.IsConnected, "connection failed") let formatter = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter() let (a, b, c) = expected |> Seq.head Instance.trace.Push(a, b, c) diff --git a/Tests.Visualizer/GtkVisualizerTests.fs b/Tests.Visualizer/GtkVisualizerTests.fs index b5e06c32d..4c4db1ad6 100644 --- a/Tests.Visualizer/GtkVisualizerTests.fs +++ b/Tests.Visualizer/GtkVisualizerTests.fs @@ -17,12 +17,11 @@ type AltCoverTests() = [] member self.AugmentNullableDetectNulls() = let input = [ "string"; null; "another string" ] - let nulls = input |> List.map (Option.nullable >> Option.isNone) + let nulls = input |> List.map (fun x -> x.IsNotNull |> not) test <@ nulls = [ false; true; false ] @> [] - member self.AugmentGetOrElseFillsInNone() = - let input = [ "string"; null; "another string" ] - let strings = input |> List.map (Option.nullable >> (Option.getOrElse "fallback")) - test <@ strings = [ "string"; "fallback"; "another string" ] @> + member self.AugmentNonNullableDetectNoNulls() = + let input = [ 1; 2 ;3 ] + test <@ input |> List.forall (fun x -> x.IsNotNull) @> end \ No newline at end of file diff --git a/Tests/Program.fs b/Tests/Program.fs index d0230c2a1..9589d2df4 100644 --- a/Tests/Program.fs +++ b/Tests/Program.fs @@ -1,6 +1,7 @@ namespace AltCover.Expecto.Tests #if NETCOREAPP3_0 +open AltCover.Augment open Expecto open Mono.Cecil open Mono.Cecil.Cil @@ -15,7 +16,6 @@ module TestMain = Tests.AltCoverRunnerTests.MaxTimeLast, "Runner.MaxTimeLast" Tests.AltCoverRunnerTests.MinTimeFirst, "Runner.MinTimeFirst" Tests.AltCoverRunnerTests.MinTimeLast, "Runner.MinTimeLast" - Tests.AltCoverRunnerTests.SafeDisposalProtects, "Runner.SafeDisposalProtects" Tests.AltCoverRunnerTests.JunkUspidGivesNegativeIndex, "Runner.JunkUspidGivesNegativeIndex" Tests.AltCoverRunnerTests.RealIdShouldIncrementCount, "Runner.RealIdShouldIncrementCount" Tests.AltCoverRunnerTests.RealIdShouldIncrementList, "Runner.RealIdShouldIncrementList" @@ -464,7 +464,7 @@ module TestMain = let testMethods = def.MainModule.GetTypes() |> Seq.collect (fun t -> t.Methods) - |> Seq.filter (fun m -> m.CustomAttributes |> isNull |> not) + |> Seq.filter (fun m -> m.CustomAttributes.IsNotNull) |> Seq.filter (fun m -> m.CustomAttributes |> Seq.exists (fun a -> a.AttributeType.Name = "TestAttribute")) |> Seq.map (fun m -> m.DeclaringType.FullName + "::" + m.Name) diff --git a/Tests/Runner.Tests.fs b/Tests/Runner.Tests.fs index 6837f30d6..08edab479 100644 --- a/Tests/Runner.Tests.fs +++ b/Tests/Runner.Tests.fs @@ -57,15 +57,6 @@ module AltCoverRunnerTests = let ago = now - TimeSpan(1,0,0,0) test <@ (Base.Counter.MinTime now ago) = ago @> - [] - let SafeDisposalProtects() = - Runner.init() - let obj1 = - { new System.IDisposable with - member x.Dispose() = ObjectDisposedException("Bang!") |> raise } - Assist.SafeDispose obj1 - test <@ true @> - #if NETCOREAPP2_0 #else [] @@ -179,6 +170,10 @@ module AltCoverRunnerTests = |> Seq.find (fun n -> n.EndsWith("Sample1WithOpenCover.xml", StringComparison.Ordinal)) + let internal Init n l = let tmp = { PointVisit.Create() with Count = n } + tmp.Tracks.AddRange l + tmp + #if NETCOREAPP2_0 #else [] @@ -197,8 +192,8 @@ module AltCoverRunnerTests = worker.Write(buffer, 0, size) worker.Position <- 0L let payload = Dictionary() - [ 0..9 ] |> Seq.iter (fun i -> payload.[10 - i] <- PointVisit.Init (int64(i + 1)) []) - [ 11..12 ] |> Seq.iter (fun i -> payload.[i ||| Counter.BranchFlag] <- PointVisit.Init (int64(i - 10)) []) + [ 0..9 ] |> Seq.iter (fun i -> payload.[10 - i] <- Init (int64(i + 1)) []) + [ 11..12 ] |> Seq.iter (fun i -> payload.[i ||| Counter.BranchFlag] <- Init (int64(i - 10)) []) let item = Dictionary>() item.Add("7C-CD-66-29-A3-6C-6D-5F-A7-65-71-0E-22-7D-B2-61-B5-1F-65-9A", payload) Counter.UpdateReport ignore (fun _ _ -> ()) true item ReportFormat.OpenCover worker @@ -244,7 +239,7 @@ module AltCoverRunnerTests = worker.Write(buffer, 0, size) () let payload = Dictionary() - [ 0..9 ] |> Seq.iter (fun i -> payload.[i] <- PointVisit.Init (int64(i + 1)) []) + [ 0..9 ] |> Seq.iter (fun i -> payload.[i] <- Init (int64(i + 1)) []) visits.["f6e3edb3-fb20-44b3-817d-f69d1a22fc2f"] <- payload Counter.DoFlush ignore (fun _ _ -> ()) true visits AltCover.Base.ReportFormat.NCover reportFile None |> ignore @@ -293,7 +288,7 @@ module AltCoverRunnerTests = worker.Write(buffer, 0, size) () let payload = Dictionary() - [ 0..9 ] |> Seq.iter (fun i -> payload.[i] <- PointVisit.Init (int64(i + 1)) []) + [ 0..9 ] |> Seq.iter (fun i -> payload.[i] <- Init (int64(i + 1)) []) visits.["f6e3edb3-fb20-44b3-817d-f69d1a22fc2f"] <- payload Counter.DoFlush ignore (fun _ _ -> ()) true visits AltCover.Base.ReportFormat.NCover reportFile (Some outputFile) |> ignore @@ -326,7 +321,7 @@ module AltCoverRunnerTests = use stderr = new StringWriter() Console.SetError stderr let empty = OptionSet() - CommandLine.Usage { Intro = "UsageError"; Options = empty; Options2 = options} + CommandLine.UsageBase { Intro = "UsageError"; Options = empty; Options2 = options} let result = stderr.ToString().Replace("\r\n", "\n") let expected = """Error - usage is: -r, --recorderDirectory=VALUE @@ -1901,11 +1896,11 @@ or Assert.That(File.Exists(unique + ".acv")) let expected = Dictionary>() let a = Dictionary() - a.Add(0, PointVisit.Init 1L []) + a.Add(0, Init 1L []) let b = Dictionary() - b.Add(1, PointVisit.Init 1L []) + b.Add(1, Init 1L []) let c = Dictionary() - c.Add(3, PointVisit.Init 1L []) + c.Add(3, Init 1L []) expected.Add ("a", a) expected.Add ("b", b) expected.Add ("c", c) @@ -1998,7 +1993,7 @@ or Base.Time 42L Base.Call 5 ] - let pv = PointVisit.Init 42L (payloads0 |> List.tail) + let pv = Init 42L (payloads0 |> List.tail) let table = Dictionary>() table.Add("Extra", Dictionary()) table.["Extra"].Add(3, pv) @@ -2191,8 +2186,8 @@ or let visits = Dictionary>() let visit = Dictionary() visits.Add("6A-33-AA-93-82-ED-22-9D-F8-68-2C-39-5B-93-9F-74-01-76-00-9F", visit) - visit.Add(100663297, PointVisit.Init 1L []) // should fill in the expected non-zero value - visit.Add(100663298, PointVisit.Init 23L []) // should be ignored + visit.Add(100663297, Init 1L []) // should fill in the expected non-zero value + visit.Add(100663298, Init 23L []) // should be ignored Runner.PostProcess visits Base.ReportFormat.OpenCover after Assert.That (after.OuterXml.Replace("uspid=\"100663298", "uspid=\"13"), Is.EqualTo before, @@ -2681,7 +2676,7 @@ or let baseline = XDocument.Load(stream) let excluded = XName.Get "excluded" baseline.Descendants() - |> Seq.iter (fun x -> if x.Attribute(excluded) |> isNull |> not then + |> Seq.iter (fun x -> if x.Attribute(excluded).IsNotNull then x.SetAttributeValue(excluded, "false")) let unique = Path.Combine @@ -2839,7 +2834,7 @@ or let baseline = XDocument.Load(stream) let excluded = XName.Get "excluded" baseline.Descendants() - |> Seq.iter (fun x -> if x.Attribute(excluded) |> isNull |> not then + |> Seq.iter (fun x -> if x.Attribute(excluded) .IsNotNull then x.SetAttributeValue(excluded, "false")) let unique = Path.Combine diff --git a/Tests/Tests.fs b/Tests/Tests.fs index 2097e12b5..6e1c84531 100644 --- a/Tests/Tests.fs +++ b/Tests/Tests.fs @@ -956,7 +956,7 @@ module AltCoverTests = Visitor.reportFormat <- Some Base.ReportFormat.OpenCover Visitor.NameFilters.Clear() let deeper = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.None) |> Seq.toList + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.None) |> Seq.toList Assert.That(deeper.Length, Is.EqualTo 3) deeper |> List.skip 1 @@ -1007,7 +1007,7 @@ module AltCoverTests = Visitor.reportFormat <- Some Base.ReportFormat.OpenCover Visitor.NameFilters.Clear() let deeper = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.Automatic) |> Seq.toList + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.Automatic) |> Seq.toList Assert.That(deeper.Length, Is.EqualTo 3) deeper |> List.skip 1 @@ -1361,12 +1361,12 @@ module AltCoverTests = let inputs = [ Node.Start [] - Node.Assembly(def, Inspect.Instrument, []) - Node.Module(null, Inspect.Ignore) - Node.Type(null, Inspect.Instrument, Exemption.None) - Node.Method(null, Inspect.Ignore, None, Exemption.None) + Node.Assembly(def, Inspections.Instrument, []) + Node.Module(null, Inspections.Ignore) + Node.Type(null, Inspections.Instrument, Exemption.None) + Node.Method(null, Inspections.Ignore, None, Exemption.None) Node.MethodPoint(null, None, 0, true, Exemption.None) - Node.AfterMethod(null, Inspect.Ignore, None) + Node.AfterMethod(null, Inspections.Ignore, None) Node.AfterModule Node.AfterAssembly (def, []) Node.Finish ] @@ -1378,7 +1378,7 @@ module AltCoverTests = [ AfterAssembly (def, []) ] [ AfterModule ] [ AfterType ] - [ AfterMethod(null, Inspect.Ignore, None) ] + [ AfterMethod(null, Inspections.Ignore, None) ] [] [] [] @@ -1418,7 +1418,7 @@ module AltCoverTests = let inputs = [ Node.MethodPoint(null, None, 0, true, Exemption.None) - Node.AfterMethod(null, Inspect.Ignore, None) + Node.AfterMethod(null, Inspections.Ignore, None) Node.AfterModule Node.AfterAssembly (def, []) Node.Finish ] @@ -1453,7 +1453,7 @@ module AltCoverTests = >> FilterClass.Build FilterScope.File >> Visitor.NameFilters.Add) let deeper = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.None) |> Seq.toList + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.None) |> Seq.toList Assert.That(deeper.Length, Is.EqualTo 12) deeper |> List.skip 10 @@ -1492,7 +1492,7 @@ module AltCoverTests = Visitor.reportFormat <- Some Base.ReportFormat.OpenCover Visitor.NameFilters.Clear() let deeper = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.Declared) + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.Declared) |> Seq.toList //deeper |> List.skip 21 |> Seq.iter (fun n -> match n with @@ -1553,7 +1553,7 @@ module AltCoverTests = Visitor.NameFilters.Clear() Visitor.coalesceBranches := true let deeper = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.StaticAnalysis) + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.StaticAnalysis) |> Seq.toList let reported = @@ -1599,14 +1599,14 @@ module AltCoverTests = >> FilterRegex.Exclude >> FilterClass.Build FilterScope.Method >> Visitor.NameFilters.Add) - let deeper = Visitor.Deeper <| Node.Type(type', Inspect.Instrument, Exemption.None) |> Seq.toList + let deeper = Visitor.Deeper <| Node.Type(type', Inspections.Instrument, Exemption.None) |> Seq.toList Visitor.Visit [] [] // cheat reset let expected = type'.Methods |> Seq.map (fun m -> let flag = - if m.Name = ".ctor" then Inspect.Instrument - else Inspect.Ignore + if m.Name = ".ctor" then Inspections.Instrument + else Inspections.Ignore let node = Node.Method(m, flag, None, Exemption.None) List.concat [ [ node ] @@ -1634,14 +1634,14 @@ module AltCoverTests = >> FilterClass.Build FilterScope.Type >> Visitor.NameFilters.Add) let deeper = - Visitor.Deeper <| Node.Module(module', Inspect.Instrument) |> Seq.toList + Visitor.Deeper <| Node.Module(module', Inspections.Instrument) |> Seq.toList Visitor.Visit [] [] // cheat reset let expected = module'.Types // we have no nested types in this test |> Seq.map (fun t -> let flag = - if t.Name <> "Program" then Inspect.Instrument - else Inspect.Ignore + if t.Name <> "Program" then Inspections.Instrument + else Inspections.Ignore let node = Node.Type(t, flag, Exemption.None) List.concat [ [ node ] @@ -1660,12 +1660,12 @@ module AltCoverTests = let def = Mono.Cecil.AssemblyDefinition.ReadAssembly path ProgramDatabase.ReadSymbols def Visitor.Visit [] [] // cheat reset - let deeper = Visitor.Deeper <| Node.Assembly(def, Inspect.Instrument, []) |> Seq.toList + let deeper = Visitor.Deeper <| Node.Assembly(def, Inspections.Instrument, []) |> Seq.toList Visitor.Visit [] [] // cheat reset let expected = def.Modules // we have no nested types in this test |> Seq.map (fun t -> - let node = Node.Module(t, Inspect.Instrument) + let node = Node.Module(t, Inspections.Instrument) List.concat [ [ node ] (Visitor.Deeper >> Seq.toList) node [ AfterModule ] ]) @@ -1684,12 +1684,12 @@ module AltCoverTests = // assembly definitions care about being separate references in equality tests let def = match Seq.head deeper with - | Node.Assembly(def', Inspect.Instrument, []) -> def' + | Node.Assembly(def', Inspections.Instrument, []) -> def' | _ -> Assert.Fail() null - let assembly = Node.Assembly(def, Inspect.Instrument, []) + let assembly = Node.Assembly(def, Inspections.Instrument, []) let expected = List.concat [ [ assembly ] @@ -1716,12 +1716,12 @@ module AltCoverTests = // assembly definitions care about being separate references in equality tests let def = match Seq.head deeper with - | Node.Assembly(def', Inspect.Ignore, []) -> def' + | Node.Assembly(def', Inspections.Ignore, []) -> def' | _ -> Assert.Fail() null - let assembly = Node.Assembly(def, Inspect.Ignore, []) + let assembly = Node.Assembly(def, Inspections.Ignore, []) let expected = List.concat [ [ assembly ] @@ -1786,12 +1786,12 @@ module AltCoverTests = // assembly definitions care about being separate references in equality tests let def = match accumulator.[1] with - | Node.Assembly(def', Inspect.Instrument, ux) -> def' + | Node.Assembly(def', Inspections.Instrument, ux) -> def' | _ -> Assert.Fail() null - let assembly = Node.Assembly(def, Inspect.Instrument, ux) + let assembly = Node.Assembly(def, Inspections.Instrument, ux) let expected = List.concat [ [ Start [ path, ux ] @@ -2370,7 +2370,7 @@ module AltCoverTests = >> FilterClass.Build FilterScope.File >> Visitor.NameFilters.Add) let branches = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.None) + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.None) |> Seq.map (fun n -> match n with | BranchPoint b -> Some b diff --git a/Tests/Tests2.fs b/Tests/Tests2.fs index d55a0ef28..6e435d687 100644 --- a/Tests/Tests2.fs +++ b/Tests/Tests2.fs @@ -7,6 +7,7 @@ open System.Security open System.Security.Cryptography open AltCover +open AltCover.Augment open Mono.Cecil open Mono.Cecil.Cil open Mono.Cecil.Rocks @@ -334,7 +335,7 @@ module AltCoverTests2 = (fun f -> f.Name.IndexOf("Mono.Cecil", StringComparison.Ordinal) >= 0) |> Seq.iter (fun f -> let resolved = Instrument.HookResolveHandler.Invoke(null, f) - test' <@ resolved |> isNull |> not @> <| f.ToString()) + test' <@ resolved.IsNotNull @> <| f.ToString()) raw.MainModule.AssemblyReferences |> Seq.filter (fun f -> f.Name.IndexOf("Mono.Cecil", StringComparison.Ordinal) >= 0) @@ -355,7 +356,7 @@ module AltCoverTests2 = |> Seq.iter (fun f -> f.Version <- System.Version("666.666.666.666") let resolved = Instrument.HookResolveHandler.Invoke(null, f) - test' <@ resolved |> isNull |> not @> <| f.ToString()) + test' <@ resolved .IsNotNull @> <| f.ToString()) finally Instrument.ResolutionTable.Clear() @@ -489,7 +490,7 @@ module AltCoverTests2 = " " + alter + " <= Sample3.g, Version=0.0.0.0, Culture=neutral, PublicKeyToken=4ebffcaabf10ce6a" ] Assert.That(traces, Is.EquivalentTo expectedTraces) - let expectedSymbols = if "Mono.Runtime" |> Type.GetType |> isNull |> not then ".dll.mdb" else ".pdb" + let expectedSymbols = if ("Mono.Runtime" |> Type.GetType).IsNotNull then ".dll.mdb" else ".pdb" let isWindows = #if NETCOREAPP2_0 false // recorder symbols not read here @@ -931,7 +932,7 @@ module AltCoverTests2 = |> Seq.length let handlersBefore = recorder.Head.Body.ExceptionHandlers.Count - AltCover.Instrument.Track state recorder.Head Inspect.Track <| Some(42, "hello") + AltCover.Instrument.Track state recorder.Head Inspections.Track <| Some(42, "hello") Assert.That (recorder.Head.Body.Instructions.Count, Is.EqualTo(countBefore + 5 - tailsBefore)) Assert.That @@ -977,7 +978,7 @@ module AltCoverTests2 = |> Seq.length let handlersBefore = target.Body.ExceptionHandlers.Count - AltCover.Instrument.Track state target Inspect.Track <| Some(42, "hello") + AltCover.Instrument.Track state target Inspections.Track <| Some(42, "hello") Assert.That (target.Body.Instructions.Count, Is.EqualTo(countBefore + 5 - tailsBefore)) Assert.That(target.Body.ExceptionHandlers.Count, Is.EqualTo(handlersBefore + 1)) @@ -1030,7 +1031,7 @@ module AltCoverTests2 = |> Array.map (fun i -> i.Offset) Assert.That (targets, Is.EquivalentTo [ 31; 33; 31; 33; 31 ]) - let m = Node.Method (target, Inspect.Instrument, None, Exemption.None) + let m = Node.Method (target, Inspections.Instrument, None, Exemption.None) let steps = Visitor.BuildSequence m Assert.That(steps, Is.Not.Empty) @@ -1082,7 +1083,7 @@ module AltCoverTests2 = let state = AltCover.InstrumentContext.Build([]) let countBefore = recorder.Head.Body.Instructions.Count let handlersBefore = recorder.Head.Body.ExceptionHandlers.Count - AltCover.Instrument.Track state recorder.Head Inspect.Track None + AltCover.Instrument.Track state recorder.Head Inspections.Track None Assert.That(recorder.Head.Body.Instructions.Count, Is.EqualTo countBefore) Assert.That(recorder.Head.Body.ExceptionHandlers.Count, Is.EqualTo handlersBefore) @@ -1100,7 +1101,7 @@ module AltCoverTests2 = try Visitor.reportFormat <- Some Base.ReportFormat.OpenCover let branches = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.None) + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.None) |> Seq.map (fun n -> match n with | BranchPoint b -> Some b @@ -1159,7 +1160,7 @@ module AltCoverTests2 = try Visitor.reportFormat <- Some Base.ReportFormat.OpenCover let branches = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.None) + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.None) |> Seq.map (fun n -> match n with | BranchPoint b -> Some b @@ -1217,7 +1218,7 @@ module AltCoverTests2 = try Visitor.reportFormat <- Some Base.ReportFormat.OpenCover let branches = - Visitor.Deeper <| Node.Method(method, Inspect.Instrument, None, Exemption.None) + Visitor.Deeper <| Node.Method(method, Inspections.Instrument, None, Exemption.None) |> Seq.map (fun n -> match n with | BranchPoint b -> Some b @@ -1266,14 +1267,14 @@ module AltCoverTests2 = let TypeShouldNotChangeState() = let input = InstrumentContext.Build [] let output = - Instrument.InstrumentationVisitor input (Node.Type(null, Inspect.Ignore, Exemption.None)) + Instrument.InstrumentationVisitor input (Node.Type(null, Inspections.Ignore, Exemption.None)) Assert.That(output, Is.SameAs input) [] let ExcludedMethodShouldNotChangeState() = let input = InstrumentContext.Build [] let output = - Instrument.InstrumentationVisitor input (Node.Method(null, Inspect.Ignore, None, Exemption.None)) + Instrument.InstrumentationVisitor input (Node.Method(null, Inspections.Ignore, None, Exemption.None)) Assert.That(output, Is.SameAs input) [] @@ -1294,7 +1295,7 @@ module AltCoverTests2 = let input = InstrumentContext.Build [] let output = Instrument.InstrumentationVisitor input - (Node.Method(func, Inspect.Instrument, None, Exemption.None)) + (Node.Method(func, Inspections.Instrument, None, Exemption.None)) Assert.That(output.MethodBody, Is.SameAs func.Body) [] @@ -1325,7 +1326,7 @@ module AltCoverTests2 = let diff = paired |> List.map (fun (i, j) -> (i, i = j.OpCode)) let output = Instrument.InstrumentationVisitor input - (Node.AfterMethod(func, Inspect.Ignore, None)) + (Node.AfterMethod(func, Inspections.Ignore, None)) Assert.That(output, Is.SameAs input) let paired' = Seq.zip diff input.MethodBody.Instructions Assert.That(paired' |> Seq.forall (fun ((i, x), j) -> x = (i = j.OpCode))) @@ -1357,7 +1358,7 @@ module AltCoverTests2 = Assert.That(paired |> Seq.exists (fun (i, j) -> i <> j.OpCode)) let output = Instrument.InstrumentationVisitor input - (Node.AfterMethod(func, Inspect.Instrument, None)) + (Node.AfterMethod(func, Inspections.Instrument, None)) Assert.That(output, Is.SameAs input) let paired' = Seq.zip opcodes input.MethodBody.Instructions Assert.That(paired' |> Seq.forall (fun (i, j) -> i = j.OpCode)) @@ -1545,7 +1546,7 @@ module AltCoverTests2 = Mono.Cecil.AssemblyDefinition.ReadAssembly (Assembly.GetExecutingAssembly().Location) let state = InstrumentContext.Build [ "nunit.framework"; "nonesuch" ] - let visited = Node.Assembly(def, Inspect.Ignore, []) + let visited = Node.Assembly(def, Inspections.Ignore, []) let result = Instrument.InstrumentationVisitor { state with RecordingAssembly = fake } visited Assert.That(def.MainModule.AssemblyReferences, Is.EquivalentTo refs) @@ -1571,7 +1572,7 @@ module AltCoverTests2 = Mono.Cecil.AssemblyDefinition.ReadAssembly (Assembly.GetExecutingAssembly().Location) let state = InstrumentContext.Build [ "nunit.framework"; "nonesuch" ] - let visited = Node.Assembly(def, Inspect.Instrument, []) + let visited = Node.Assembly(def, Inspections.Instrument, []) let result = Instrument.InstrumentationVisitor { state with RecordingAssembly = fake } visited Assert.That @@ -1584,7 +1585,7 @@ module AltCoverTests2 = Path.Combine(Path.GetDirectoryName(where) + AltCoverTests.Hack(), "Sample2.dll") let def = Mono.Cecil.AssemblyDefinition.ReadAssembly path ProgramDatabase.ReadSymbols def - let visited = Node.Module(def.MainModule, Inspect.Ignore) + let visited = Node.Module(def.MainModule, Inspections.Ignore) let state = InstrumentContext.Build [ "nunit.framework"; "nonesuch" ] let result = Instrument.InstrumentationVisitor state visited Assert.That @@ -1597,7 +1598,7 @@ module AltCoverTests2 = Path.Combine(Path.GetDirectoryName(where) + AltCoverTests.Hack(), "Sample2.dll") let def = Mono.Cecil.AssemblyDefinition.ReadAssembly path ProgramDatabase.ReadSymbols def - let visited = Node.Module(def.MainModule, Inspect.Instrument) + let visited = Node.Module(def.MainModule, Inspections.Instrument) let state = InstrumentContext.Build [ "nunit.framework"; "nonesuch" ] let path' = Path.Combine @@ -1703,7 +1704,7 @@ module AltCoverTests2 = Path.Combine(Path.GetDirectoryName(where) + AltCoverTests.Hack(), "Sample2.dll") let def = Mono.Cecil.AssemblyDefinition.ReadAssembly path ProgramDatabase.ReadSymbols def - let visited = Node.Module(def.MainModule, Inspect.Instrument) + let visited = Node.Module(def.MainModule, Inspections.Instrument) let state = InstrumentContext.Build [ "nunit.framework"; "nonesuch" ] let path' = Path.Combine @@ -1886,9 +1887,13 @@ module AltCoverTests2 = [] let OutputCanBeExercised() = let sink = StringSink(ignore) - Output.SetInfo sink - Output.SetError sink - Output.SetWarn sink + let SetInfo(x : StringSink) = Output.Info <- x.Invoke + let SetError(x : StringSink) = Output.Error <- x.Invoke + let SetWarn(x : StringSink) = Output.Warn <- x.Invoke + + SetInfo sink + SetError sink + SetWarn sink Output.Echo <- ignore Output.Usage <- ignore Assert.That(Output.Usage, Is.Not.Null) @@ -1898,8 +1903,7 @@ module AltCoverTests2 = |> Seq.collect (fun t -> t.GetNestedTypes(BindingFlags.NonPublic)) |> Seq.filter (fun t -> let tokens = - [ "Info"; "Echo"; "Error"; "Usage"; "Warn"; "ToConsole"; "SetInfo"; - "SetError"; "SetWarn" ] + [ "Info"; "Echo"; "Error"; "Usage"; "Warn"; "ToConsole" ] let name = t.Name tokens |> List.exists name.StartsWith) |> Seq.iter (fun t -> diff --git a/Tests/Tests3.fs b/Tests/Tests3.fs index 618cf40b6..14adb77c0 100644 --- a/Tests/Tests3.fs +++ b/Tests/Tests3.fs @@ -2114,10 +2114,8 @@ module AltCoverTests3 = let PreparingNewPlaceShouldCopyEverything() = Main.init() let monoRuntime = - "Mono.Runtime" - |> Type.GetType - |> isNull - |> not + ("Mono.Runtime" + |> Type.GetType).IsNotNull // because mono symbol-writing is broken, work around trying to // examine the instrumented files in a self-test run. let here = if monoRuntime @@ -2283,7 +2281,7 @@ module AltCoverTests3 = use stderr = new StringWriter() Console.SetError stderr let empty = OptionSet() - CommandLine.Usage { Intro = "UsageError"; Options = options; Options2 = empty } + CommandLine.UsageBase { Intro = "UsageError"; Options = options; Options2 = empty } let result = stderr.ToString().Replace("\r\n", "\n") let expected = """Error - usage is: -i, --inputDirectory=VALUE Optional, multiple: A folder containing assemblies diff --git a/Tests/XTests.fs b/Tests/XTests.fs index 2c4d41b08..4d966fb1e 100644 --- a/Tests/XTests.fs +++ b/Tests/XTests.fs @@ -8,6 +8,7 @@ open System.Text.RegularExpressions open System.Xml.Linq open AltCover +open AltCover.Augment open Mono.Options open Newtonsoft.Json.Linq open Swensen.Unquote @@ -158,7 +159,7 @@ module AltCoverXTests = let instance = FSApi.CollectParams.Primitive subject let scan = instance.Validate(false) test <@ scan.Length = 0 @> - test <@ instance.GetHashCode() :> obj |> isNull |> not @> // gratuitous coverage for coverlet + test <@ (instance.GetHashCode() :> obj).IsNotNull @> // gratuitous coverage for coverlet test <@ (FSApi.CollectParams.Primitive subject) |> FSApi.Args.Collect = [ "Runner"; "-t"; "23"; "--collect" ] @> @@ -171,7 +172,7 @@ module AltCoverXTests = Executable = TypeSafe.Tool "dotnet" } let instance = FSApi.CollectParams.TypeSafe subject - test <@ instance.GetHashCode() :> obj |> isNull |> not @> // gratuitous coverage for coverlet + test <@ (instance.GetHashCode() :> obj).IsNotNull @> // gratuitous coverage for coverlet let scan = instance.Validate(false) test <@ scan.Length = 0 @> @@ -179,7 +180,7 @@ module AltCoverXTests = <@ instance |> FSApi.Args.Collect = [ "Runner"; "-x"; "dotnet"; "-t"; "23"; "--teamcity:+B" ] @> let validate = instance.WhatIf(false) - test <@ validate.GetHashCode() :> obj |> isNull |> not @> // gratuitous coverage for coverlet + test <@ (validate.GetHashCode() :> obj).IsNotNull @> // gratuitous coverage for coverlet test <@ validate.ToString() = "altcover Runner -x dotnet -t 23 --teamcity:+B" @> [] @@ -237,7 +238,7 @@ module AltCoverXTests = let instance = FSApi.PrepareParams.Primitive subject let scan = instance.Validate() test <@ scan.Length = 0 @> - test <@ instance.GetHashCode() :> obj |> isNull |> not @> // gratuitous coverage for coverlet + test <@ (instance.GetHashCode() :> obj).IsNotNull @> // gratuitous coverage for coverlet let rendered = (FSApi.PrepareParams.Primitive subject) |> FSApi.Args.Prepare let location = Assembly.GetExecutingAssembly().Location test @@ -273,7 +274,7 @@ module AltCoverXTests = TypeSafe.Filters [| TypeSafe.Raw "ok" |] } let instance = FSApi.PrepareParams.TypeSafe subject - test <@ instance.GetHashCode() :> obj |> isNull |> not @> // gratuitous coverage for coverlet + test <@ (instance.GetHashCode() :> obj).IsNotNull @> // gratuitous coverage for coverlet let scan = instance.Validate() test <@ scan.Length = 0 @> diff --git a/WeakNameTests/Tests.fs b/WeakNameTests/Tests.fs index ae8082db3..a85a81f0d 100644 --- a/WeakNameTests/Tests.fs +++ b/WeakNameTests/Tests.fs @@ -129,6 +129,7 @@ type AltCoverTests() = member self.GratuitousCoverage() = let l = Left 23 let r = Right true + test <@ (23).IsNotNull @> let output = [ r; l ] diff --git a/altcover.core.sln b/altcover.core.sln index 34829ce14..22e55d35b 100644 --- a/altcover.core.sln +++ b/altcover.core.sln @@ -50,6 +50,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build Items", "Build Items" Build\Apply-Xslt.ps1 = Build\Apply-Xslt.ps1 appveyor.yml = appveyor.yml Build\build.fsx = Build\build.fsx + Build\common-rules.xml = Build\common-rules.xml Build\get-token.fsx = Build\get-token.fsx global.json = global.json Build\Infrastructure.snk = Build\Infrastructure.snk @@ -59,9 +60,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build Items", "Build Items" Build\powershell.ps1 = Build\powershell.ps1 Build\Recorder.snk = Build\Recorder.snk ReleaseNotes.md = ReleaseNotes.md - Build\rules-fake.xml = Build\rules-fake.xml - Build\rules-posh.xml = Build\rules-posh.xml - Build\rules.xml = Build\rules.xml Build\SelfTest.snk = Build\SelfTest.snk Build\setup.fsx = Build\setup.fsx Build\targets.fsx = Build\targets.fsx