The document is about a mini-course on test-driven development in Rails. It discusses topics like what and how to test, when to write tests, how many assertions per test. It provides context on unit, integration, view and other types of tests. It explains the test-first development cycle of developing, testing, developing more while testing continuously. Code examples are given of a test class and method for a Roman numeral conversion method.
radix_4 fft processor can be determine to creating for four channel and if it is from how moving the data from one stage to another stage and how get correct output equal to input.
the main advantage:creating for multiple channel from group of channel and analysis how moving of data from stage by stage,
increasing for data processing speed,
Software transactional memory. pure functional approachAlexander Granin
Slides for C++ Russia 2018
I'm presenting my `cpp_stm_free` library: composable monadic STM for C++ on Free monads for lock-free concurrent programming.
At first glance, Java byte code can appear to be some low level magic that is both hard to understand and effectively irrelevant to application developers. However, neither is true. With only little practice, Java byte code becomes easy to read and can give true insights into the functioning of a Java program. In this talk, we will cast light on compiled Java code and its interplay with the Java virtual machine. In the process, we will look into the evolution of byte code over the recent major releases with features such as dynamic method invocation which is the basis to Java 8 lambda expressions. Finally, we will learn about tools for the run time generation of Java classes and how these tools are used to build modern frameworks and libraries. Among those tools, I present Byte Buddy, an open source tool of my own efforts and an attempt to considerably simplify run time code generation in Java. (http://bytebuddy.net)
radix_4 fft processor can be determine to creating for four channel and if it is from how moving the data from one stage to another stage and how get correct output equal to input.
the main advantage:creating for multiple channel from group of channel and analysis how moving of data from stage by stage,
increasing for data processing speed,
Software transactional memory. pure functional approachAlexander Granin
Slides for C++ Russia 2018
I'm presenting my `cpp_stm_free` library: composable monadic STM for C++ on Free monads for lock-free concurrent programming.
At first glance, Java byte code can appear to be some low level magic that is both hard to understand and effectively irrelevant to application developers. However, neither is true. With only little practice, Java byte code becomes easy to read and can give true insights into the functioning of a Java program. In this talk, we will cast light on compiled Java code and its interplay with the Java virtual machine. In the process, we will look into the evolution of byte code over the recent major releases with features such as dynamic method invocation which is the basis to Java 8 lambda expressions. Finally, we will learn about tools for the run time generation of Java classes and how these tools are used to build modern frameworks and libraries. Among those tools, I present Byte Buddy, an open source tool of my own efforts and an attempt to considerably simplify run time code generation in Java. (http://bytebuddy.net)
ITT 2014 - Eric Lafortune - ProGuard, Optimizer and Obfuscator in the Android...Istanbul Tech Talks
Eric presents ProGuard - the open-source optimizer and obfuscator that is integrated in the Android SDK. ProGuard reduces the size of applications, improves their performance, and makes them more difficult to reverse-engineer. Eric presents some typical results on what to expect from ProGuard, discuss the latest developments and provide some background that should help mobile developers get the best out of ProGuard.
SoCal Code Camp 2015: An introduction to Java 8Chaitanya Ganoo
Java 8 introduced cool new features such as Lambdas and Streams. We'll take a look at what they are how to use them effectively. We'll also walkthrough an example of a lightweight Java 8 service running in AWS cloud, which can read and index tweets into an ElasticSearch cluster
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrineFrankie Dintino
A few weeks into your tenure as a software engineer at the Ministry of Truth you are assigned your first real feature request: write a context manager that can make “2 + 2” equal 5 at runtime. Your solution should be written only in Python (for maximum portability). Absurd? Perhaps, but you know better than to ask questions. You are no thought-criminal.
In this talk I walk through the steps I took to modify the value of two plus two in CPython at runtime—using only Python and the ctypes module. What began for me as a silly and frivolous side project became an education in how the python data model works behind the scenes and how CPython compiles, optimizes, and executes python code.
The goal of this talk is to provide an introduction to CPython internals while walking through the steps needed to monkeypatch integer addition to make “2 + 2” equal 5. The audience should come away with a better understanding of how python objects and types are represented in memory, how references are counted, and how python scripts are transformed into abstract syntax trees, compiled into code objects, and then executed by the CPython virtual stack machine. And because I’ve limited myself to using ctypes, these topics can be explored without familiarity with C as a prerequisite.
Revised and extended version of the "Virtual Separation of Concerns" talk, prepared for the GI-Dissertationspreis colloquium at Dagstuhl and for the invited talk at Oregon State University in Corvallis.
Антон Бикинеев, Writing good std::future< C++ >Sergey Platonov
В докладе Антон расскажет о грядущих мажорных изменениях языка, которые, не войдя в Стандарт 17-го года и оставшись в Technical Specifications, будут ждать своего мержа в 20-м, а также быть уже реализованными в некоторых компиляторах. Осветятся также минорные, уже одобренные фичи следующего Стандарта, как языковые, так и библиотечные. Антон расскажет об их целях, покажет методы использования, а также осветит некоторые гайдлайны и трики.
The talk is about Kotlin features, which are decompiled to Java code. You’ll understand how all of this ‘magic’ works in depths, which benefits it’ll give to you and what you may loose. Some benchmarks are included as a bonus.
ITT 2014 - Eric Lafortune - ProGuard, Optimizer and Obfuscator in the Android...Istanbul Tech Talks
Eric presents ProGuard - the open-source optimizer and obfuscator that is integrated in the Android SDK. ProGuard reduces the size of applications, improves their performance, and makes them more difficult to reverse-engineer. Eric presents some typical results on what to expect from ProGuard, discuss the latest developments and provide some background that should help mobile developers get the best out of ProGuard.
SoCal Code Camp 2015: An introduction to Java 8Chaitanya Ganoo
Java 8 introduced cool new features such as Lambdas and Streams. We'll take a look at what they are how to use them effectively. We'll also walkthrough an example of a lightweight Java 8 service running in AWS cloud, which can read and index tweets into an ElasticSearch cluster
2 + 2 = 5: Monkey-patching CPython with ctypes to conform to Party doctrineFrankie Dintino
A few weeks into your tenure as a software engineer at the Ministry of Truth you are assigned your first real feature request: write a context manager that can make “2 + 2” equal 5 at runtime. Your solution should be written only in Python (for maximum portability). Absurd? Perhaps, but you know better than to ask questions. You are no thought-criminal.
In this talk I walk through the steps I took to modify the value of two plus two in CPython at runtime—using only Python and the ctypes module. What began for me as a silly and frivolous side project became an education in how the python data model works behind the scenes and how CPython compiles, optimizes, and executes python code.
The goal of this talk is to provide an introduction to CPython internals while walking through the steps needed to monkeypatch integer addition to make “2 + 2” equal 5. The audience should come away with a better understanding of how python objects and types are represented in memory, how references are counted, and how python scripts are transformed into abstract syntax trees, compiled into code objects, and then executed by the CPython virtual stack machine. And because I’ve limited myself to using ctypes, these topics can be explored without familiarity with C as a prerequisite.
Revised and extended version of the "Virtual Separation of Concerns" talk, prepared for the GI-Dissertationspreis colloquium at Dagstuhl and for the invited talk at Oregon State University in Corvallis.
Антон Бикинеев, Writing good std::future< C++ >Sergey Platonov
В докладе Антон расскажет о грядущих мажорных изменениях языка, которые, не войдя в Стандарт 17-го года и оставшись в Technical Specifications, будут ждать своего мержа в 20-м, а также быть уже реализованными в некоторых компиляторах. Осветятся также минорные, уже одобренные фичи следующего Стандарта, как языковые, так и библиотечные. Антон расскажет об их целях, покажет методы использования, а также осветит некоторые гайдлайны и трики.
The talk is about Kotlin features, which are decompiled to Java code. You’ll understand how all of this ‘magic’ works in depths, which benefits it’ll give to you and what you may loose. Some benchmarks are included as a bonus.
OrderTest.javapublic class OrderTest { Get an arra.pdfakkhan101
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println(\"Usage: java OrderTest sizeOfArray\ \"
+ \"\\tor\ \\tjava OrderTest arrayFile\");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println(\"unable to read array from \" + args[0]);
System.exit(1);//14
}
}
System.out.println(\"before:\");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(\"\ after:\");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? \" %d\" : \" %d\ \", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + \" \");
}
outFile.close();
} catch (IOException e) {
System.err.println(\"Could not write to \" + outfile + \"\ \" + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) .
Palestra realizada na Semana de Tecnologia da Unip 2016.
Conhecendo boas práticas e como esta poderosa ferramenta do Java 8 pode auxiliar no desenvolvimento de aplicativos Java.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
Ubiratan Soares - Software Engineer da Stone, fala sobre Kotlin : Advanced Tricks no Kotlin Community Summit 2018.
https://eventos.imasters.com.br/kotlinsummit/
Saiba mais em
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
import java.util.Scanner;public class Factorial { method usi.pdfaptind
import java.util.Scanner;
public class Factorial
{
// method using recursion to find factorial of number
public static int factorial(int input)
{
// factorial of 0 is 1
if (input == 0)
{
return 1;
}
// else recursively call the function
else
{
return input * factorial(input - 1);
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int input;
System.out.println(\"Enter a number: \");
input = scan.nextInt();
// store result in answer
int answer = factorial(input);
System.out.println(\"The factorial of \" + input + \" is \" + answer);
}
}
Solution
import java.util.Scanner;
public class Factorial
{
// method using recursion to find factorial of number
public static int factorial(int input)
{
// factorial of 0 is 1
if (input == 0)
{
return 1;
}
// else recursively call the function
else
{
return input * factorial(input - 1);
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int input;
System.out.println(\"Enter a number: \");
input = scan.nextInt();
// store result in answer
int answer = factorial(input);
System.out.println(\"The factorial of \" + input + \" is \" + answer);
}
}.
Loomio how to Series - Creating a new Group of PeopleSEA Tecnologia
Loomio is an online platform for collaborative decisions. In this tutorial, we discuss how to create a new group o people interested on a common subject.
Gerentes em Crise existencial - Existimos no Universo Ágil?SEA Tecnologia
Nesta apresentação serão abordadas diversos questionamentos comuns que permeiam o universo de gerenciamento de projetos quando se trata da adoção de métodos ágeis, como: receios de perda de poder, desorganização generalizada, quais os riscos da adoção, falta de documentação, falta de planejamento, de definição de escopo, se há necessidade de gerente, que tipo de trabalho o gerente vai fazer, o que é esse tal de management 3.0, o que vai mudar na rotina (ou na vida, ou na empresa), como medir produtividade, se serve pra qualquer tipo e tamanho de projeto, e se um post-it sumir da parede?; dentre outros questionamentos que podem surgir dos participantes.
Contratos de desenvolvimento de software para governo blue pill or red pill?SEA Tecnologia
Apresentaremos brevemente a evolução dos contratos de desenvolvimento de software e uso dos métodos ágeis no governo, passando pelos movimentos da comunidade ágil, sua influência, alguns cases de sucesso e seus aprendizados. Mas, contar histórias e problemas não muda muito as coisas. O maior propósito desse talk é apresentar duas premissas diferentes para gestores públicos e empresas privadas relfetirem sobre contratos de desenvolvimento de software, e em seguida apresentar algumas ideias bastante inovadoras e amadurecê-las junto a audiência.
Não se questiona mais os méritos da filosofia ágil de desenvolvimento de software. Mesmo as mais ortodoxas escolas de gestão e desenvolvimento de projetos têm ratificado em suas doutrinas práticas e princípios promovidos pela agilidade. No vácuo deste movimento, seguem os governos de todo o mundo, restritos em suas estruturas legais, mas dispostos a experimentação de novas formas de prestação de serviço à sociedade. No Brasil, o setor público se vale da criatividade para a adequação desta nova cultura de trabalho às regras singulares do sistema. Vamos apresentar nesta palestra uma visão ampla do uso de técnicas ágeis pelo governo brasileiro, alguns resultados, suas dificuldades e, principalmente, o que de fato está em jogo sob o manto de todo esse discurso.
Os benefícios e desafios da participação pública digitalSEA Tecnologia
Apresentação realizada no seminário de comemoração dos 10 anos da Comissão de Legislação Participativa da Câmara dos Deputados. Vídeo disponível em
http://www2.camara.gov.br/atividade-legislativa/webcamara/arquivos/recentes/videoArquivo?codSessao=00019175
O movimento Lean Startup está quente no Brasil. Nesta apresentação, busco apresentar um resumo introdutório do assunto para orientar startupeiros de carreira e, quiçá, despertar o interesse de novos.
Emerge no cenário internacional uma nova tendência em favor do intercâmbio extremo de informações. Sob a luz do open mind principle, instituições públicas e privadas de todo o mundo engrossam o coro em busca de novos significados de dados existentes. Governos de todo mundo, influenciados pela onda da Web 2.0, fomentam progressivamente a construção de mashups a partir de suas bases. Batizado de Open Data, este movimento chegou ao Brasil e tem ganhado força na esfera pública. Como desenvolvedores de software, toda esta onda nos trás um sem número de oportunidades, econômicas, políticas e sociais. Por um lado, usando de nosso know how técnico, temos a chance de criar soluções que agregem transparência às ações políticas, aproximem a sociedade da gestão pública e viabilizem o exercício de uma verdadeira cidadania digital. Por outro lado, trata-se de um amplo leque de novas oportunidades de negócio que se apresenta. Nesta palestra, falaremos um pouco da filosofia OpenData e OpenGovData, apresentaremos iniciativas da comunidade hacker, discutiremos as propostas do governo e analisaremos algumas técnicas e tecnologias que temperam o caminho da abertura de dados, do scraping à semantic web.
Primeiro Roadshow no Brasil, na capital Brasília, do lançamento oficial do Liferay Enterprise 6. Abertura Bruno Farache, Liferay, e Clédiston, SEA Tecnologia.
Computação ou medicina? Passar num concurso, enviar curriculos ou abrir uma empresa? Web, mobile ou desktop? Desde os tempos de escola somos inundados de questões que somente o curso da vida nos é capaz de responder. Em nossa formação escolar, somos orientados a seguir um único caminho, o caminho da estabilidade, segurança e conforto. Educam-nos a sermos submissos e obedientes e, condutas fora do padrão esperado são rechaçadas e condenadas ao castigo. Protagonizando essa história, estamos nós, sob avaliação incisiva dos olhos críticos da sociedade. Poucos, acertam de primeira em suas escolhas de vida. Outros, no entando, não têm a mesma sorte e atrofiam-se em gaiolas de outro sem gozar do prazer de se viver dia após dia. Nesta apresentação, vamos refletir sobre todos estes fatos, usando exemplos vivos de rotinas de profissionais na mais diferentes situações e analisando por que a paixão pelo trabalho é a principal virtude compartilhada por profissionais e empreendedores de sucesso.
A comunidade técnica brasileira tem um poder de motivação, articulação e organização coletiva invejada por grupos de usuários de todo o mundo. E se usássemos toda esta sinergia para a geração de riqueza e valor através do empreendorismo em software?
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
22. (...)
public void meuTeste() {
int par1 = 1;
int par2 = 1;
int result = Classe.soma(par1,par1);
assertEquals(2, result);
}
(...)
(...)
public int soma(int a, int b) {
// código
}
(...)
23. (...)
public void meuTeste() {
int par1 = 1;
Preparação
int par2 = 1;
int result = Classe.soma(par1,par1);
assertEquals(2, result);
}
(...)
(...)
public int soma(int a, int b) {
// código
}
(...)
24. (...)
public void meuTeste() {
int par1 = 1;
int par2 = 1;
int result = Classe.soma(par1,par2);
assertEquals(2, result);
Exercício
}
(...)
(...)
public int soma(int a, int b) {
// código
}
(...)
25. (...)
public void meuTeste() {
int par1 = 1;
int par2 = 1;
int result = Classe.soma(par1,par1);
}
assertEquals(2, result);
Verificação
(...)
(...)
public int soma(int a, int b) {
// código
}
(...)
104. Test fixture refers to the fixed
state used as a baseline for
running tests in software testing.
The purpose of a test fixture is to
ensure that there is a well known
and fixed environment in which
tests are run so that results are
repeatable. Some people call this
the test context.
http://en.wikipedia.org/wiki/Test_fixture 67
107. Inicialização da base
database.yml
Identificação dos
arquivos de testes
test/**/*.rb
Para cada teste
identificação dos
métodos de testes
70
108. Para cada método de teste
test “should xxx yyy”
1. carrega fixtures
test/fixtures/users.yml
2. executa setup
3. executa o teste
.....FE
4. executa teardown
5. “descarrega” fixtures
rollback ou delete 71
134. kiwitter $ rake test:units
/opt/local/bin/ruby -I"lib:test" "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/
rake_test_loader.rb" "test/unit/helpers/users_helper_test.rb" "test/unit/user_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader
Started
.FF..
Finished in 0.421486 seconds.
1) Failure:
test_should_not_sign_in_when_invalid_password_is_given(UserTest) [/test/unit/
user_test.rb:27]:
<false> is not true.
2) Failure:
test_should_not_sign_in_when_invalid_username_is_given(UserTest) [/test/unit/
user_test.rb:31]:
<false> is not true.
5 tests, 5 assertions, 2 failures, 0 errors
rake aborted!
Command failed with status (1): [/opt/local/bin/ruby -I"lib:test" "/opt/loc...]
(See full trace by running task with --trace) 97
164. kiwitter $ rake test:functionals
/opt/local/bin/ruby -I"lib:test" "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/
rake/rake_test_loader.rb" "test/functional/sessions_controller_test.rb" "test/
functional/users_controller_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/
rake_test_loader
Started
F.......
inconsistência
Finished in 0.610806 seconds.
1) Failure:
test_should_authenticate_user(SessionsControllerTest) [/test/functional/
sessions_controller_test.rb:9]:
Expected response to be a <:success>, but was <302>
8 tests, 11 assertions, 1 failures, 0 errors
rake aborted!
Command failed with status (1): [/opt/local/bin/ruby -I"lib:test" "/opt/loc...]
(See full trace by running task with --trace)
127
166. kiwitter $ rake test:functionals
/opt/local/bin/ruby -I"lib:test" "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/
rake/rake_test_loader.rb" "test/functional/sessions_controller_test.rb" "test/
functional/users_controller_test.rb"
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/
rake_test_loader
Started redirect não implica na
F....... renderização da página de
Finished in 0.99891 seconds. destino
1) Failure:
test_should_authenticate_user(SessionsControllerTest) [/test/functional/
sessions_controller_test.rb:13]:
expecting <"users/home"> but rendering with <"">
8 tests, 13 assertions, 1 failures, 0 errors
rake aborted!
Command failed with status (1): [/opt/local/bin/ruby -I"lib:test" "/opt/loc...]
(See full trace by running task with --trace)
129
169. Labs
Testar/implementar autenticação
de usuário inválido
@user não deve ser criada
usuário deve ser redirecionado para página de login
Testar/implementar
post de mensagem
132
175. {post, get, delete...}_via_redirect
segue todos os redirects
follow_redirect!
segue apenas um redirect
redirect?
verifica se a última req foi redirect
https!
faz com que todas as reqs pareçam HTTPs
host!
altera o servidor da app
138
184. assert_select("form")
verifica a existência da tag <form>
<span>Maré de Agilidade</span>
assert_select("span", "Maré de Agilidade")
assert_select("span", /Agilidade/)
147
204. Mocks Aren't Stubs
The term 'Mock Objects' has become a popular one to
describe special case objects that mimic real objects for
testing. Most language environments now have frameworks
that make it easy to create mock objects. What's often not
realized, however, is that mock objects are but one form of
special case test object, one that enables a different style of
testing. In this article I'll explain how mock objects work,
how they encourage testing based on behavior verification,
and how the community around them uses them to develop
a different style of testing.
http://www.martinfowler.com/articles/mocksArentStubs.html 167
206. Objeto falso que retorna um valor predeterminado
para uma chamada de método
objeto.stubs(:metodo).and_returns("alguma coisa")
“ignore a implementacao real de objeto.metodo e
retorne ‘alguma coisa’”
se objeto.metodo for invocado
retornará "alguma coisa"
se objeto.metodo NÃO for invocado
nada acontecerá
169
211. semelhante ao stub,
com uma diferença
objeto.stubs(:metodo).adn_returns("alguma coisa")
se objeto.metodo for invocado
retornará "alguma coisa"
se objeto.metodo NÃO for invocado
o teste falhará
174
231. 194
“ RSpec is
the original
Behaviour
Driven
Development
framework for
Ruby.
http://rspec.info
232. Test Driven *
corretude qualidade
< 100% = 100%
rebola a ordem não
no mato importa
195
233. testes
passado
descrição de algo pronto
X
especificação
futuro
descrição de algo inexistente
196
234. $ sudo gem install rspec
Password:
**************************************************
Thank you for installing rspec-1.2.8
Please be sure to read History.rdoc and Upgrade.rdoc
for useful information about this release.
**************************************************
Successfully installed rspec-1.2.8
1 gem installed
Installing ri documentation for rspec-1.2.8...
Installing RDoc documentation for rspec-1.2.8...
(...)
197
240. should_not should have_at_most
should be_true
be_instance_of have_exactly
should be_false
should_not helper
should be_nil
be_an_instance_of should include
should
should be_close should_not include
be_[arbitrary_predicate]
should_not be_close inspect_object
should_not be_nil
be_instance_of should match
should_not
be_kind_of should_not match
be_[arbitrary_predicate]
should change should raise_error
be_a
should_not change should_not raise_error
should be_kind_of
should eql should respond_to
should be_a_kind_of
should_not eql should_not respond_to
should_not be_kind_of
should equal should satisfy
should_not
should_not equal should_not satisfy
be_a_kind_of
should exist simple_matcher
be_an
should_not exist should throw_symbol
should be_instance_of
should have should_not
should
should_not have throw_symbol
be_an_instance_of
should have_at_least wrap_expectation
http://rspec.rubyforge.org/rspec/1.2.8/classes/Spec/Matchers.html 203
244. $ sudo gem install rspec-rails
Password:
**************************************************
Thank you for installing rspec-rails-1.2.7.1
If you are upgrading, do this in each of your rails apps
that you want to upgrade:
$ ruby script/generate rspec
Please be sure to read History.rdoc and Upgrade.rdoc
for useful information about this release.
**************************************************
Successfully installed rspec-rails-1.2.7.1
1 gem installed
Installing ri documentation for rspec-rails-1.2.7.1...
Installing RDoc documentation for rspec-rails-1.2.7.1...
(...) 207
266. puts Faker::Lorem.paragraphs(2)
Rerum quos hic et. Autem harum ea asperiores consequatur libero et. Ipsum cumque dicta optio
voluptate. Et quia officia minus iure vitae. Ducimus delectus unde neque odio voluptas
inventore minima.
Fugiat nihil error incidunt nihil quo natus omnis. Quis consequatur aut totam ad. Doloribus
nihil officiis nobis rerum tempora. Nam eos mollitia delectus assumenda veritatis.
Itaque voluptatem repudiandae odit provident error ut. Perspiciatis est facilis sit quis et
qui vel. Hic corrupti recusandae aliquid possimus.
Et error ad ut voluptatem non labore. Accusantium non tempore aut assumenda architecto enim.
Quasi eos et dicta. Tempore quia optio eos pariatur fugiat.
Est neque molestias aliquid et. Dolor cum nemo tempora. Eum ratione esse quam magni officiis
dolor. Earum maxime sit eaque optio laboriosam tempora voluptatibus.
Quo illum ipsa sit. Ea sequi id et sunt nemo quibusdam maxime. Ab voluptate nesciunt maxime
rerum iure explicabo in. Sed quidem dignissimos est officia necessitatibus sed qui. Similique
odit qui id nostrum corporis autem quas enim.
Sunt placeat eum architecto tempora non. Est libero aut repellat mollitia. Quisquam non quia
et id est repellat qui aspernatur.
Animi ut sit quaerat. Dignissimos enim esse autem qui sed aut optio a. Debitis facilis aut
eaque alias exercitationem quia impedit. Maiores vitae id odio est inventore.
Aut accusamus et et vel sint. Quo ducimus dolor nemo quia libero autem. Assumenda est voluptas
debitis in libero.
Illo sit deleniti tenetur nisi. Reiciendis et odit fugiat velit hic. Quo nisi deserunt sit.
229
271. DSL features
scenarios
Rails Test steps
Rails Code 233
272. $ sudo gem install cucumber
Password:
Successfully installed term-ansicolor-1.0.4
Successfully installed polyglot-0.2.6
Successfully installed treetop-1.3.0
Successfully installed diff-lcs-1.1.2
Successfully installed builder-2.1.2
Successfully installed cucumber-0.3.92
6 gems installed
Installing ri documentation for term-ansicolor-1.0.4...
Installing ri documentation for polyglot-0.2.6...
Installing ri documentation for treetop-1.3.0...
(...)
Installing RDoc documentation for diff-lcs-1.1.2...
Installing RDoc documentation for builder-2.1.2...
Installing RDoc documentation for cucumber-0.3.92...
234
273. kiwitter $ script/plugin install git://github.com/brynary/webrat.git
Initialized empty Git repository in .../kiwitter/vendor/plugins/webrat/.git/
remote: Counting objects: 275, done.
remote: Compressing objects: 100% (236/236), done.
remote: Total 275 (delta 36), reused 170 (delta 20)
Receiving objects: 100% (275/275), 5.07 MiB | 154 KiB/s, done.
Resolving deltas: 100% (36/36), done.
From git://github.com/brynary/webrat
* branch HEAD -> FETCH_HEAD
= Webrat - Ruby Acceptance Testing for Web applications
...
== Description
Webrat lets you quickly write expressive and robust acceptance tests for a Ruby
web application.
235
274. kiwitter $ sudo gem install nokogiri
Building native extensions. This could take a while...
Successfully installed nokogiri-1.3.3
1 gem installed
Installing ri documentation for nokogiri-1.3.3...
Installing RDoc documentation for nokogiri-1.3.3...
236
276. Feature: caso de uso/estória em teste
In order objetivo da funcionalidade
Stakeholder
o que o stakeholder deseja
Background
Given pré-condições
And mais pré-condições
| login | email | password |
| alegomes | alegomes@gmail.com | ale123 |
| luciana | lu@brasilia.net | xuxu |
Scenario: cenário/fluxo em teste
Given pré-condições
When ação do usuário
Then resultado da ação do usuário 238
281. kiwitter $ rake features
/opt/local/bin/ruby -I "/opt/local/lib/ruby/gems/1.8/gems/cucumber-0.3.92/lib:lib" "/opt/local/lib/
ruby/gems/1.8/gems/cucumber-0.3.92/bin/cucumber" --format pretty features/
manage_users_and_updates.feature
Feature: Post update messages
In order to make my life widely public
As a User
I want to post short messages describing what I am doing
Scenario: Post new messages # features/manage_users_and_updates.feature:6
Given I am at users home page # features/manage_users_and_updates.feature:7
And I have entered a text message up to 140 chars # features/manage_users_and_updates.feature:8
When I press post # features/manage_users_and_updates.feature:9
Then the message should be registered # features/manage_users_and_updates.feature:10
1 scenario (1 undefined)
4 steps (4 undefined)
0m0.653s
...
243
282. ...
You can implement step definitions for undefined steps with these
snippets:
Given /^I am at users home page$/ do
pending
end
Given /^I have entered a text message up to 140 chars$/ do
pending
end
When /^I press post$/ do
pending
end
Then /^the message should be registered$/ do
pending
end
244
285. ...
You can implement step definitions for undefined steps with
these snippets:
Given /^I am at users home page$/ do
pending
end
Given /^I have entered a text message up to 140 chars$/ do
pending
end
When /^I press post$/ do
pending
end
Then /^the message should be registered$/ do
pending
end
247
286. kiwitter $ rake features
/opt/local/bin/ruby -I "/opt/local/lib/ruby/gems/1.8/gems/cucumber-0.3.92/lib:lib" "/opt/
local/lib/ruby/gems/1.8/gems/cucumber-0.3.92/bin/cucumber" --format pretty features/
manage_users_and_updates.feature
Feature: Post update messages
In order to make my life widely public
As a User
I want to post short messages describing what I am doing
Scenario: Post new messages
Given I am at users home page
TODO (Cucumber::Pending)
features/manage_users_and_updates.feature:7:in `Given I am at users home page'
And I have entered a text message up to 140 chars
When I press post
Then the message should be registered
1 scenario (1 pending)
4 steps (3 skipped, 1 pending)
0m0.134s
248
287. Given I am at users home page
TODO (Cucumber::Pending)
features/manage_users_and_updates.feature:7:in `Given I am at users home page'
Given /^I am at users home page$/ do
visit "users/home"
end
249
288. kiwitter $ rake features
...
Scenario: Post new messages
users_controller.home
Given I am at users home page
And I have entered a text message up to 140 chars
TODO (Cucumber::Pending)
features/manage_users_and_updates.feature:8:in `And I
have entered a text message up to 140 chars'
When I press post
Then the message should be registered
1 scenario (1 pending)
4 steps (2 skipped, 1 pending, 1 passed)
0m0.260s 250
289. And I have entered a text message up to 140 chars
TODO (Cucumber::Pending)
features/manage_users_and_updates.feature:8:in `And I have entered a
text message up to 140 chars'
251
290. kiwitter $ cucumber features/manage_users_and_updates.feature
Feature: Post update messages
In order to make my life widely public
As a User
I want to post short messages describing what I am doing
Scenario: Post new messages
users_controller.home
Given I am at users home page
And I have entered a text message up to 140 chars
When I press post
TODO (Cucumber::Pending)
features/manage_users_and_updates.feature:9:in `When I press post'
Then the message should be registered
1 scenario (1 pending)
4 steps (1 skipped, 1 pending, 2 passed)
0m0.305s
252
291. When I press post
TODO (Cucumber::Pending)
features/manage_users_and_updates.feature:9:in `When I press post'
253
292. kiwitter $ cucumber features/manage_users_and_updates.feature
Feature: Post update messages
In order to make my life widely public
As a User
I want to post short messages describing what I am doing
Scenario: Post new messages
users_controller.home
Given I am at users home page
And I have entered a text message up to 140 chars
When I press post
Then the message should be registered
TODO (Cucumber::Pending)
features/manage_users_and_updates.feature:10:in `Then the
message should be registered'
1 scenario (1 pending)
4 steps (1 pending, 3 passed)
0m0.282s 254
293. Then the message should be registered
TODO (Cucumber::Pending)
features/manage_users_and_updates.feature:10:in `Then the message should be registered'
?
255
299. $ sudo gem install rcov
Password:
Building native extensions. This could take a while...
Successfully installed rcov-0.8.1.2.0
1 gem installed
Installing ri documentation for rcov-0.8.1.2.0...
Installing RDoc documentation for rcov-0.8.1.2.0...
261
Pouco tempo e muito conte&#xFA;do
Turma heterog&#xEA;nea
Cada um segue seu ritmo
Pouca teoria e muita pr&#xE1;tica
Comecemos falando de testes
Se voc&#xEA; falar com qualquer pessoa comum sobre testes, ela associar&#xE1; &#xE0; realiza&#xE7;&#xE3;o de rotinas de verifica&#xE7;&#xE3;o de algo anteriormente constru&#xED;do.
Se voc&#xEA; falar com qualquer pessoa comum sobre testes, ela associar&#xE1; &#xE0; realiza&#xE7;&#xE3;o de rotinas de verifica&#xE7;&#xE3;o de algo anteriormente constru&#xED;do.
O problema, entretanto, &#xE9; grande tempo entre a constru&#xE7;&#xE3;o e a verifica&#xE7;&#xE3;o.
O problema, entretanto, &#xE9; grande tempo entre a constru&#xE7;&#xE3;o e a verifica&#xE7;&#xE3;o.
O problema, entretanto, &#xE9; grande tempo entre a constru&#xE7;&#xE3;o e a verifica&#xE7;&#xE3;o.
A medida que o tempo passa, manuten&#xE7;&#xF5;es ficam mais caras.
E a&#xED;, o cen&#xE1;rio mais comum, e come&#xE7;ar a guerra fria entre os que constroem e os que verificam.
Convergindo na pior afirma&#xE7;&#xE3;o de qualquer membro de equipe: &#x201C;n&#xE3;o &#xE9; problema meu&#x201D;
Como forma de aliviar, dentre outras coisas, essa disputa entre desenvolvedores e testadores, foi proposta uma metodologia de desenvolvimento chamada TDD.
Quando se faz teste, al&#xE9;m do c&#xF3;digo programa em si, deve-se escrever outro c&#xF3;digo que verifique o programa que, quando &#xE9; executado....
Quando se faz teste, al&#xE9;m do c&#xF3;digo programa em si, deve-se escrever outro c&#xF3;digo que verifique o programa que, quando &#xE9; executado....
...pode passar...
Eu tenho um c&#xF3;digo e v&#xE1;rios testes que o suportam.
Eu tenho um c&#xF3;digo e v&#xE1;rios testes que o suportam.
Eu tenho um c&#xF3;digo e v&#xE1;rios testes que o suportam.
Eu tenho um c&#xF3;digo e v&#xE1;rios testes que o suportam.
Eu tenho um c&#xF3;digo e v&#xE1;rios testes que o suportam.
Eu tenho um c&#xF3;digo e v&#xE1;rios testes que o suportam.
Eu tenho um c&#xF3;digo e v&#xE1;rios testes que o suportam.
Eu tenho um c&#xF3;digo e v&#xE1;rios testes que o suportam.
O impacto de qualquer modifica&#xE7;&#xE3;o no c&#xF3;digo....
...&#xE9; imediatamente apontado por seus testes.
Testes automaticos tratam de algo t&#xE3;o importante que mal sabemos traduzir....
Controla o crescimento do custo das mudan&#xE7;as que, tradicionalmente, &#xE9; descontrolado.
Iterativo vs Incremental
Iterativo!??! S&#xF3; na constru&#xE7;&#xE3;o.
Big Design Upfront vs Design Evolutivo
Iterativo vs Incremental
Iterativo!??! S&#xF3; na constru&#xE7;&#xE3;o.
Big Design Upfront vs Design Evolutivo
Big design upf-ront
Mudan&#xE7;as: rastreamento autom&#xE1;tico de impactos de modifica&#xE7;&#xF5;es
Robustez: evitar apps fr&#xE1;geis cujos bugs sempre voltam
Direcionamento: &#x201C;s&#xED;ndrome da folha em branco&#x201D;
Vamos fazer um Twitter.
Quando se cria uma app Rails, v&#xE1;rios testes s&#xE3;o automaticamente gerados...
Para execu&#xE7;&#xE3;o dos teste, utiliza-se instru&#xE7;&#xF5;es rake.
Quando se executa os tese
Toda execu&#xE7;&#xE3;o de testes no Rails utiliza o seu ambiente de testes, sem impactar na base de desenvolvimento ou nos dados de produ&#xE7;&#xE3;o.
Fixtures &#xE9; o mecanismo do Rails para cria&#xE7;&#xE3;o da massa de testes.
Na verdade, Fixtures &#xE9; uma t&#xE9;cnica n&#xE3;o exclusiva do Rails
...discutida at&#xE9; em livros...
Testes unit&#xE1;rios do Rails s&#xE3;o compostos por recursos b&#xE1;sicos de testes do Ruby mais recursos espec&#xED;ficos do Rails
O funcionamento dos testes unit&#xE1;rios seguem a regra geral, com detalhe para o passo 3.
V&#xE1;rias asser&#xE7;&#xF5;es v&#xEA;m do Ruby Test::Unit::TestCase
Do Ruby...
Do Rails...
Teste gerado pelo Rails.
Criemos um teste pra checar o ActiveRecord (apenas para fins did&#xE1;ticos)
Oops, tudo funcionou de cara. Mas claro, o ActiveRecord j&#xE1; est&#xE1; pronto!
Fa&#xE7;amos um novo teste.
TODO:
u.valid?
u.errors.invalid?(:email)
mensagem de erro no assert
associacao
yml
helper
Implementar funcionalidade de Login.
Defini&#xE7;&#xE3;o do m&#xE9;todo &#x2018;signin&#x2019;
O m&#xE9;todo signin retorna &#x2018;null&#x2019;, mas o teste espera &#x2018;true&#x2019;
Teste espera &#x2018;false&#x2019; mas c&#xF3;digo retorna &#x2018;true&#x2019;
Agora sim. Ficou mais claro qual teste est&#xE1; falhando.
N&#xE3;o encontrou no banco qualquer registro com login = &#x201C;alegomes&#x201D; e password = &#x201C;ale123&#x201D;
Dicas:
- Criar scaffold de updates
Resumo dos testes funcionais: teste enviar requisi&#xE7;&#xE3;o HTTP ao controller e verifica se a resposta enviada coincide com a resposta esperada.
Testes unit&#xE1;rios do Rails s&#xE3;o compostos por recursos b&#xE1;sicos de testes do Ruby mais recursos espec&#xED;ficos do Rails
Novidades
Asser&#xE7;&#xF5;es
Teste pode passar, mas pode n&#xE3;o existir rota definidar pra ele.
Uma par&#xE2;metro n&#xE3;o string pode fazer o teste passar, mas n&#xE3;o funcionar&#xE1; para o usu&#xE1;rio, pois o browser sempre manda string.
assert_response {200,300...} ou {:success, :redirect, :missing, :error}
assert_template &#x201C;index&#x201D; (n&#xE3;o checa o conte&#xFA;do!)
assert_redirect n&#xE3;o segue o redirecionamento
Exemplos
N&#xE3;o repita os mesmos testes nos dois lugares.
Pra cada controlador...
...tem-se seu respectivo teste.
Testes funcionais gerados pelo scaffold n&#xE3;o est&#xE3;o passando.
A requisi&#xE7;&#xE3;o post est&#xE1; passando um usu&#xE1;rio sem informar nenhum atributo, contrariando nossa valida&#xE7;&#xE3;o.
Agora sim!
Prossigamos com a funcionaldiade de login.
Gera&#xE7;&#xE3;o de um novo controlador de sess&#xF5;es, respons&#xE1;vel pelo login e logout do usu&#xE1;rio.
Teste funcional criado para o novo controller.
Mais de perto.... Esta &#xE9; a forma mais comum de se testar um controlador:
assert_response
assert_not_nil
assert_template
Teste funcional criado falhando na linha 8:
assert_not_nil assigns(:user)
Controlador invocando Model para autentica&#xE7;&#xE3;o do usu&#xE1;rio e disponibiliza&#xE7;&#xE3;o da inst&#xE2;ncia @user pra camada View.
Falha agora no assert da linha 13:
assert_template "users/home"
Se o usu&#xE1;rio tiver sido autenticado com sucesso, redirecione-o para sua p&#xE1;gina home.
Nosso teste est&#xE1; inconsistente! Em um momento, ele verifica o retorno de sucesso (200) da requisi&#xE7;&#xE3;o. Em outro, ele checa se a requisi&#xE7;&#xE3;o gerou um redirecionamento de p&#xE1;gina (300).
Mudan&#xE7;a no teste de &#x2018;assert_response :success&#x2019; para &#x2018;assert_response :redirect&#x2019;
ATEN&#xC7;&#xC3;O! O redirect n&#xE3;o implica no render do template de destino. Logo, n&#xE3;o podemos usar assert_template com redirect.
Mudan&#xE7;as no teste:
- Substitui&#xE7;&#xE3;o do assert_template por assert_redirect_to
- Elimina&#xE7;&#xE3;o do &#x2018;assert_response :redirect&#x2019;, cuja verifica&#xE7;&#xE3;o j&#xE1; &#xE9; impl&#xED;cita no assert_redirected_to
Fa&#xE7;a um monte de chamadas a v&#xE1;rios controladores e verifique o resultado.