vexx32 / pskoans Goto Github PK
View Code? Open in Web Editor NEWA simple, fun, and interactive way to learn the PowerShell language through Pester unit testing.
License: GNU General Public License v3.0
A simple, fun, and interactive way to learn the PowerShell language through Pester unit testing.
License: GNU General Public License v3.0
Foundations\AboutStringOperators.koans.ps1
It 'can limit the number of substrings' {
$Planets = 'Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune'
$Planets -split ',', 4 | Should -Be @('Mecury', 'Venus', 'Earth', 'Mars,Jupiter,Saturn,Uranus,Neptune')
}
I attempted to admire a list of all the planets, including Pluto. Instead, I witnessed only 8.
Sources: WolframAlpha
When running Measure-Karma
under ISE the following error is printed in lieu of the progress bar:
Specified argument was out of the range of valid values.
Parameter name: times
At C:\Program Files\WindowsPowerShell\Modules\pskoans\0.42.2\Private\Write-MeditationPrompt.ps1:138 char:20
+ "$([char]0x2015)" * ($ProgressWidth - $PortionDone)
+ ~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentOutOfRangeException
+ FullyQualifiedErrorId : System.ArgumentOutOfRangeException
Running Measure-Karma
in the ISE integrated console triggers the issue consistently.
The progress bar should be printed as per normal
This appears to be due to the ISE console not populating the $host.UI.RawUI.WindowSize
field. It appears it does correctly populate the $host.UI.RawUI.BufferSize
field instead, so the width from that field should also be checked.
This one completes successfully without user interaction. It needs a default case that throws.
The regex muddies this example a lot.
The regex will turn input like Harmless
into H,a,a,a,r,a,m,a,l,a,e,a,s,a,s,a,
. This is distinctly confusing and detracts from the example which is focuses on wildcard matching in switch.
I recommend this example is reviewed.
These two koans should be swapped around for a more logical progression. /cc @thomasrayner
PSKoans/PSKoans/Koans/Foundations/AboutStringOperators.Koans.ps1
Lines 98 to 106 in eac7d82
Great project!
Trying to follow but hit some hurdles
git clone the repository into your desired directory, or download and extract the repository as a .zip file into a directory of your choice
guess it actually meant:
git clone the repository into your desired directory, or download the repository as a .zip file and extract into a directory of your choice
PS C:\Users\user> Install-Module PSKoans -Scope CurrentUser
PS C:\Users\user> Measure-Karma
Measure-Karma : The term 'Measure-Karma' is not recognized as the name of a cmdlet, function, script file, or operable program.
Versions:
- PSKoans 0.39.6.
- $psversiontable
Name Value
---- -----
PSVersion 6.0.3
PSEdition Core
GitCommitId v6.0.3
OS Microsoft Windows 10.0.17134
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
It "can be used to select a value for a variable"
Get-Thing returns the length.
$Result = if ($Thing.Length -gt 5)
That's the Length of the Length.
"$Thing is less than 5"
seems to refer to the first order length.
50 is less than 5
seems strange.
I'd alter the conditional if ($Thing -gt 5)
Ty @dizzi90
Hello,
I am having trouble following some instruction as they expected outcome does not occur. I assume that some update must have changed the way it was meant to work.
Double click on the PSKoans.psm1 file, and VS Code will launch a powershell console
When I double click this file in the Visual Studio Code it just opens it for me to read and edit the code not actually run it.
Thanks,
So VS code's style plugins stop complaining at me. :D
I noticed that the last test 'does not throw exceptions with invalid indexes' in the Foundations\AboutArrays.Koans.ps1 file passes without any user modifications.
PSKoans/PSKoans/Koans/Foundations/AboutArrays.Koans.ps1
Lines 94 to 103 in 622f273
Both sides of the Pipeline are $null. The left side has the alias named __, and that calls the function Get-Blank that returns $null. On the right side the Should -Be values are outside of the range of the array, and that also returns $null.
I had attempted to change the __ to 0, which now fails and the following is displayed when running Measure-Karma
.
The answers you seek...
Expected $null, but got 0.
Please meditate on the following code:
[It] does not throw exceptions with invalid indexes
at <ScriptBlock>, C:\Users\Username\PSKoans\Foundations\AboutArrays.Koans.ps1: line 99
99: 0 | Should -Be $Array[4]
I'm running the following versions:
PSversion: 5.1.17763.134
pskoans: 0.42.2
pester: 4.6.0
Console colors can be reconfigured arbitrarily, causing our set colors for Show-MeditationPrompt
to become a bit unreadable. We could handle this better.
Private module handler command, possibly tied in with Write-ConsoleLine
from @SeeminglyScience's reply:
@vexx32 If
PSReadLine
is loaded you can pull from it's settings to determine what colors to use.$psrlModule = Get-Module PSReadLine if (-not $psrlModule) { return } $options = Get-PSReadLineOption if ($psrlModule.Version.Major -ge 2) { # Handle as ANSI escape return '{1}Colored like a number{0} {2}Colored like a keyword{0}' -f ( "$([char]27)[0m", # Reset color ANSI escape $options.NumberColor, $options.KeywordColor) } else { # Handle like ConsoleColor }
Invoke-Koan
-Topic
parameter of Measure-Koan
Get-Koan
Get-PSKoanLocation
and Set-PSKoanLocation
If you want to upgrade from one version of PSKoans to a newer one while your learning is in progress (some koans are done, some are not done), you're going to get a bunch of errors because of changes in the engine and how some of the koans have been restructured.
Everybody wants the latest and greatest versions of their modules, but changing versions while your learning is in progress will result in a wide variety of different issues depending which versions you're moving between.
An upgrade should automatically detect inprog koans and edit them accordingly, or otherwise report your progress. If a new koan is in a file that was previously completely solved, there should be a friendly message describing that scenario.
Obviously the expected behavior is up for debate, but it's not a reasonable assumption that people will start and end their PSKoans learning journey on the same version of the module - especially while hard working folks like @vexx32 @steviecoaster and @corbob are contributing new koans.
I understand what you're going for here, but I'm not convinced that this is a good excersize. I hate pointing out something without offering a fix.
AboutAssignmentAndArithmetic
needs a koan for multi-assignment, e.g. $var1 = $var2 = 'value'
demonstrate how to create classes. How properties and methods works, access modifiers (hidden), inheritance etc. I wouldn't mind chipping in if it's something you want in the project
Maybe we should include the answers somewhere in the project but not publish them with the module in the gallery. This way we can find bugs in the koans before we push. Thoughts?
At this point in one's PSKoans journey, they probably aren't ready to dig into error records to find expected messages. They can probably guess at it, but it might be too early, or need a comment describing what's expected of the learner. But hey, at least it's just expectedmessage not expectedtype!
The partial answers are only reliable if the hashtable is ordered. Keys are stored in hash order, not entered order.
It 'allows you to retrieve a list of keys or values' {
$Hashtable = @{One = 1; Two = 2; Three = 3; Four = 4}
$Hashtable.Keys | Should -Be @('__', '__', '__', '__')
$Hashtable.Values | Should -Be @( , , , 4)
}
It 'allows you to remove keys' {
$Hashtable = @{
One = 1
Two = 2
Three = 3
Four = 4
}
$Hashtable.Remove('One')
$Hashtable.Count | Should -Be __
$Hashtable.Keys | Should -Be @('__', '__', 'Four')
$Hashtable.Values | Should -Be @( , , 4)
}
Recommend introducing (with another Koan) and adding [Ordered]
.
Hi,
just i minor thing i've noticed in the readme while trying it on mac and windows:
Tested with:
Describe the koan you'd like to see
For years, seekers of enlightenment had to sully their karma and physical bodies with SQLPS.
SLOW was their loading times!
CHANGED was their path!
WARNED where they of unapproved verbs (which elicited a few unapproved 4 letter words from the seekers themselves...)
Then LO! As how a journey starts with but a single step, a new module arrived from the need to improve a single action.
From a migration tool to a fully fledged module, dbatools has become the de facto module for interacting with SQL Server.
Outline the scope you think would be most helpful and conducive to the koan format
dbatools has most of their commands broken down into categories themselves so we can work off that if needed.
Start off small, say server/database information. Then move up to say SQL Server Agent Jobs, etc.
Additional context
Blog posts and websites and people, oh my!
dbatools website
Chrissy LeMaire
Rob Sewell
and more and more and more
From the about_quotationRules
To make double-quotation marks appear in a string, enclose the entire
string in single quotation marks. For example:
'As they say, "live and learn."'
The output of this command is:
As they say, "live and learn."
You can also enclose a single-quoted string in a double-quoted string.
For example:
"As they say, 'live and learn.'"
The output of this command is:
As they say, 'live and learn.'
Or, double the quotation marks around a double-quoted phrase. For
example:
"As they say, ""live and learn."""
The output of this command is:
As they say, "live and learn."
To include a single quotation mark in a single-quoted string, use a
second consecutive single quote. For example:
'don''t'
The output of this command is:
don't``
From issue #12
So either we need to change the ConfirmImpact of the function to High or we need to alter the call that the Get-Enlightenment function does with the -Reset switch to call the Initialize-KoanDirectory function with the -Confirm switch.
My opinion is, Initialize-KoanDirectory is not an exported function, so the simplest option is to remove the -FirstImport parameter and set ConfirmImpact to High.
Could easily be convinced the other direction.
The Evaluated Strings
context in Foundations/AboutStrings.Koans.ps1
calls Get-Item 'C:\Windows'
which will always fail on non-Windows machine.
Evaluated Strings
context:
It 'can do a simple expansion' {
$Windows = Get-Item 'C:\Windows' | Select-Object -ExpandProperty FullName
'__' | Should -Be "The windows directory is located here: $Windows"
}
There are few ways this could be fixed. If you prefer to use Get-Item
without a variable, you could use something like Get-Item '.'
. Or if you don't mind variables you could use something like Get-Item $env:HOME
. Or you could something less platform specific like
It 'can do a simple expansion' {
$DayOfWeek = Get-Date | Select-Object -ExpandProperty DayOfWeek
'__' | Should -Be "The day of the week today is $DayofWeek"
}
The .Keys
and .Values
properties of ordered hashtables aren't regular arrays and so these assertions fail, even when the learner enters the values in order.
Appending .ForEach{$_}
to both lines to get an array out of these properties would work around this issue. Otherwise the arrays will have to be constructed differently.
Add a comment explaining that values passed to parameters are passed to the parameter variables within the function for that run of the function.
Change the comment to more clearly indicate exactly where in the line to place the .Invoke()
call
On completion of PSKoans 201 (AboutDiscovery), evaluation of a previous answer starts to fail:
Describing 'If/Else' has damaged your karma.
You have not yet reached enlightenment.
The answers you seek...
Expected '0 is less than 5', but got 10191.
Please meditate on the following code:
[It] can be used to select a value for a variable
at <ScriptBlock>, C:\Users\chrident\PSKoans\Foundations\AboutConditionals.Koans.ps1: line 62
62: $Result | Should -Be '0 is less than 5'
Because AboutPSProviders starts to add content to that same path which may change the previously given answer:
Describe 'FileSystem Provider' {
$Path = $home | Join-Path -ChildPath 'File001.tmp'
if (-not (Test-Path $Path)) {
New-Item -Path $Path > $null
This is not cleaned unless you already have all the answers to that section right. I suggest using TestDrive for this set of examples, or at the very least somewhere else. Thoughts?
Mention different creation methods, as well as best practices.
Every Function Should Have Comment-Based Help!
It would be nice to see all the topics covered by the Koans. Something like this:
Measure-Karma -ListAllTopics
A problem when jumping too many versions:
At C:\Users\Chris\Documents\WindowsPowerShell\Modules\pskoans\0.41.0\Private\Write-MeditationPrompt.ps1:150 char:13
+ $PortionDone = ($KoansPassed / $TotalKoans) * $ProgressWi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
Attempted to divide by zero.
Script stack trace:
at Write-MeditationPrompt, C:\Users\Chris\Documents\WindowsPowerShell\Modules\pskoans\0.41.0\Private\Write-MeditationPrompt.ps1: line 150
at Measure-Karma, C:\Users\Chris\Documents\WindowsPowerShell\Modules\pskoans\0.41.0\Public\Measure-Karma.ps1: line 118
at <ScriptBlock>, <No file>: line 1
Describe the koan you'd like to see
Hashtables, like most non-primitive types, are reference types. The use and effect of .Clone should be introduced.
Outline the scope you think would be most helpful and conducive to the koan format
TBC
Additional context
With respect to the pipeline, how it affects collections in general, and it can't hurt to explain how it works in brief.
I don't quite understand this one. It feels like the answer is wrong (although it is, of course, not).
Context 'Members of objects returned from cmdlets' {
...
It 'actually returns objects itself' {
$MemberData = 'string' | Get-Member
# We can all betray our own selves.
$MemberData | Should -BeOfType [Object[]]
}
Just me?
Chris
I'm sure this is an oversight. I'd be happy to fix, though not sure how I can.
Change comment to indicate which parameter of [Math]::Pow()
is base and which is exponent.
Courtesy of @romero126 on the PS Discord:
<#
Master Koan! The Monks of the PowerShell order have become angry, and began to complain
that the best chores are being given to the favored Monks. In order to prevent the dishonor of
the angry Monks we must fix this.
Write a PowerShell script that takes input of [array[int]]$data, [int]$n that takes in a list of less
than 100 integers and a number n, and returns that same list but with all of the numbers that
occur more than n times removed entirely. The returned list should retain the same ordering
as the origional list. For instance, if data was @(1, 3, 5, 3, 2) and $n is 1, the answer would result
in a list @(1,5,2) because 3 occurs twice, and thus was removed from the list entirely.
#>
param ($data, $n)
This has been committed as a draft here: https://github.com/vexx32/PSKoans/blob/master/drafts/ComplexArrayFilter.ps1
The flavour text may need to be tweaked or rewritten entirely if needed.
AboutFunctionsAndScriptBlocks.Koans.ps1
Koan could use clearer context around Write-Output vs return statements.
The following code could be clearer on what is happening specifically around that Write-Output can return multiple values to the pipe where return stops all output and doesn't run any code after it.
It 'allows you to assign a name to a sequence of commands' {
<#
An apt name eases the transition to abstraction.
PowerShell function names are named in convention following
the cmdlets; Verb-Noun. To see the list of approved
PowerShell verbs, run 'Get-Verb' in the console.
There are many methods of sending output from a function.
#>
function Get-Number {
<#
Explicit use of Write-Output allows multiple items to be output
within the function without causing the function to exit.
#>
Write-Output 20
}
function Get-ReturnedNumber {
<#
Use of the return statement causes all output previously declared
to be sent, along with any output passed to the return statement
itself, then ends the function.
#>
return 13
}
function Get-DroppedNumber {
<#
Leaving a value, or a statement that returns a value on a line
by itself causes that output to be 'dropped' to the output
stream, similar to functional languages. It can be considered
an implicit (and faster) 'Write-Output'
#>
12
}
20 | Should -Be (Get-Number)
Get-ReturnedNumber | Should -Be 13
12 | Should -Be (Get-DroppedNumber)
}
It 'allows you to assign a name to a sequence of commands' {
<#
An apt name eases the transition to abstraction.
PowerShell function names are named in convention following
the cmdlets; Verb-Noun. To see the list of approved
PowerShell verbs, run 'Get-Verb' in the console.
There are many methods of sending output from a function.
#>
function Get-Number {
<#
Explicit use of Write-Output allows multiple items to be output
within the function without causing the function to exit.
#>
Write-Output 20
Write-Output 42
}
function Get-ReturnedNumber {
<#
Use of the return statement causes all output previously declared
to be sent, along with any output passed to the return statement
itself, then ends the function.
#>
return 13
Write-Output "Doe not return"
}
function Get-DroppedNumber {
<#
Leaving a value, or a statement that returns a value on a line
by itself causes that output to be 'dropped' to the output
stream, similar to functional languages. It can be considered
an implicit (and faster) 'Write-Output'
#>
12
}
20,42 | Should -Be (Get-Number)
Get-ReturnedNumber | Should -Be 13
12 | Should -Be (Get-DroppedNumber)
}
Happy to provide a pull request if there is interest.
Consider:
It 'can look for commands by module' {
$KoanCommands = Get-Command -Module 'PSKoans'
$KoanCommands.Count | Should -Be 5
$KoanCommands.Name | Should -Be @('Get-Enlightenment', 'Invoke-PSKoans', 'Test-Koans', 'Get-Blanks', 'Measure-Karma')
}
Would you consider that answer correct?
PSKoans doesn't. When the test executes it also finds the commands which are not exported from the module (because it is executing inside the module scope).
See the response with a few line breaks for clarity:
Expected
@('Get-Enlightenment', 'Invoke-PSKoans', 'Test-Koans', 'Get-Blanks', 'Measure-Karma'),
but got
@('Get-Enlightenment', 'Invoke-PSKoans', 'Test-Koans', 'Assert-Equality', 'Get-Blank', 'Initialize-KoanDirectory', 'Measure-Karma', 'Measure-Koan', 'Write-MeditationPrompt').
Hard to fix while preserving the relative simplicity of the test.
Measure-Karma Topic should allow you to complete the Koans in that particular topic
Example:
I wish to complete the Koans on String operators only at this time. I would simply execute Measure-Karma -Topic AboutStringOperators
and the Koans for that particular section would load and be made available to me to complete.
AboutAssignmentAndArithmetic L75
[int[]]@(1, 2, 3, 4, 5) + '17' | Should -Be @(1, 2, 3, 4, 5, 17)
I'm not sure this example teaches the intended lesson. By appending '17'
to the end of the array declaration like that, PowerShell just writes the 1..5
out, and then appends '17'
to the output. It does the same thing with strings that can't be coerced to an integer, although the comment on the line before indicates that the value is being converted.
[int[]]@(1, 2, 3, 4, 5) + '17' | gm
returns member information for both integers and strings, indicating both types of values are written to the pipeline.
At first I thought this was occurring because no type coercion was being performed because no assignment operation was being done. Turns out, nope. Try this example.
$a = [int[]]@(1, 2, 3, 4, 5)
$a += '17'
$a += "I love PSKoans"
$a
#outputs
1
2
3
4
5
17
I love PSKoans
Version info
$psversiontable
Name Value
---- -----
PSVersion 5.1.18300.1001
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.18300.1001
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Knowing the right way to build complicated and huge strings is important too!
Not sure if Pester can do this, but if it can I wanna do it. Save us oops cases when we have too many tests and run into text vs numeric sort order issues
See title. Looks like I overlooked it, oops.
#Background
I just started on the Koans last night, mostly enjoying it.
Currently, however, shifts from one subject to another are abrupt. "Oh, I guess I'm doing assignment operators now?"
Progress is currently shown purely as a "x of (total)". I'm contemplating the idea of having the various subjects being titled and represented by "Mile Markers" in the progress display. Perhaps have them represented by a glyph/symbol, and only display the current and next subject in order to keep the output manageable/readable.
Thoughts?
Minus any that aren't... really... testable -- e.g., the standard output for the rake
function is all Write-Host and shouldn't do anything.
Perhaps that should be Mocked to just do nothing unless params are supplied? I'm not sure. Or at least the Write-MeditationPrompt should be mocked, anyway.
Anyway, need to figure all that stuff out to make sure the core module bits and pieces work properly!
All PowerShell objects are wrapped in PSObject wrappers, which is typically hidden but very much accessible and useful to work with on occasion. These members are available to all objects, including PSCustomObject-created PSObject instances, but these koans are not currently covered in AboutCustomObjects.
TBD
,@() | Get-Member -Force
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.