The document introduces go-testdeep, a testing framework for Go that provides a custom comparison engine and operators to easily test nested structures, along with features like accurate error reports, table driven tests, and HTTP request testing. It explains how go-testdeep avoids boilerplate code through methods like Cmp() and shortcuts, allows powerful matching with 62 operators, and encapsulates the testing.T within a td.T instance for additional capabilities.
A better version can be found at https://app.box.com/s/8zuk8yd4x9m7rbvinkb0xztz17x6xoqj
This is the slide for a presentation at Golang Melbourne meetup.
The document discusses Groovy concepts including types, operators, objects, structures, closures, control structures, and methods for strings, lists, and maps. It covers topics such as optional syntax, imports, type checking, numbers, strings, GStrings, lists, maps, enums, operators, date/time operations, and closure usage including delegation and implicit parameters. Groovy allows for optional syntax elements, dynamic typing, closures, and methods to operate on common data types like strings, lists, and maps.
Giordano Scalzo introduces himself as an iOS developer and provides a swift introduction to the Swift programming language. He demonstrates various Swift features through code examples, including functions, closures, classes, structs, enums, generics, and operator overloading. He also discusses unit testing support in Swift through XCTest and Quick. To conclude, he proposes coding a reverse polish notation calculator to demonstrate applying these Swift concepts.
The document discusses good code practices and principles. It begins with an agenda that covers why code quality matters, object oriented principles like SOLID, code smells and heuristics for good code, and concludes with questions. Some key principles discussed include the single responsibility principle, open/closed principle, Liskov substitution principle, and interface segregation principle. Examples are given to illustrate how to apply these principles and improve code quality.
The Ring programming language version 1.5.4 book - Part 35 of 185Mahmoud Samir Fayed
The String class in Ring provides methods for manipulating and working with strings. Some key methods include lower(), upper(), left(), right(), trim(), replace(), split(), and tolist() which converts a string with newline separated lines to a list. The class inherits from the StdBase class and allows initializing strings from other data types. Strings support common operations like concatenation, comparison, and indexing.
When I left Frogtrade, I was asked to provide a presentation on Javascript basics to act as reference material for the PHP developers I left behind. This is that presentation.
The Ring programming language version 1.5.3 book - Part 35 of 184Mahmoud Samir Fayed
The document provides documentation on various functions available in the Ring programming language standard library (stdlib). It describes functions for generating permutations, reading lines from a file, finding substrings, changing substrings, sleeping, checking if a file is the main source file, checking if a directory exists, making directories, getting file sizes, trimming strings, getting the epoch time, executing system commands, listing all files in a folder, and more. It also provides details on classes in the stdlib like the String, List, Stack, Queue, HashTable, Tree, Math, DateTime, File, and other classes along with their methods.
A better version can be found at https://app.box.com/s/8zuk8yd4x9m7rbvinkb0xztz17x6xoqj
This is the slide for a presentation at Golang Melbourne meetup.
The document discusses Groovy concepts including types, operators, objects, structures, closures, control structures, and methods for strings, lists, and maps. It covers topics such as optional syntax, imports, type checking, numbers, strings, GStrings, lists, maps, enums, operators, date/time operations, and closure usage including delegation and implicit parameters. Groovy allows for optional syntax elements, dynamic typing, closures, and methods to operate on common data types like strings, lists, and maps.
Giordano Scalzo introduces himself as an iOS developer and provides a swift introduction to the Swift programming language. He demonstrates various Swift features through code examples, including functions, closures, classes, structs, enums, generics, and operator overloading. He also discusses unit testing support in Swift through XCTest and Quick. To conclude, he proposes coding a reverse polish notation calculator to demonstrate applying these Swift concepts.
The document discusses good code practices and principles. It begins with an agenda that covers why code quality matters, object oriented principles like SOLID, code smells and heuristics for good code, and concludes with questions. Some key principles discussed include the single responsibility principle, open/closed principle, Liskov substitution principle, and interface segregation principle. Examples are given to illustrate how to apply these principles and improve code quality.
The Ring programming language version 1.5.4 book - Part 35 of 185Mahmoud Samir Fayed
The String class in Ring provides methods for manipulating and working with strings. Some key methods include lower(), upper(), left(), right(), trim(), replace(), split(), and tolist() which converts a string with newline separated lines to a list. The class inherits from the StdBase class and allows initializing strings from other data types. Strings support common operations like concatenation, comparison, and indexing.
When I left Frogtrade, I was asked to provide a presentation on Javascript basics to act as reference material for the PHP developers I left behind. This is that presentation.
The Ring programming language version 1.5.3 book - Part 35 of 184Mahmoud Samir Fayed
The document provides documentation on various functions available in the Ring programming language standard library (stdlib). It describes functions for generating permutations, reading lines from a file, finding substrings, changing substrings, sleeping, checking if a file is the main source file, checking if a directory exists, making directories, getting file sizes, trimming strings, getting the epoch time, executing system commands, listing all files in a folder, and more. It also provides details on classes in the stdlib like the String, List, Stack, Queue, HashTable, Tree, Math, DateTime, File, and other classes along with their methods.
This document outlines Chapter 11 from a 2003 Prentice Hall textbook on Strings and Characters in Java. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, comparison, locating/extracting substrings, and concatenation. It also discusses regular expressions and string tokenization. The chapter aims to explain fundamental string processing and manipulation in Java.
The document discusses the authors' initial naive expectations for using Scala and Clojure compared to their actual experience. They initially thought the languages would solve issues like boilerplate code and Java compiler problems, but found they still had to deal with interoperability, immutability, and other functional programming concepts. In the end, Clojure met more of their needs due to its emphasis on seamless interoperability, traits, and pattern matching.
Groovy is a dynamic language for the Java Virtual Machine that aims to provide a concise, readable syntax with features like closures, metaprogramming and domain-specific language support. Some key features include dynamic typing, operator overloading, builders for generating XML/Swing code and the ability to extend any class or category of objects with additional methods. Groovy aims to be fully interoperable with Java while allowing more compact representations of common patterns.
This document discusses code generation programs and macro systems in programming languages. It provides examples of macro systems in Lisp from the late 1950s and OCaml from the early 2000s that allow for abstraction and extension of programming languages through syntactic transformations of code. The examples demonstrate how macros can be used to create custom control structures, bindings, and other syntactic constructs to extend the expressiveness of a language.
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
The document discusses functional programming and event sourcing. It begins with an overview of functional programming principles like avoiding side effects and variable mutation. It then provides examples of modeling user data retrieval in a functional way using classes like Cache, UserRepo, and UserFinder. The examples demonstrate functional patterns like avoiding stateful objects and embracing immutable and recursive functions. The document argues that functional programming and event sourcing are well-aligned due to their shared emphasis on immutable data models and avoidance of shared state.
Unit testing with PHPUnit allows developers to automate testing of classes and functions. Tests can validate expected outputs and behaviors and catch bugs. PHPUnit provides assertions to validate results and annotations to organize tests, mark them as incomplete, or specify expected exceptions. Fixtures can set up and tear down test environments and data. Writing thorough automated tests improves code quality and prevents regressions.
The document provides an overview of ObjectSpace and minitest features in Ruby including:
- ObjectSpace allows querying and iterating over all living objects and provides methods to count object sizes and types.
- Minitest is a simplified and streamlined version of Test::Unit with a similar interface to RSpec. It provides assertions like refute instead of assert_not and skips tests.
- ObjectSpace and minitest/autorun are useful for testing, debugging, and understanding memory usage and object lifetimes in Ruby.
The document discusses clean coding practices for Java developers. It covers topics such as choosing meaningful names for variables, methods, and classes; writing code that is easy for others to understand; breaking methods down into single logical steps; and using fluent APIs to make code more readable. The presentation provides examples of clean code and ways to refactor code to follow best practices.
Spread syntax and rest syntax allow iterable objects like arrays and strings to be expanded in function calls, array literals, and object literals. Spread syntax spreads the elements into separate arguments/elements, while rest syntax collects remaining elements into a single variable. Tagged template literals allow functions to operate on template literal strings before they are evaluated. Decorators propose a way to annotate and modify classes and class elements.
The document discusses abstract syntax tree (AST) transformations in Groovy and Java. It covers several tools and techniques for AST transformations including Lombok, Groovy, CodeNarc, IntelliJ IDEA, Mirah macros, and how they allow generating code, performing static analysis, and rewriting code at compile time through analyzing and modifying the AST. The key topics are how these tools work by compiling code to an AST, analyzing and modifying the AST nodes, and sometimes generating source code from the transformed AST.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 2:
- Slots vs Dictionaries
- Basic and Advanced Generators
- Async programming
The document appears to be code or data that is not easily summarized due to its unstructured nature. It contains various symbols, brackets, and other characters with no clear meaning or context provided.
The document discusses the Apache Commons project, which develops reusable Java components. It notes that Commons components allow for faster and smaller development by avoiding reinventing common functions. The document outlines several active Commons components like Collections, IO, Lang, and Logging, as well as sandbox and dormant components. It emphasizes that 80% of Commons components have no dependencies on each other, promoting flexibility and reuse.
The document provides an overview of essential JavaScript concepts for survival including scope, literals and constructors, functions, and testing frameworks. It discusses best practices for declaring variables with var, using constructor functions and prototypes to create objects, encapsulating functions and data with closures, and popular JavaScript testing frameworks like QUnit, JSUnit, and Vows.
JavaScript for Unleashed a game about a robbery in London and its pretty long i do not know why you would want it but here have it :P also this is not pro its just for school because i am a loner like that and i have nothing better to do
The document discusses code generation on the JVM using various tools and frameworks. It provides an overview of Lombok for generating Java boilerplate code, Groovy AST transformations, CodeNarc for static analysis, and Spock, GContracts, and Groovy++ for framework-oriented code generation. It also discusses generating code at compile time using abstract syntax trees.
Groovy Closures allows defining and passing code blocks (closures) as arguments to methods. Closures in Groovy are similar to lambdas in Java 8 and support defining parameters, implicit parameters, and variable arguments. Closures can be passed around and used within methods to perform operations on method arguments or variables.
This document provides an introduction to JavaScript, covering topics such as:
- What JavaScript is and its origins
- How to set up the browser console and load scripts
- Data types in JavaScript including numbers, strings, Booleans, objects, and more
- Variables, operators, and comparisons
- Logical flow and conditionals
- Basic programming concepts like functions, events, and objects
The document gives examples and explanations for JavaScript syntax and fundamentals to help newcomers get started with the language. It also outlines a simple task manager project as an introduction to building applications with JavaScript.
Reviews examples of details on how to pass data to a stored procedure and how to return data from a stored procedure. Further shows how to pass status or debugging messages from stored procedure, including message localization.
The document discusses Scala as a potential replacement for Java on the JVM. It provides quotes from several influential Java developers who express their view that Scala is the most capable replacement for Java currently available on the JVM, and the momentum behind Scala is growing. The document also briefly outlines an agenda for introducing Scala, covering basic syntax, patterns, functions, classes and traits.
This document outlines Chapter 11 from a 2003 Prentice Hall textbook on Strings and Characters in Java. It covers the String, StringBuffer, and Character classes, including constructors, methods for length, comparison, locating/extracting substrings, and concatenation. It also discusses regular expressions and string tokenization. The chapter aims to explain fundamental string processing and manipulation in Java.
The document discusses the authors' initial naive expectations for using Scala and Clojure compared to their actual experience. They initially thought the languages would solve issues like boilerplate code and Java compiler problems, but found they still had to deal with interoperability, immutability, and other functional programming concepts. In the end, Clojure met more of their needs due to its emphasis on seamless interoperability, traits, and pattern matching.
Groovy is a dynamic language for the Java Virtual Machine that aims to provide a concise, readable syntax with features like closures, metaprogramming and domain-specific language support. Some key features include dynamic typing, operator overloading, builders for generating XML/Swing code and the ability to extend any class or category of objects with additional methods. Groovy aims to be fully interoperable with Java while allowing more compact representations of common patterns.
This document discusses code generation programs and macro systems in programming languages. It provides examples of macro systems in Lisp from the late 1950s and OCaml from the early 2000s that allow for abstraction and extension of programming languages through syntactic transformations of code. The examples demonstrate how macros can be used to create custom control structures, bindings, and other syntactic constructs to extend the expressiveness of a language.
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
The document discusses functional programming and event sourcing. It begins with an overview of functional programming principles like avoiding side effects and variable mutation. It then provides examples of modeling user data retrieval in a functional way using classes like Cache, UserRepo, and UserFinder. The examples demonstrate functional patterns like avoiding stateful objects and embracing immutable and recursive functions. The document argues that functional programming and event sourcing are well-aligned due to their shared emphasis on immutable data models and avoidance of shared state.
Unit testing with PHPUnit allows developers to automate testing of classes and functions. Tests can validate expected outputs and behaviors and catch bugs. PHPUnit provides assertions to validate results and annotations to organize tests, mark them as incomplete, or specify expected exceptions. Fixtures can set up and tear down test environments and data. Writing thorough automated tests improves code quality and prevents regressions.
The document provides an overview of ObjectSpace and minitest features in Ruby including:
- ObjectSpace allows querying and iterating over all living objects and provides methods to count object sizes and types.
- Minitest is a simplified and streamlined version of Test::Unit with a similar interface to RSpec. It provides assertions like refute instead of assert_not and skips tests.
- ObjectSpace and minitest/autorun are useful for testing, debugging, and understanding memory usage and object lifetimes in Ruby.
The document discusses clean coding practices for Java developers. It covers topics such as choosing meaningful names for variables, methods, and classes; writing code that is easy for others to understand; breaking methods down into single logical steps; and using fluent APIs to make code more readable. The presentation provides examples of clean code and ways to refactor code to follow best practices.
Spread syntax and rest syntax allow iterable objects like arrays and strings to be expanded in function calls, array literals, and object literals. Spread syntax spreads the elements into separate arguments/elements, while rest syntax collects remaining elements into a single variable. Tagged template literals allow functions to operate on template literal strings before they are evaluated. Decorators propose a way to annotate and modify classes and class elements.
The document discusses abstract syntax tree (AST) transformations in Groovy and Java. It covers several tools and techniques for AST transformations including Lombok, Groovy, CodeNarc, IntelliJ IDEA, Mirah macros, and how they allow generating code, performing static analysis, and rewriting code at compile time through analyzing and modifying the AST. The key topics are how these tools work by compiling code to an AST, analyzing and modifying the AST nodes, and sometimes generating source code from the transformed AST.
Slides from Advaned Python lectures I gave recently in Haifa Linux club
Advanced python, Part 2:
- Slots vs Dictionaries
- Basic and Advanced Generators
- Async programming
The document appears to be code or data that is not easily summarized due to its unstructured nature. It contains various symbols, brackets, and other characters with no clear meaning or context provided.
The document discusses the Apache Commons project, which develops reusable Java components. It notes that Commons components allow for faster and smaller development by avoiding reinventing common functions. The document outlines several active Commons components like Collections, IO, Lang, and Logging, as well as sandbox and dormant components. It emphasizes that 80% of Commons components have no dependencies on each other, promoting flexibility and reuse.
The document provides an overview of essential JavaScript concepts for survival including scope, literals and constructors, functions, and testing frameworks. It discusses best practices for declaring variables with var, using constructor functions and prototypes to create objects, encapsulating functions and data with closures, and popular JavaScript testing frameworks like QUnit, JSUnit, and Vows.
JavaScript for Unleashed a game about a robbery in London and its pretty long i do not know why you would want it but here have it :P also this is not pro its just for school because i am a loner like that and i have nothing better to do
The document discusses code generation on the JVM using various tools and frameworks. It provides an overview of Lombok for generating Java boilerplate code, Groovy AST transformations, CodeNarc for static analysis, and Spock, GContracts, and Groovy++ for framework-oriented code generation. It also discusses generating code at compile time using abstract syntax trees.
Groovy Closures allows defining and passing code blocks (closures) as arguments to methods. Closures in Groovy are similar to lambdas in Java 8 and support defining parameters, implicit parameters, and variable arguments. Closures can be passed around and used within methods to perform operations on method arguments or variables.
This document provides an introduction to JavaScript, covering topics such as:
- What JavaScript is and its origins
- How to set up the browser console and load scripts
- Data types in JavaScript including numbers, strings, Booleans, objects, and more
- Variables, operators, and comparisons
- Logical flow and conditionals
- Basic programming concepts like functions, events, and objects
The document gives examples and explanations for JavaScript syntax and fundamentals to help newcomers get started with the language. It also outlines a simple task manager project as an introduction to building applications with JavaScript.
Reviews examples of details on how to pass data to a stored procedure and how to return data from a stored procedure. Further shows how to pass status or debugging messages from stored procedure, including message localization.
The document discusses Scala as a potential replacement for Java on the JVM. It provides quotes from several influential Java developers who express their view that Scala is the most capable replacement for Java currently available on the JVM, and the momentum behind Scala is growing. The document also briefly outlines an agenda for introducing Scala, covering basic syntax, patterns, functions, classes and traits.
This is my attempt at a look at some of the features of C++11, and more importantly, describing some of the style changes in C++11 that will make programmers more productive and programs more efficient.
The document discusses behavior driven development (BDD) and test-driven development (TDD). It shows an example of incrementally developing a FizzBuzz program using TDD and JUnit tests. First, a single test is written to verify the output for the number 1. Then tests are added and code is modified to pass each new test, building up the full FizzBuzz logic over multiple test/code iterations. The document also discusses differences between traditional TDD testing and BDD-style testing, where test method names are written as sentences describing expected behavior.
The presentation shows major features of the new C++ standard (language and the library). The full list of new things is very broad, so I've categorized them to be easier to understand.
This document summarizes a talk given at YAPC Tokyo 2010 about calling C code from Perl using various techniques. It discusses Ctypes, a module for directly calling C functions without XS; Libperl++, a C++ library for embedding and extending Perl; and XS++, which allows writing C++ classes that integrate seamlessly with Perl using a special syntax.
This talk was part tongue in cheek, part serious, but entirely fun and given twice as a lightning talk - once at Europython & once at the ACCU python uk 05. It presents a generic python like language parser which does actually work. Think of it as an alternative to brackets in Lisp!
Prototype extends the functionality of JavaScript arrays by mixing in the Enumerable module and adding additional methods. It allows arrays to be iterated over and manipulated in more powerful ways than default JavaScript arrays, but using the for-in loop to iterate over prototype extended arrays may enumerate extended methods. The document provides examples of alternative looping constructs and describes numerous methods added to the Array prototype by the Prototype library.
This document summarizes a talk given about Nokia's migration to Scala for its Places API. The key points are:
1) Nokia migrated its Places API codebase to Scala to take advantage of Scala's features like its powerful type system, immutable data structures, and functional programming capabilities.
2) The migration was done gradually over time while continuing to develop new features. They discovered many benefits of Scala along the way like improved test readability and JSON parsing capabilities.
3) Nokia uses Scala features like case classes, options, and functions to model data and add type safety to its codebase. This uncovered bugs that would have been hard to find in Java.
Slides from talk given at Ithaca Web Group and GORGES on CoffeeScript.
The focus is on explaining to people who haven't tried it yet that it's more than syntactic sugar. There are several real life code examples but they were explained verbally so they may not be super helpful if you don't know CoffeeScript yet.
It's an overview, not a tutorial.
Spock is a Groovy-based testing framework that provides features for writing tests in a clear, expressive, and highly readable manner. Some key features highlighted in the document include:
- Spock tests are structured into blocks like "given", "when", "then" that give tests a clear structure and meaning.
- Spock includes powerful and easy to read assertion methods as well as the ability to display diffs when expectations are not met.
- Spock supports mocking and stubbing of dependencies in a simple way.
- Data-driven testing is first-class in Spock through features like the "where" block that allows input test data to be specified in a table.
Spock is a Groovy-based testing framework that provides a powerful and concise specification testing language. Some key features highlighted in the document include:
- Spock tests are structured into blocks like "given", "when", "then" that define meaning.
- Spock includes simple and detailed assertions as well as support for mocking, stubbing, data-driven testing, and property-based testing.
- Data-driven tests in Spock can use a table-like structure to define input test data in a readable way.
- The document discusses how machine learning can be seen as automated test-driven development, and how property-based testing is a good specification for automated code generation
You already know TDD, your code coverage is almost at 80%, jUnit has no secret for you? But you feel that you could do more with your tests, the tools you use have limitations. Or maybe you're just tired of assertEquals?
Don't panic! We will see how you can code tests. We will look upon:
- Mutation Testing
- BDD, Behaviour Driven Development
- Property Testing
Making JavaScript Libraries More ApproachablePamela Fox
A talk given at NotConf in Phoenix, Texas in 2012.
(Alternative title: Why nested ternary operators make me want to kick inanimate objects in the nuts.)
The document provides an overview of key concepts in the C# programming language including variables and data types, arrays, conditional logic, loops, methods, parameters, and delegates. It discusses basic syntax, operators, and how to perform common tasks like type conversions and working with dates and strings. The goal is to give readers enough information to get started with C# as well as refer back to for language details while working through ASP.NET examples.
The document contains code examples demonstrating various Scala programming concepts such as functions, pattern matching, traits, actors and more. It also includes links to online resources for learning Scala.
In this chapter we will explore strings. We are going to explain how they are implemented in C# and in what way we can process text content. Additionally, we will go through different methods for manipulating a text: we will learn how to compare strings, how to search for substrings, how to extract substrings upon previously settled parameters and last but not least how to split a string by separator chars. We will demonstrate how to correctly build strings with the StringBuilder class. We will provide a short but very useful information for the most commonly used regular expressions. We will discuss some classes for efficient construction of strings. Finally, we will take a look at the methods and classes for achieving more elegant and stricter formatting of the text content.
The document discusses various Java programming concepts such as Hello World, primitive data types, variables, input/output, and control structures like if/else, switch/case, while loops. It provides examples of declaring and using variables, type casting between primitives, and commenting code. Various Java classes for input/output like Scanner and System.out are demonstrated.
Build the Next Generation of Apps with the Einstein 1 Platform.
Rejoignez Philippe Ozil pour une session de workshops qui vous guidera à travers les détails de la plateforme Einstein 1, l'importance des données pour la création d'applications d'intelligence artificielle et les différents outils et technologies que Salesforce propose pour vous apporter tous les bénéfices de l'IA.
Comparative analysis between traditional aquaponics and reconstructed aquapon...bijceesjournal
The aquaponic system of planting is a method that does not require soil usage. It is a method that only needs water, fish, lava rocks (a substitute for soil), and plants. Aquaponic systems are sustainable and environmentally friendly. Its use not only helps to plant in small spaces but also helps reduce artificial chemical use and minimizes excess water use, as aquaponics consumes 90% less water than soil-based gardening. The study applied a descriptive and experimental design to assess and compare conventional and reconstructed aquaponic methods for reproducing tomatoes. The researchers created an observation checklist to determine the significant factors of the study. The study aims to determine the significant difference between traditional aquaponics and reconstructed aquaponics systems propagating tomatoes in terms of height, weight, girth, and number of fruits. The reconstructed aquaponics system’s higher growth yield results in a much more nourished crop than the traditional aquaponics system. It is superior in its number of fruits, height, weight, and girth measurement. Moreover, the reconstructed aquaponics system is proven to eliminate all the hindrances present in the traditional aquaponics system, which are overcrowding of fish, algae growth, pest problems, contaminated water, and dead fish.
AI for Legal Research with applications, toolsmahaffeycheryld
AI applications in legal research include rapid document analysis, case law review, and statute interpretation. AI-powered tools can sift through vast legal databases to find relevant precedents and citations, enhancing research accuracy and speed. They assist in legal writing by drafting and proofreading documents. Predictive analytics help foresee case outcomes based on historical data, aiding in strategic decision-making. AI also automates routine tasks like contract review and due diligence, freeing up lawyers to focus on complex legal issues. These applications make legal research more efficient, cost-effective, and accessible.
Generative AI Use cases applications solutions and implementation.pdfmahaffeycheryld
Generative AI solutions encompass a range of capabilities from content creation to complex problem-solving across industries. Implementing generative AI involves identifying specific business needs, developing tailored AI models using techniques like GANs and VAEs, and integrating these models into existing workflows. Data quality and continuous model refinement are crucial for effective implementation. Businesses must also consider ethical implications and ensure transparency in AI decision-making. Generative AI's implementation aims to enhance efficiency, creativity, and innovation by leveraging autonomous generation and sophisticated learning algorithms to meet diverse business challenges.
https://www.leewayhertz.com/generative-ai-use-cases-and-applications/
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...IJECEIAES
Medical image analysis has witnessed significant advancements with deep learning techniques. In the domain of brain tumor segmentation, the ability to
precisely delineate tumor boundaries from magnetic resonance imaging (MRI)
scans holds profound implications for diagnosis. This study presents an ensemble convolutional neural network (CNN) with transfer learning, integrating
the state-of-the-art Deeplabv3+ architecture with the ResNet18 backbone. The
model is rigorously trained and evaluated, exhibiting remarkable performance
metrics, including an impressive global accuracy of 99.286%, a high-class accuracy of 82.191%, a mean intersection over union (IoU) of 79.900%, a weighted
IoU of 98.620%, and a Boundary F1 (BF) score of 83.303%. Notably, a detailed comparative analysis with existing methods showcases the superiority of
our proposed model. These findings underscore the model’s competence in precise brain tumor localization, underscoring its potential to revolutionize medical
image analysis and enhance healthcare outcomes. This research paves the way
for future exploration and optimization of advanced CNN models in medical
imaging, emphasizing addressing false positives and resource efficiency.
Embedded machine learning-based road conditions and driving behavior monitoringIJECEIAES
Car accident rates have increased in recent years, resulting in losses in human lives, properties, and other financial costs. An embedded machine learning-based system is developed to address this critical issue. The system can monitor road conditions, detect driving patterns, and identify aggressive driving behaviors. The system is based on neural networks trained on a comprehensive dataset of driving events, driving styles, and road conditions. The system effectively detects potential risks and helps mitigate the frequency and impact of accidents. The primary goal is to ensure the safety of drivers and vehicles. Collecting data involved gathering information on three key road events: normal street and normal drive, speed bumps, circular yellow speed bumps, and three aggressive driving actions: sudden start, sudden stop, and sudden entry. The gathered data is processed and analyzed using a machine learning system designed for limited power and memory devices. The developed system resulted in 91.9% accuracy, 93.6% precision, and 92% recall. The achieved inference time on an Arduino Nano 33 BLE Sense with a 32-bit CPU running at 64 MHz is 34 ms and requires 2.6 kB peak RAM and 139.9 kB program flash memory, making it suitable for resource-constrained embedded systems.
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELijaia
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
VARIABLE FREQUENCY DRIVE. VFDs are widely used in industrial applications for...PIMR BHOPAL
Variable frequency drive .A Variable Frequency Drive (VFD) is an electronic device used to control the speed and torque of an electric motor by varying the frequency and voltage of its power supply. VFDs are widely used in industrial applications for motor control, providing significant energy savings and precise motor operation.
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
Discover the latest insights on Data Driven Maintenance with our comprehensive webinar presentation. Learn about traditional maintenance challenges, the right approach to utilizing data, and the benefits of adopting a Data Driven Maintenance strategy. Explore real-world examples, industry best practices, and innovative solutions like FMECA and the D3M model. This presentation, led by expert Jules Oudmans, is essential for asset owners looking to optimize their maintenance processes and leverage digital technologies for improved efficiency and performance. Download now to stay ahead in the evolving maintenance landscape.
4. Go testing
Why a test framework?
To avoid boilerplate code, especially error reports �
�
import "testing"
func TestGetPerson(t *testing.T) {
person, err := GetPerson("Bob")
if err != nil {
t.Errorf("GetPerson returned error %s", err)
} else {
if person.Name != "Bob" {
t.Errorf(`Name: got=%q expected="Bob"`, person.Name)
}
if person.Age != 42 {
t.Errorf("Age: got=%s expected=42", person.Age)
}
}
}
4
5. Using a test framework
For example using go-testdeep �
�
import (
"testing"
"github.com/maxatome/go-testdeep/td"
)
func TestGetPerson(t *testing.T) {
person, err := GetPerson("Bob")
if td.CmpNoError(t, err, "GetPerson does not return an error") {
td.Cmp(t, person, Person{Name: "Bob", Age: 42}, "GetPerson returns Bob")
}
}
In most cases, there is not even test names �
�
func TestGetPerson(t *testing.T) {
person, err := GetPerson("Bob")
if td.CmpNoError(t, err) {
td.Cmp(t, person, Person{Name: "Bob", Age: 42})
}
}
5
6. Why go-testdeep instead of an existing framework?
Custom comparison engine allowing the use of powerful operators
Accurate and colored error reports
62 operators to match in all circumstances
Fully documented with plenty examples
Consistent API: got parameter is always before expected one
Very few basic functions, all others are operators shortcuts (args... allow to name tests):
Cmp(t TestingT, got, expected interface{}, args ...interface{}) bool
CmpError(t TestingT, got error, args ...interface{}) bool
CmpFalse(t TestingT, got interface{}, args ...interface{}) bool
CmpLax(t TestingT, got, expected interface{}, args ...interface{}) bool
CmpNoError(t TestingT, got error, args ...interface{}) bool
CmpNot(t TestingT, got, notExpected interface{}, args ...interface{}) bool
CmpNotPanic(t TestingT, fn func(), args ...interface{}) bool
CmpPanic(t TestingT, fn func(), expectedPanic interface{}, args ...interface{}) bool
CmpTrue(t TestingT, got interface{}, args ...interface{}) bool
6
7. Why go-testdeep instead of an existing framework? (part 2)
Unique anchoring feature, to easily test literals
JSON content testable like never before
Table driven tests are simple to write and maintain
Comparison engine can be configured to be lax, to ignore struct unexported fields, to treat
specifically some types, to display N errors before giving up
Efficient flattening of []X slices into ...interface{} of variadic functions
A function returning several values can be tested in one call, thanks to tuples
tdhttp helper allows to easily test HTTP APIs regardless of the web framework used
tdsuite helper handles consistent and flexible suites of tests
Probably some others reasons you will discover by yourself :) 7
8. Test names
As many testing frameworks, tests can optionally be named �
�
td.Cmp(t, got, "Bob", `Hey! got has to be "Bob" here!`)
Each Cmp* function cleverly accepts fmt.Fprintf or fmt.Fprint parameters in args
func Cmp(t TestingT, got, expected interface{}, args ...interface{}) bool
The doc says:
// "args..." are optional and allow to name the test. This name is
// used in case of failure to qualify the test. If len(args) > 1 and
// the first item of "args" is a string and contains a '%' rune then
// fmt.Fprintf is used to compose the name, else "args" are passed to
// fmt.Fprint. Do not forget it is the name of the test, not the
// reason of a potential failure.
So, no risk of mistake between Cmp and a (nonexistent) Cmpf: only use Cmp! �
�
td.Cmp(t, got, 12, "Check got is ", 12) → fmt.Fprint
td.Cmp(t, got, 12, "Check got is %d", 12) → fmt.Fprintf
td.Cmp(t, got, 12, lastErr) → fmt.Fprint
8
9. Custom comparison engine
Derived from reflect.DeepEqual and heavily modified to integrate operators handling
It allows go-testdeep to know exactly where a test fails in a big structure, and even to
continue testing in this structure to report several mismatches at the same time (up to 10
by default)
Reports are also very accurate and colorized, instead of awful diffs you see elsewhere…
service_test.go:449: Failed test 'Service is OK'
SERVICE.Owner.Age: values differ
got: 22
expected: 40 ≤ got ≤ 45
[under operator Between at service_test.go:451]
SERVICE.Owner.Name: values differ
got: "Bob"
expected: "Alice"
[under operator Struct at service_test.go:450]
This is how we got here:
testOneService() internal/service/service_test.go:449
TestService() internal/service/service_test.go:430
only displayed if call stack is deep
or if not at the root of the module
to help to find quickly the error
only displayed if the expected
value belongs to an operator
test name if provided
location & reason of failure
9
10. 62 operators to match in all circumstances
Some examples, see the expected (3rd) parameter �
�
here ↴
td.Cmp(t, age, td.Between(40, 45))
td.Cmp(t, headers, td.ContainsKey("X-Ovh"))
td.Cmp(t, err, td.Contains("Internal server error"))
td.Cmp(t, grants, td.Len(td.Gt(2)))
td.Cmp(t, price, td.N(float64(12.03), float64(0.01)))
td.Cmp(t, name, td.Re(`^[A-Z][A-Za-z-]+z`))
td.Cmp(t, ids, td.Set(789, 456, 123))
td.Cmp(t, tags, td.SuperMapOf(map[string]bool{"enabled": true, "shared": true}, nil))
All operators follow
All Contains Isa MapEach NotNil Smuggle SuperJSONOf
Any ContainsKey JSON N NotZero SStruct SuperMapOf
Array Delay JSONPointer NaN PPtr String SuperSetOf
ArrayEach Empty Keys Nil Ptr Struct SuperSliceOf
Bag Gt Lax None Re SubBagOf Tag
Between Gte Len Not ReAll SubJSONOf TruncTime
Cap HasPrefix Lt NotAny Set SubMapOf Values
Catch HasSuffix Lte NotEmpty Shallow SubSetOf Zero
Code Ignore Map NotNaN Slice SuperBagOf
10
11. Almost all operators have shortcuts
Always the same pattern
td.Cmp(t, got, td.HasPrefix(expectedPrefix), …) → td.CmpHasPrefix(t, got, expectedPrefix, …)
td.Cmp(t, got, td.HasSuffix(expectedSuffix), …) → td.CmpHasSuffix(t, got, expectedSuffix, …)
¯¯¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯¯¯
td.Cmp(t, got, td.NotEmpty(), …) → td.CmpNotEmpty(t, got, …)
¯¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯¯
You just understood CmpNot and CmpLax were in fact shortcuts :)
td.Cmp(t, got, td.Not(notExpected)) → td.CmpNot(t, got, notExpected)
td.Cmp(t, got, td.Lax(expected)) → td.CmpLax(t, got, expected)
¯¯¯ ¯¯¯
Using a shortcut is not mandatory, it could just be more readable in some cases (or not)
4 operators without shortcut: Catch, Delay, Ignore, Tag, because having a shortcut in these
cases is a nonsense 11
12. Matching nested structs/slices/maps
Take this structure returned by a GetPerson function:
type Person struct {
ID int64 `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
Children []*Person `json:"children"`
}
We want to check:
• Bob, is 40 to 45 year-old
• has a non-zero ID
• has 2 children
◦ Alice, 20 year-old, and Brian, 18 year-old
◦ both with a non-zero ID too
◦ both without any children 12
13. Operators in nested structs/slices/maps — 1/4 classic way, like others
Like other frameworks, we can do �
�
got := GetPerson("Bob")
td.Cmp(t, got.ID, td.NotZero())
td.Cmp(t, got.Name, "Bob")
td.Cmp(t, got.Age, td.Between(40, 45))
if td.Cmp(t, got.Children, td.Len(2)) {
// Alice
td.Cmp(t, got.Children[0].ID, td.NotZero())
td.Cmp(t, got.Children[0].Name, "Alice")
td.Cmp(t, got.Children[0].Age, 20)
td.Cmp(t, got.Children[0].Children, td.Len(0))
// Brian
td.Cmp(t, got.Children[1].ID, td.NotZero())
td.Cmp(t, got.Children[1].Name, "Brian")
td.Cmp(t, got.Children[1].Age, 18)
td.Cmp(t, got.Children[1].Children, td.Len(0))
}
Exercise: replace the following shortcuts in the code above ↑ �
�
CmpNotZero(t, …) — CmpBetween(t, …) — CmpLen(t, …)
13
14. Operators in nested structs/slices/maps — 2/4 using SStruct operator
SStruct is the strict-Struct operator
SStruct(model interface{}, expectedFields StructFields)
Strict because omitted fields are checked against their zero value, instead of ignoring them
�
�
td.Cmp(t, GetPerson("Bob"),
td.SStruct(Person{Name: "Bob"},
td.StructFields{
"ID": td.NotZero(),
"Age": td.Between(40, 45),
"Children": td.Bag(
td.SStruct(&Person{Name: "Alice", Age: 20},
td.StructFields{"ID": td.NotZero()}),
td.SStruct(&Person{Name: "Brian", Age: 18},
td.StructFields{"ID": td.NotZero()}),
),
},
))
14
15. Operators in nested structs/slices/maps — 3/4 using JSON operator
JSON allows to compare the JSON representation (comments are allowed!) �
�
td.Cmp(t, GetPerson("Bob"), td.JSON(`
{
"id": $1, // ← placeholder (could be "$1" or $BobAge, see JSON operator doc)
"name": "Bob",
"age": Between(40, 45), // yes, most operators are embedable
"children": [
{
"id": NotZero(),
"name": "Alice",
"age": 20,
"children": Empty(), /* null is "empty" */
},
{
"id": NotZero(),
"name": "Brian",
"age": 18,
"children": Nil(),
}
]
}`,
td.Catch(&bobID, td.NotZero()), // $1 catches the ID of Bob on the fly and sets bobID var
))
15
16. Operators in nested structs/slices/maps — 3/4 using JSON + Bag ops
JSON allows to compare the JSON representation (comments are allowed!) �
�
td.Cmp(t, GetPerson("Bob"), td.JSON(`
{
"id": $1, // ← placeholder (could be "$1" or $BobAge, see JSON operator doc)
"name": "Bob",
"age": Between(40, 45), // yes, most operators are embedable
"children": Bag( // ← Bag HERE
{
"id": NotZero(),
"name": "Brian",
"age": 18,
"children": Nil(),
},
{
"id": NotZero(),
"name": "Alice",
"age": 20,
"children": Empty(), /* null is "empty" */
},
)
}`,
td.Catch(&bobID, td.NotZero()), // $1 catches the ID of Bob on the fly and sets bobID var
))
16
17. Operators in nested structs/slices/maps — 4/4 using anchoring
Anchoring feature allows to put operators directly in literals
To keep track of anchors, a td.T instance is needed �
�
assert := td.Assert(t)
assert.Cmp(GetPerson("Bob"),
Person{
ID: assert.A(td.Catch(&bobID, td.NotZero())).(int64),
Name: "Bob",
Age: assert.A(td.Between(40, 45)).(int),
Children: []*Person{
{
ID: assert.A(td.NotZero(), int64(0)).(int64),
Name: "Alice",
Age: 20,
},
{
ID: assert.A(td.NotZero(), int64(0)).(int64),
Name: "Brian",
Age: 18,
},
},
})
17
18. Anatomy of an anchor
Anchors are created using A (or its alias Anchor) method of *td.T
It generates a specific value that can be retrieved during the comparison process
func (t *T) A(operator TestDeep, model ...interface{}) interface{}
│ └ mandatory if the type can not be guessed from the operator
└ the operator to use
// model is not needed when operator knows the type behind the operator
assert.A(td.Between(40, 45)).(int)
// model is mandatory if the type behind the operator cannot be guessed
assert.A(td.NotZero(), int64(666)).(int64)
// for reflect lovers, they can use the longer version
assert.A(td.NotZero(), reflect.TypeOf(int64(666))).(int64)
Conflicts are possible, so be careful with 8 and 16 bits types
Work for pointers, slices, maps, but not available for bool types
Specific handling is needed for structs, see AddAnchorableStructType function 18
19. Encapsulating testing.T
Instead of doing �
�
func TestVals(t *testing.T) {
got := GetPerson("Bob")
td.Cmp(t, got.Age, td.Between(40, 45))
td.Cmp(t, got.Children, td.Len(2))
}
one can build a td.T instance encapsulating the testing.T one �
�
func TestVals(t *testing.T) {
assert := td.Assert(t)
got := GetPerson("Bob")
assert.Cmp(got.Age, td.Between(40, 45))
assert.Cmp(got.Children, td.Len(2))
}
Building a td.T instance provides some advantages over using td.Cmp* functions directly19
20. td.T — Introduction — 1/6
type T struct {
testing.TB // implemented by *testing.T
Config ContextConfig // defaults to td.DefaultContextConfig
}
See testing.TB interface, ContextConfig struct and DefaultContextConfig variable
Construction:
func NewT(t testing.TB, config ...ContextConfig) *T // inherit properties from t
func Assert(t testing.TB, config ...ContextConfig) *T // test failures are not fatal
func Require(t testing.TB, config ...ContextConfig) *T // t.Fatal if a test fails
func AssertRequire(t testing.TB, config ...ContextConfig) (*T, *T) // Assert() + Require()
Configuring *td.T instance (return a new instance):
func (t *T) BeLax(enable ...bool) *T // enable/disable strict type comparison
func (t *T) FailureIsFatal(enable ...bool) *T // enable/disable failure "fatality"
func (t *T) IgnoreUnexported(types ...interface{}) *T // ignore unexported fields of some structs
func (t *T) RootName(rootName string) *T // change data root name, "DATA" by default
func (t *T) UseEqual(types ...interface{}) *T // delegate cmp to Equal() method if available
20
22. td.T — Shortcuts — 3/6
Shortcuts, as for td functions, follow always the same pattern:
t.Cmp(got, td.HasPrefix(expected), …) → t.HasPrefix(got, expected, …)
t.Cmp(got, td.HasSuffix(expected), …) → t.HasSuffix(got, expected, …)
¯¯¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯¯¯
t.Cmp(got, td.NotEmpty(), …) → t.NotEmpty(t, got, …)
¯¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯¯
So yes, T.Not is in fact a shortcut:
t.Cmp(got, td.Not(notExpected)) → t.Not(got, notExpected)
¯¯¯ ¯¯¯
The only exception is T.CmpLax method, shortcut of td.Lax operator, it is more relevant
than a T.Lax method
Same 4 operators without shortcut: Catch, Delay, Ignore, Tag, because having a shortcut in
these cases is a nonsense 22
23. td.T — Anchoring — 4/6
Anchoring related methods:
func (t *T) A(operator TestDeep, model ...interface{}) interface{}
func (t *T) Anchor(operator TestDeep, model ...interface{}) interface{}
func (t *T) AnchorsPersistTemporarily() func()
func (t *T) DoAnchorsPersist() bool
func (t *T) ResetAnchors()
func (t *T) SetAnchorsPersist(persist bool)
A and Anchor allow both to anchor an operator, the first is just shorter to write
By default, anchoring is effective only for the next Cmp* call, but this can be overridden
thanks to SetAnchorsPersist and AnchorsPersistTemporarily
Useful for helpers writers or table driven tests afficionados :) 23
25. td.T — Advanced usage — 6/6
WithCmpHooks allows to register comparison functions for some types �
�
assert = assert.WithCmpHooks(
func (got, expected reflect.Value) bool {
return td.EqDeeply(got.Interface(), expected.Interface())
},
(time.Time).Equal, // bypasses the UseEqual flag
)
x := 123
assert.Cmp(reflect.ValueOf(x), reflect.ValueOf(123)) // succeeds
WithSmuggleHooks allows to register functions to alter the data before comparing it �
�
assert = assert.WithSmuggleHooks(
func (got int) bool { return got != 0 }, // each int is changed to a bool
strconv.Atoi, // each string is converted to an int
)
assert.Cmp("123", 123) // succeeds
Smuggle hooks are run just before Cmp hooks and are not run again for their returned
value 25
26. Table driven tests — the heaven of go-testdeep operators
�
�
var personTests = []struct {
name string
expectedErr td.TestDeep
expectedPerson td.TestDeep
}{
{"Bob", nil, td.JSON(`{"name":"Bob","age":41,"id":NotZero(),"children":Len(2)}`)},
{"Marcel", td.String("User not found"), td.Nil()},
{"Alice", nil, td.SStruct(&Person{Name: "Alice", Age: 20}, td.StructFields{"ID": td.NotZero()})},
{"Brian", nil, td.SStruct(&Person{Name: "Brian", Age: 18}, td.StructFields{"ID": td.NotZero()})},
}
=== RUN TestGetPerson
func TestGetPerson(t *testing.T) { === RUN TestGetPerson/Bob
assert := td.Assert(t) === RUN TestGetPerson/Marcel
for _, pt := range personTests { === RUN TestGetPerson/Alice
assert.Run(pt.name, func(assert *td.T) { === RUN TestGetPerson/Brian
person, err := GetPerson(pt.name) --- PASS: TestGetPerson (0.00s)
assert.Cmp(err, pt.expectedErr) --- PASS: TestGetPerson/Bob (0.00s)
assert.Cmp(person, pt.expectedPerson) --- PASS: TestGetPerson/Marcel (0.00s)
}) --- PASS: TestGetPerson/Alice (0.00s)
} --- PASS: TestGetPerson/Brian (0.00s)
} PASS
26
27. Operators types
There is two kinds of operators: classic ones and smuggler ones
A smuggler operator is an operator able to transform the value (by changing its value or
even its type) before comparing it
Smuggler operators follows:
Cap Contains JSONPointer Lax PPtr Smuggle Values
Catch ContainsKey Keys Len Ptr Tag
Some examples �
�
td.Cmp(t, slice, td.Len(td.Between(3, 4)))
td.Cmp(t, headers, td.ContainsKey(td.HasPrefix("X-Ovh")))
td.Cmp(t, &age, td.Ptr(td.Gt(18)))
td.Cmp(t, ageStr, td.Smuggle(strconv.Atoi, td.Catch(&age, td.Gt(18))))
td.Cmp(t, body1, td.Smuggle(json.RawMessage{}, td.JSON(`{"name": $br}`, td.Tag("br", "Brian"))))
td.Cmp(t, body2, td.Smuggle("Service.Owner.Children[0].Name", "Alice"))
td.Cmp(t, body2, td.JSONPointer("/service/owner/children/0/name", "Alice"))
td.Cmp(t, headers, td.Keys(td.SuperSetOf("X-Ovh", "X-Remote-IP")))
td.Cmp(t, err, td.Contains("integrity constraint"))
td.Cmp(t, bytes, td.Lax("pipo bingo!"))
27
28. Custom operators — for beginners
Two operators Code and Smuggle allow to achieve what others cannot for your very
special use cases
Below, only the year of time.Time is important
With Code, you do the test �
�
td.Cmp(t, gotTime,
td.Code(func(date time.Time) bool {
return date.Year() == 2018
}))
With Smuggle, you transform the value and delegate the test �
�
td.Cmp(t, gotTime,
td.Smuggle(func(date time.Time) int { return date.Year() },
td.Between(2010, 2020)),
)
Discover more features in each operator description 28
29. Custom operators — master class 1/2
Sometimes you need to test something over and over, let's do your own operator!
func CheckDateGte(t time.Time, catch *time.Time) td.TestDeep {
op := td.Gte(t.Truncate(time.Millisecond))
if catch != nil {
op = td.Catch(catch, op)
}
return td.All(
td.HasSuffix("Z"),
td.Smuggle(func(s string) (time.Time, error) {
t, err := time.Parse(time.RFC3339Nano, s)
if err == nil && t.IsZero() {
err = errors.New("zero time")
}
return t, err
}, op))
}
Ensures that a RFC3339-stringified date has "Z" suffix and is well RFC3339-formatted. Then
check it is greater or equal than t truncated to milliseconds
Additionally, if catch is non-nil, stores the resulting time.Time in *catch 29
30. Custom operators — master class 2/2
This new operator is useful when used with JSON operator �
�
func TestCreateArticle(t *testing.T) {
type Article struct {
ID int64 `json:"id"`
Code string `json:"code"`
CreatedAt time.Time `json:"created_at"`
}
var createdAt time.Time
beforeCreation := time.Now()
td.Cmp(t, CreateArticle("Car"),
td.JSON(`{"id": NotZero(), "code": "Car", "created_at": $1}`,
CheckDateGte(beforeCreation, &createdAt)))
// If the test succeeds, then "created_at" value is well a RFC3339
// datetime in UTC timezone and its value is directly exploitable as
// time.Time thanks to createdAt variable
t.Logf("Article created at %s", createdAt)
}
30
31. The tdhttp helper or how to easily test a http.Handler
And now you want to test your API, aka a http.Handler
Thanks to the tdhttp helper and all these *#@!# operators, nothing is easier! �
�
import (
"testing"
"github.com/maxatome/go-testdeep/helpers/tdhttp"
"github.com/maxatome/go-testdeep/td"
)
func TestMyApi(t *testing.T) {
ta := tdhttp.NewTestAPI(t, myAPI)
var id int64
ta.Name("Retrieve a person").
Get("/person/Bob", "Accept", "application/json").
CmpStatus(http.StatusOK).
CmpHeader(td.ContainsKey("X-Custom-Header")).
CmpJSONBody(td.JSON(`{"id": $1, "name": "Bob", "age": 26}`, td.Catch(&id, td.NotZero())))
t.Logf("Did the test succeeded? %t, ID of Bob is %d", !ta.Failed(), id)
}
31
32. tdhttp for any framework
myAPI is here a http.Handler ↴
ta := tdhttp.NewTestAPI(t, myAPI)
That's pretty cool as:
• gin-gonic *gin.Engine
• net/http *http.ServeMux
• go-swagger restapi.configureAPI() or restapi.HandlerAPI() return value
• Beego, echo, gorilla/mux, HttpRouter, pat
• any other?
implement all http.Handler! Check the HTTP frameworks section of the FAQ
You can now change your web framework and keep your test framework :) 32
33. tdhttp for any content
Ready to use GET, POST, PATCH, PUT, DELETE, HEAD requests, but can be fed by any
already created http.Request
Supports out of the box application/x-www-form-urlencoded, application/json,
application/xml and multipart/form-data encoding & cookies
Supports string and []byte bodies so you can handle the encoding by yourself
Operator anchoring works out of the box too �
�
func TestMyApiAnchor(t *testing.T) {
ta := tdhttp.NewTestAPI(t, myAPI)
var id int64
ta.Get("/person/Bob", "Accept", "application/json").
CmpStatus(http.StatusOK).
CmpJSONBody(Person{
ID: ta.A(td.Catch(&id, td.NotZero())).(int64),
Name: "Bob",
Age: ta.A(td.Between(25, 30)).(int),
})
}
33
34. tdhttp with easy debug
Thanks to AutoDumpResponse, Or & OrDumpResponse methods, you can inpect the
HTTP response to see what happened in case of failure �
�
func TestMyApiDumpIfFailure(t *testing.T) {
ta := tdhttp.NewTestAPI(t, myAPI)
var id int64
ta.Name("Person creation").
PostJSON("/person", PersonNew{Name: "Bob"}).
CmpStatus(http.StatusCreated).
CmpJSONBody(td.JSON(`
{
"id": $1,
"name": "Bob",
"created_at": $2
}`,
td.Catch(&id, td.NotZero()), // catch just created ID
td.Gte(ta.SentAt()), // check that created_at is ≥ request sent date
)).
OrDumpResponse() // if some test fails, the response is dumped
}
34
35. The tdsuite helper — Simple example — 1/3
Or tests suites with one hand tied behind your back �
�
import (
"testing"
"github.com/maxatome/go-testdeep/helpers/tdsuite"
"github.com/maxatome/go-testdeep/td"
)
func TestPerson(t *testing.T) {
tdsuite.Run(t, &PersonSuite{ // entrypoint of the suite
db: InitDB(), // a DB handler probably used in each tests
})
}
type PersonSuite struct{ db MyDBHandler }
func (ps *PersonSuite) TestGet(assert *td.T) {
// …
}
func (ps *PersonSuite) TestPost(assert, require *td.T) {
// …
}
35
36. tdsuite — All hooks — 2/3
Each method Test* of the suite is run in a sub-test
assert or assert+require, you choose
Several hooks can be implemented:
Setup(t *td.T) error
Destroy(t *td.T) error
PreTest(t *td.T, testName string) error
PostTest(t *td.T, testName string) error
BetweenTests(t *td.T, previousTestName, nextTestName string) error
Setup and Destroy are respectively called before any test is run and after all tests ran
PreTest and PostTest are respectively called before and after each test
BetweenTests is called between 2 consecutive tests (after the PostTest call of previous test
but before the PreTest call of next test)
If a hook returns a non-nil error, the suite fails immediately 36
37. tdsuite — Composing suites — 3/3
func TestAnother(t *testing.T) { // �
� https://goplay.tools/snippet/5cbM9eHbx33
tdsuite.Run(t, &AnotherSuite{}) // entrypoint of the suite
}
// BaseSuite is the base test suite used by all tests suite using the DB.
type BaseSuite struct{ db MyDBHandler }
func (bs *BaseSuite) Setup(t *td.T) (err error) {
bs.db, err = InitDB()
return
}
func (bs *BaseSuite) Destroy(t *td.T) error {
return bs.db.Exec(`TRUNCATE x, y, z CASCADE`)
}
// AnotherSuite is the final test suite blah blah blah…
type AnotherSuite struct{ BaseSuite }
func (as *AnotherSuite) TestGet(assert, require *td.T) {
res, err := as.db.Query(`SELECT 42`)
require.CmpNoError(err)
assert.Cmp(res, 42)
}
37
38. End
Some stats:
• +37k lines of go code
• 99.855% code coverage
• go report A+
• 24 releases since 2018
Links:
• Home page
• godoc
• godoc API tester — tdhttp
• godoc testing suite — tdsuite
• godoc helpers utils — tdutil
• Github ← don't forget to � :) 38