aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/windows/shared.psm1
blob: b04e54b26709bc392d0f489a82eab50c2663d0f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# EMACS settings: -*-  tab-width: 2; indent-tabs-mode: t -*-
# vim: tabstop=2:shiftwidth=2:noexpandtab
# kate: tab-width 2; replace-tabs off; indent-width 2;
# 
# ==============================================================================
#  Authors:
#    Patrick Lehmann
# 
#  PowerShell Module:	The module provides common CmdLets for ...
# 
# Description:
# ------------------------------------
#  This PowerShell module provides CommandLets (CmdLets) to ...
#
# ==============================================================================
#  Copyright (C) 2016-2017 Patrick Lehmann
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <gnu.org/licenses>.
# ==============================================================================

[CmdletBinding()]
param(
	[Parameter(Mandatory=$true)][string]$WorkingDir,
	[Parameter(Mandatory=$true)][Switch]$Hosted
)

$Module_WorkingDir =	$WorkingDir
$Module_Hosted =			$Hosted

function Exit-CompileScript
{	<#
		.SYNOPSIS
		Undocumented
		.DESCRIPTION
		Undocumented
		.PARAMETER ExitCode
		ExitCode of this script run
	#>
	[CmdletBinding()]
	param(
		[int]$ExitCode = 0
	)
	cd $Module_WorkingDir
	# unload modules
	if (-not $Module_Hosted)
	{	Remove-Module shared  -Verbose:$false -Debug:$false
		Remove-Module targets -Verbose:$false -Debug:$false
	}
	exit $ExitCode
}

function New-LibraryDirectory
{	<#
		.SYNOPSIS
		Undocumented
		
		.DESCRIPTION
		Undocumented
		
		.PARAMETER Directory
		Undocumented
	#>
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$true)][string]$Directory	#,
		# [Parameter(Mandatory=$true)][bool]$EnableVerbose
	)
	$EnableVerbose = $false
	if (Test-Path -Path $Directory)
	{	$EnableVerbose -and (Write-Host "    Directory '$Directory' already exists."	) | Out-Null	}
	else
	{	Write-Host "    Creating directory '$Directory'."
		New-Item -ItemType directory -Path $Directory -ErrorAction SilentlyContinue | Out-Null
	}
}

function Format-VHDLSourceFile
{	<#
		.SYNOPSIS
		Undocumented
		
		.DESCRIPTION
		Undocumented
		
		.PARAMETER Version
		Undocumented
		.PARAMETER InputObject
		A object stream is required as an input.
	#>
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$true)][string]$Version,
		[Parameter(ValueFromPipeline=$true)]$InputObject
	)
	
	begin
	{	$State = 1
		$Version = switch ($Version)
								{	"87"	{	87	}
									"93"	{	93	}
									"02"	{	2		}
									"08"	{	8		}
								}
	}
	
	process
	{	if ($InputObject -is [String])
		{	$Line = $InputObject.ToString()
			if ($Line.StartsWith("--START-V"))
			{	$State = switch ($Line.Substring(9, 2))
									{	"87"	{	87	}
										"93"	{	93	}
										"02"	{	2		}
										"08"	{	8		}
									}
			}
			elseif ($Line.StartsWith("--START-!V"))
			{	if ($Line.Substring(10, 2) -eq $Version)
				{	$State = 2	}
			}
			elseif ($Line.StartsWith("--END-V") -or $Line.StartsWith("--END-!V"))
			{	$State = 1		}
			else
			{	if ($State -eq 1)
				{	if ($Line.EndsWith("--V$Version"))
					{	Write-Output $Line		}
					elseif (-not (($Line -like "*--V??") -or ($Line.EndsWith("--!V$Version"))))
					{	Write-Output $Line		}
				}
				elseif ($State -eq $Version)
				{	Write-Output $Line			}
			}
		}
		else
		{	Write-Host "Unknown pipeline object type." -ForegroundColor Red		}
	}
	
	end
	{	
	}
}

function Restore-NativeCommandStream
{	<#
		.SYNOPSIS
		This CmdLet gathers multiple ErrorRecord objects and reconstructs outputs
		as a single line.
		
		.DESCRIPTION
		This CmdLet collects multiple ErrorRecord objects and emits one String
		object per line.
		.PARAMETER InputObject
		A object stream is required as an input.
		.PARAMETER Indent
		Indentation string.
	#>
	[CmdletBinding()]
	param(
		[Parameter(ValueFromPipeline=$true)]
		$InputObject
	)

	begin
	{	$LineRemainer = ""	}

	process
	{	if ($InputObject -is [System.Management.Automation.ErrorRecord])
		{	if ($InputObject.FullyQualifiedErrorId -eq "NativeCommandError")
			{	Write-Output $InputObject.ToString()		}
			elseif ($InputObject.FullyQualifiedErrorId -eq "NativeCommandErrorMessage")
			{	$NewLine = $LineRemainer + $InputObject.ToString()
				while (($NewLinePos = $NewLine.IndexOf("`n")) -ne -1)
				{	Write-Output $NewLine.Substring(0, $NewLinePos)
					$NewLine = $NewLine.Substring($NewLinePos + 1)
				}
				$LineRemainer = $NewLine
			}
		}
		elseif ($InputObject -is [String])
		{	Write-Output $InputObject		}
		else
		{	Write-Host "Unsupported object in pipeline stream"		}
	}

	end
	{	if ($LineRemainer -ne "")
		{	Write-Output $LineRemainer	}
	}
}

function Write-ColoredGCCLine
{	<#
		.SYNOPSIS
		This CmdLet colors GHDL output lines.
		
		.DESCRIPTION
		This CmdLet colors GHDL output lines. Warnings are prefixed with 'WARNING: '
		in yellow and errors are prefixed with 'ERROR: ' in red.
		
		.PARAMETER InputObject
		A object stream is required as an input.
		.PARAMETER SuppressWarnings
		Skip warning messages. (Show errors only.)
		.PARAMETER Indent
		Indentation string.
	#>
	[CmdletBinding()]
	param(
		[Parameter(ValueFromPipeline=$true)]
		$InputObject,
		
		[Parameter(Position=1)]
		[switch]$SuppressWarnings = $false,
		[Parameter(Position=2)]
		[string]$Indent = ""
	)

	begin
	{	$ErrorRecordFound = $false	}
	
	process
	{	if ($InputObject -is [String])
		{	if ($InputObject -match ":\d+:\d+:\swarning:\s")
			{	if (-not $SuppressWarnings)
				{	Write-Host "${Indent}WARNING: "	-NoNewline -ForegroundColor Yellow
					Write-Host $InputObject
				}
			}
			elseif ($InputObject -match ":\d+:\d+:\s")
			{	$ErrorRecordFound	= $true
				Write-Host "${Indent}ERROR: "		-NoNewline -ForegroundColor Red
				Write-Host $InputObject
			}
			else
			{	Write-Host "${Indent}$InputObject"		}
		}
		else
		{	Write-Host "Unsupported object in pipeline stream"		}
	}

	end
	{	$ErrorRecordFound		}
}

function Write-ColoredGHDLLine
{	<#
		.SYNOPSIS
		This CmdLet colors GHDL output lines.
		
		.DESCRIPTION
		This CmdLet colors GHDL output lines. Warnings are prefixed with 'WARNING: '
		in yellow and errors are prefixed with 'ERROR: ' in red.
		
		.PARAMETER InputObject
		A object stream is required as an input.
		
		.PARAMETER SuppressWarnings
		Skip warning messages. (Show errors only.)
	#>
	[CmdletBinding()]
	param(
		[Parameter(ValueFromPipeline=$true)]
		$InputObject,
		
		[Parameter(Position=1)]
		[switch]$SuppressWarnings = $false,
		[Parameter(Position=2)]
		[string]$Indent = ""
	)

	begin
	{	$ErrorRecordFound = $false	}
	
	process
	{	if ($InputObject -is [String])
		{	if ($InputObject -match ":\d+:\d+:warning:\s")
			{	if (-not $SuppressWarnings)
				{	Write-Host "${Indent}WARNING: "	-NoNewline -ForegroundColor Yellow
					Write-Host $InputObject
				}
			}
			elseif ($InputObject -match ":\d+:\d+:\s")
			{	$ErrorRecordFound	= $true
				Write-Host "${Indent}ERROR: "		-NoNewline -ForegroundColor Red
				Write-Host $InputObject
			}
			else
			{	Write-Host "${Indent}$InputObject"		}
		}
		else
		{	Write-Host "Unsupported object in pipeline stream"		}
	}

	end
	{	$ErrorRecordFound		}
}

function Write-HostExtended
{	<#
		.SYNOPSIS
		This CmdLet colors GHDL output lines.
		
		.DESCRIPTION
		This CmdLet colors GHDL output lines. Warnings are prefixed with 'WARNING: '
		in yellow and errors are prefixed with 'ERROR: ' in red.
		
		.PARAMETER InputObject
		A object stream is required as an input.
		.PARAMETER Indent
		Indentation string.
	#>
	[CmdletBinding()]
	param(
		[Parameter(ValueFromPipeline=$true)]
		$InputObject,
		
		[Parameter(Position=1)]
		[string]$Indent = ""
	)

	begin
	{		}
	
	process
	{	if ($InputObject -is [String])
		{	Write-Host "${Indent}$InputObject"									}
		else
		{	Write-Host "Unsupported object in pipeline stream"	}
	}

	end
	{		}
}

function Test-GitRepository
{	<#
		.SYNOPSIS
		Returns true, if the current working directy is under git control.
	#>
	
	git rev-parse 2>&1 | Out-Null
	return $LastExitCode -eq 0
}

# export functions
Export-ModuleMember -Function 'Exit-CompileScript'

Export-ModuleMember -Function 'New-LibraryDirectory'
Export-ModuleMember -Function 'Format-VHDLSourceFile'

Export-ModuleMember -Function 'Restore-NativeCommandStream'
Export-ModuleMember -Function 'Write-ColoredGCCLine'
Export-ModuleMember -Function 'Write-ColoredGHDLLine'
Export-ModuleMember -Function 'Write-HostExtended'

Export-ModuleMember -Function 'Test-GitRepository'
---------|:---------------------------------------------------| |`AnyOf(m1, m2, ..., mn)`|`argument` matches at least one of the matchers `m1` to `mn`.| |`Not(m)` |`argument` doesn't match matcher `m`. | ## Adapters for Matchers ## |`MatcherCast<T>(m)`|casts matcher `m` to type `Matcher<T>`.| |:------------------|:--------------------------------------| |`SafeMatcherCast<T>(m)`| [safely casts](CookBook.md#casting-matchers) matcher `m` to type `Matcher<T>`. | |`Truly(predicate)` |`predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor.| ## Matchers as Predicates ## |`Matches(m)(value)`|evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor.| |:------------------|:---------------------------------------------------------------------------------------------| |`ExplainMatchResult(m, value, result_listener)`|evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | |`Value(value, m)` |evaluates to `true` if `value` matches `m`. | ## Defining Matchers ## | `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | |:-------------------------------------------------|:------------------------------------------------------| | `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a macher `IsDivisibleBy(n)` to match a number divisible by `n`. | | `MATCHER_P2(IsBetween, a, b, std::string(negation ? "isn't" : "is") + " between " + PrintToString(a) + " and " + PrintToString(b)) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | **Notes:** 1. The `MATCHER*` macros cannot be used inside a function or class. 1. The matcher body must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). 1. You can use `PrintToString(x)` to convert a value `x` of any type to a string. ## Matchers as Test Assertions ## |`ASSERT_THAT(expression, m)`|Generates a [fatal failure](../../googletest/docs/Primer.md#assertions) if the value of `expression` doesn't match matcher `m`.| |:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------| |`EXPECT_THAT(expression, m)`|Generates a non-fatal failure if the value of `expression` doesn't match matcher `m`. | # Actions # **Actions** specify what a mock function should do when invoked. ## Returning a Value ## |`Return()`|Return from a `void` mock function.| |:---------|:----------------------------------| |`Return(value)`|Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed.| |`ReturnArg<N>()`|Return the `N`-th (0-based) argument.| |`ReturnNew<T>(a1, ..., ak)`|Return `new T(a1, ..., ak)`; a different object is created each time.| |`ReturnNull()`|Return a null pointer. | |`ReturnPointee(ptr)`|Return the value pointed to by `ptr`.| |`ReturnRef(variable)`|Return a reference to `variable`. | |`ReturnRefOfCopy(value)`|Return a reference to a copy of `value`; the copy lives as long as the action.| ## Side Effects ## |`Assign(&variable, value)`|Assign `value` to variable.| |:-------------------------|:--------------------------| | `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | | `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | | `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | | `SetArgReferee<N>(value)` | Assign value to the variable referenced by the `N`-th (0-based) argument. | |`SetArgPointee<N>(value)` |Assign `value` to the variable pointed by the `N`-th (0-based) argument.| |`SetArgumentPointee<N>(value)`|Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0.| |`SetArrayArgument<N>(first, last)`|Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range.| |`SetErrnoAndReturn(error, value)`|Set `errno` to `error` and return `value`.| |`Throw(exception)` |Throws the given exception, which can be any copyable value. Available since v1.1.0.| ## Using a Function or a Functor as an Action ## |`Invoke(f)`|Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor.| |:----------|:-----------------------------------------------------------------------------------------------------------------| |`Invoke(object_pointer, &class::method)`|Invoke the {method on the object with the arguments passed to the mock function. | |`InvokeWithoutArgs(f)`|Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | |`InvokeWithoutArgs(object_pointer, &class::method)`|Invoke the method on the object, which takes no arguments. | |`InvokeArgument<N>(arg1, arg2, ..., argk)`|Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments.| The return value of the invoked function is used as the return value of the action. When defining a function or functor to be used with `Invoke*()`, you can declare any unused parameters as `Unused`: ``` double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } ... EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); ``` In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, wrap it inside `ByRef()`. For example, ``` InvokeArgument<2>(5, string("Hi"), ByRef(foo)) ``` calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by value, and `foo` by reference. ## Default Action ## |`DoDefault()`|Do the default action (specified by `ON_CALL()` or the built-in one).| |:------------|:--------------------------------------------------------------------| **Note:** due to technical reasons, `DoDefault()` cannot be used inside a composite action - trying to do so will result in a run-time error. ## Composite Actions ## |`DoAll(a1, a2, ..., an)`|Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void. | |:-----------------------|:-----------------------------------------------------------------------------------------------------------------------------| |`IgnoreResult(a)` |Perform action `a` and ignore its result. `a` must not return void. | |`WithArg<N>(a)` |Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | |`WithArgs<N1, N2, ..., Nk>(a)`|Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | |`WithoutArgs(a)` |Perform action `a` without any arguments. | ## Defining Actions ## | `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | |:--------------------------------------|:---------------------------------------------------------------------------------------| | `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | | `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | The `ACTION*` macros cannot be used inside a function or class. # Cardinalities # These are used in `Times()` to specify how many times a mock function will be called: |`AnyNumber()`|The function can be called any number of times.| |:------------|:----------------------------------------------| |`AtLeast(n)` |The call is expected at least `n` times. | |`AtMost(n)` |The call is expected at most `n` times. | |`Between(m, n)`|The call is expected between `m` and `n` (inclusive) times.| |`Exactly(n) or n`|The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0.| # Expectation Order # By default, the expectations can be matched in _any_ order. If some or all expectations must be matched in a given order, there are two ways to specify it. They can be used either independently or together. ## The After Clause ## ``` using ::testing::Expectation; ... Expectation init_x = EXPECT_CALL(foo, InitX()); Expectation init_y = EXPECT_CALL(foo, InitY()); EXPECT_CALL(foo, Bar()) .After(init_x, init_y); ``` says that `Bar()` can be called only after both `InitX()` and `InitY()` have been called. If you don't know how many pre-requisites an expectation has when you write it, you can use an `ExpectationSet` to collect them: ``` using ::testing::ExpectationSet; ... ExpectationSet all_inits; for (int i = 0; i < element_count; i++) { all_inits += EXPECT_CALL(foo, InitElement(i)); } EXPECT_CALL(foo, Bar()) .After(all_inits); ``` says that `Bar()` can be called only after all elements have been initialized (but we don't care about which elements get initialized before the others). Modifying an `ExpectationSet` after using it in an `.After()` doesn't affect the meaning of the `.After()`. ## Sequences ## When you have a long chain of sequential expectations, it's easier to specify the order using **sequences**, which don't require you to given each expectation in the chain a different name. <i>All expected<br> calls</i> in the same sequence must occur in the order they are specified. ``` using ::testing::Sequence; Sequence s1, s2; ... EXPECT_CALL(foo, Reset()) .InSequence(s1, s2) .WillOnce(Return(true)); EXPECT_CALL(foo, GetSize()) .InSequence(s1) .WillOnce(Return(1)); EXPECT_CALL(foo, Describe(A<const char*>())) .InSequence(s2) .WillOnce(Return("dummy")); ``` says that `Reset()` must be called before _both_ `GetSize()` _and_ `Describe()`, and the latter two can occur in any order. To put many expectations in a sequence conveniently: ``` using ::testing::InSequence; { InSequence dummy; EXPECT_CALL(...)...; EXPECT_CALL(...)...; ... EXPECT_CALL(...)...; } ``` says that all expected calls in the scope of `dummy` must occur in strict order. The name `dummy` is irrelevant.) # Verifying and Resetting a Mock # Google Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: ``` using ::testing::Mock; ... // Verifies and removes the expectations on mock_obj; // returns true iff successful. Mock::VerifyAndClearExpectations(&mock_obj); ... // Verifies and removes the expectations on mock_obj; // also removes the default actions set by ON_CALL(); // returns true iff successful. Mock::VerifyAndClear(&mock_obj); ``` You can also tell Google Mock that a mock object can be leaked and doesn't need to be verified: ``` Mock::AllowLeak(&mock_obj); ``` # Mock Classes # Google Mock defines a convenient mock class template ``` class MockFunction<R(A1, ..., An)> { public: MOCK_METHODn(Call, R(A1, ..., An)); }; ``` See this [recipe](CookBook.md#using-check-points) for one application of it. # Flags # | `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | |:-------------------------------|:----------------------------------------------| | `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |