Getting Started with Pester 5: A Beginner's Guide / Начало работы с Pester 5: руководство для начинающих Год издания: 2024 Автор: Heaume Owen / Хеуме Оуэн Издательство: Apress Media LLC ISBN: 979-8-8688-0306-2 Язык: Английский Формат: PDF/EPUB Качество: Издательский макет или текст (eBook) Количество страниц: 259 Описание: Embark on a transformative journey into the world of Pester and elevate your PowerShell scripting to new heights of robustness, reliability, and efficiency. This comprehensive beginner's guide provides a hands-on approach to PowerShell testing using Pester, empowering you to enhance your code quality with confidence. The book starts with an introduction to Pester, the powerful testing and mocking framework for PowerShell. You'll gain a solid foundation by exploring Pester's fundamental building blocks. The book guides you through the phases of Pester, helping you write your initial Pester code. You will dive into topics such as tags, assertions with Should and parameter filters, and you will explore advanced techniques such as Test Drive and Test Registry. You will discover the art of mocking in Pester and master its advanced testing methodologies. You will gain insights into working without installed modules and seamlessly integrating Pester with Azure DevOps Pipeline for a streamlined testing process. After reading this book, you will have the knowledge and skills to initiate your own exploration into PowerShell testing with Pester. You will transform your scripts into reliable powerhouses, ensuring the resilience and quality of your PowerShell code. What Will You Learn Building blocks and phases of Pester Writing effective Pester tests Assertions, mocking, and advanced testing techniques Integration with Azure DevOps Tags, code coverage Who This Book Is For PowerShell scripters and Pester Framework beginners Совершите увлекательное путешествие в мир Pester и поднимите свои скрипты PowerShell на новые высоты надежности и результативности. Это всеобъемлющее руководство для начинающих содержит практический подход к тестированию PowerShell с использованием Pester, что позволит вам уверенно повышать качество своего кода. Книга начинается с ознакомления с Pester, мощной платформой тестирования и макетирования для PowerShell. Вы получите прочную основу, изучив основные строительные блоки Pester. Книга проведет вас по этапам работы с Pester и поможет написать первоначальный код для Pester. Вы углубитесь в такие темы, как теги, утверждения с фильтрами Should и параметров, а также изучите передовые методы, такие как тест-драйв и тестовый реестр. Вы познакомитесь с искусством макетирования в Pester и освоите его передовые методики тестирования. Вы узнаете о том, как работать без установленных модулей и легко интегрировать Pester с Azure DevOps Pipeline для упрощения процесса тестирования. Прочитав эту книгу, вы приобретете знания и навыки, необходимые для того, чтобы начать самостоятельное изучение тестирования PowerShell с помощью Pester. Вы превратите свои скрипты в надежные источники энергии, обеспечивающие устойчивость и качество кода PowerShell. Чему вы научитесь Основные блоки и этапы работы с Pester Написание эффективных тестов на надоедливость Утверждения, макетирование и продвинутые методы тестирования Интеграция с Azure DevOps Теги, покрытие кода Для кого предназначена эта книга Скриптеры PowerShell и новички в Pester Framework
Примеры страниц (скриншоты)
Оглавление
About the Author .........................................................................................xi About the Technical Reviewer ........................................................................xiii Chapter 1: Unveiling the Power of Pester ........................................................1 What Is Pester? ...........................................................................................2 Why Use Pester? .........................................................................................2 Installing Pester ..........................................................................................4 Navigating the Testing Landscape in PowerShell: Test Types ..............................6 Unit Tests ...................................................................................................7 Integration Tests .........................................................................................7 The Analogy: Orchestrating Script Performances .............................................8 Acceptance Tests ........................................................................................8 The Analogy: The Grand Stage Performance ...................................................9 Pester Test Naming Convention and File Structure ...........................................9 Summary ..................................................................................................11 Chapter 2: Mastering Pester Fundamentals ....................................................13 Understanding Blocks in Pester ....................................................................13 Describe: The Pillar of Logical Organization ....................................................14 Context: Adding Contextual Relevance ..........................................................15 It: Defining Specific Tests ............................................................................15 Setting the Stage with BeforeAll ...................................................................16 Clearing the Stage with AfterAll ....................................................................18 Preparing the Ground with BeforeEach ..........................................................19 Nurturing Cleanliness with AfterEach ............................................................22 Summary .................................................................................................24 Chapter 3: Writing Your First Tests ...............................................................27 Pester Cmdlets ..........................................................................................27 It ............................................................................................................29 Should .....................................................................................................29 Get-ShouldOperator ...................................................................................29 The Structure of a Test ...............................................................................31 Testing True and False Scenarios ..................................................................32 The AAA Pattern: Arrange, Act, Assert ..........................................................34 The AAA Theater: A Pester Production ...........................................................36 A Glimpse into Should Operators ..................................................................37 -HaveParameter Operator ............................................................................37 -BeOfType Operator ....................................................................................39 Running Your Tests .....................................................................................41 Inline Execution .........................................................................................41 Dot Sourcing .............................................................................................42 Import-Module ..........................................................................................43 Invoke the Magic .......................................................................................45 Summary .................................................................................................46 Chapter 4: Mastering Block Scope in Pester ...................................................49 Defining Block Scope ..................................................................................49 Elevating Scope with BeforeAll .....................................................................51 Contextual Hierarchies and Limitations ..........................................................53 The Perils of Unbounded Scope ....................................................................57 Our Ubiquitous Theater Analogy ...................................................................59 Summary ..................................................................................................59 Chapter 5: Data-Driven Tests .......................................................................61 Testing the Waters: Rigorous Evaluation of Remove-Files Functionality ...............61 Reviewing Chapter Insights with Listing 5-2 ....................................................63 Describe ‘Remove-Files’ ...............................................................................64 Context ‘when removing files from the specified path’ ......................................64 It ‘should remove all txt files’ .......................................................................64 Unlocking Efficiency: Data-Driven Testing with -ForEach in Pester ......................65 Introduction to Templates in Pester ...............................................................68 Templates Unveiled .....................................................................................68 Utilizing Templates in Tests ..........................................................................69 Expanding Template Scope ..........................................................................70 A Note on Template Presentation ..................................................................71 Summary ..................................................................................................72 Chapter 6: Navigating the Pester Phases: Discovery and Run ...........................73 Pester’s Discovery Phase .............................................................................73 The Significance of Discovery .......................................................................74 Pester’s Run Phase ......................................................................................78 Run Phase Dynamics ...................................................................................78 Execution Order Complexity .........................................................................79 Navigating the Run Phase ............................................................................82 Visualizing the Phases: Discovery and Run .....................................................84 Script Showcase: The Choreography of Discovery and Run ...............................85 Summary ..................................................................................................87 Chapter 7: TestDrive and TestRegistry ...........................................................89 TestDrive ...................................................................................................89 Behind the TestDrive Curtain ........................................................................90 Setting Up Your TestDrive Playground ............................................................91 Key Points to Remember .............................................................................100 TestRegistry ...............................................................................................100 Behind the TestRegistry Curtain ....................................................................101 Let’s Craft Your Virtual Registry Sandbox .......................................................101 Interacting with Your Virtual Realm: A Practical Demonstration .........................101 Cleaning Up with a Snap .............................................................................103 Key Points to Remember .............................................................................104 Summary ..................................................................................................104 Chapter 8: Tags and Invoke-Pester ................................................................107 Tag Along! Organizing Your Pester Tests with Tags ...........................................108 What Are Tags? ..........................................................................................108 Why Use Tags? ...........................................................................................109 Adding Tags to Your Tests ............................................................................109 Tagging in Action: Unleashing Efficiency ........................................................112 Excluding Tests: The Magic of -Skip and Tags .................................................114 Unleash Granular Testing Power: Running Specific Test Types with Ease .............117 Running Specific Tests with Ease: Your Guide to Pester Efficiency ......................118 Summary ..................................................................................................120 Chapter 9: Mocking Your Way to Success .......................................................123 What Is Mocking? .......................................................................................123 Why Use Mocks to Avoid Real Services? .........................................................124 BeforeAll Block ...........................................................................................129 Describe Block ...........................................................................................130 Context Blocks ...........................................................................................131 IT Block ....................................................................................................131 A Little More Between the Curly Braces, Please ..............................................132 Mocking Best Practices ...............................................................................133 Mocking Complex Cmdlets ..........................................................................135 PSCustomObject .......................................................................................136 There’s More Than One Way to Skin a Cat ....................................................139 Hashtables ...............................................................................................140 When to Use a PSCustomObject over a Hashtable ..........................................141 Import-CliXML ...........................................................................................142 .Net Classes ..............................................................................................144 But Wait, There’s More! ...............................................................................146 Understanding the Transformation: From Listing 9-12 to Listing 9-13 ................149 Listing 9-14 Explained .................................................................................151 Verifying Your Mocks: Ensuring Your Logic Is Sound ........................................152 Understanding the Verification Line ...............................................................155 Using a Parameter Filter ..............................................................................156 Why Would You Use -ParameterFilter? ...........................................................157 How to Use -ParameterFilter ........................................................................157 Gotta Catch ‘em All ....................................................................................159 Validating Output Messages Like a Boss Using -ParameterFilter ........................162 Verifiable Mocks .........................................................................................165 Ensuring the Right Performers Take the Stage ...............................................165 Mocking Without Modules: Ensuring Test Portability .......................................168 Mocking with Modules: Navigating Module Scopes .........................................174 Using the -ModuleName Parameter .............................................................176 Using InModuleScope Script Block ..............................................................177 Summary ................................................................................................179 Chapter 10: Unveiling the Secrets of Code Coverage .....................................181 Demystifying Code Coverage: Unveiling the Map of Your Code’s Tested Terrain ...................................................................................................182 Metrics: Unveiling the Degrees of Coverage ................................................182 Sample Functions and Tests ......................................................................183 Pester Code Coverage Configuration ..........................................................185 Running the Configuration ........................................................................187 Best Practices for Code Coverage Targets ...................................................194 Running Coverage Across a Directory .........................................................195 Understanding Pester’s Coverage.xml .........................................................196 Customizing Output Path ...........................................................................197 Exploring Pester Configuration ...................................................................197 Summary ................................................................................................200 Chapter 11: Streamlining Testing with Azure DevOps and Pester .....................201 Bridging the Gap: The Purpose of Automation ...............................................202 Why Automate Pester Tests and Code Coverage? ...........................................202 Unlocking a New Dimension ........................................................................204 Diving into Azure DevOps – Setting Up the Stage ...........................................204 Ready, Set, Code .......................................................................................204 You Ain’t My Language, but You’re Useful: Working with YAML Pipelines .............206 Diving into the YAML Depths: Azure-Pipeline. yaml ..........................................207 Let’s Break It Down .....................................................................................208 YAML Quirks: Mind the Spaces! .....................................................................209 Beyond the Surface: Exploring YAML’s Potential ...............................................210 Next Steps .................................................................................................211 Bringing Your YAML into Azure DevOps ..........................................................211 Crafting the Pipeline Magic: Bringing Automation to Life ...................................212 Unraveling the Code Coverage Gems: Insights and Learnings ...........................220 Earning Your Badge of Honor: Showcasing Pipeline Success .............................224 Documenting Your DevOps Prowess: README.md and the Status Badge ............225 Summary ..................................................................................................231 Chapter 12: From Theory to Practice: Applying Pester to Your Projects ...............233 Example 1: A Simple Function ......................................................................234 Example 2: Mocking in Action .......................................................................235 Code Breakdown .........................................................................................238 Example 3: Unleashing Data Clarity: Data-Driven Testing with a Twist ................239 Revisiting “ConvertTo-Uppercase” ..................................................................239 Summary ...................................................................................................242 Key Takeaways ............................................................................................242 Moving Forward ...........................................................................................243 Index .........................................................................................................245
Heaume Owen / Хеуме Оуэн - Getting Started with Pester 5: A Beginner\'s Guide / Начало работы с Pester 5: руководство для начинающих [2024, PDF/EPUB, ENG] download torrent for free and without registration
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum