Dulce Villarreal
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Testing Smart Contracts with Truffle Dev Advocate [Dulce Villarreal](https://twitter.com/Dulce_vird) Developer invitados: Senior Developer [Carlos Colorado](https://twitter.com/Ccolorado) Senior Developer JS [Hiram Perez](https://twitter.com/Driverinside) 2020/07/08 [developers.rsk.co/webinars/202007-007/slides](/webinars/202007-005/slides/) NOTE: --- Hands-on session. (so get your computers ready!) Funciona mejor como una sesión de práctica. (¡así que ten tu computadora lista!) --- <!-- .slide: data-background="/assets/img/preso/webinars-page-screenshot.png" --> <!-- .element: style="background-color: #ffffffb0;" --> ### [developers.rsk.co/webinars](/webinars/) [65+ past events](/webinars/#calendar-past) NOTE: `Dulce` Para aquellos que se unen por primera vez, nos gustaría resaltar que este es uno de una gran serie de webinadas, que consta de más de 65 y sigue aumentando. Hay mucho material ya listo, entra a [developers.rsk.co](developers.rsk.co) para todos los detalles. --- ## IOV Labs ![RSK Taringa RIF ](/assets/img/logos/rsk-taringa-rif.png) ![](https://i.imgur.com/ZW3pAgC.png) NOTE: `Dulce` - We both work in IOV Labs, the umbrella organization for RSK, Taringa, and RIF. - RSK is the smart contract platform secured by the bitcoin mining hash power, and therefore the most secure one. - Taringa is a social media platform, and - RIF offers a suite of services for the decentralised Internet: name service, payments, communications, storage, and marketplaces... all decentralised. - IOV is building a fully decentralized internet for Financial Inclusion. RSK es la plataforma de 'Smart contract' asegurada por el poder del 'hash mining' de bitcoin y por lo tanto la más segura. --- ## Us - Dulce NOTE: `Dulce` ---- ### Dulce Villarreal - Dev 🥑 IOVlabs: RSK + RIF - México 🇲🇽 - San Francisco 🌁 - Economist & data scientist 🧮 - Foodie & mezcal sommelier 🌮 🍛 🍣 - Roller skater ⛸️ - @Dulce_vird ---- ### Carlos Colorado - Senior Js Dev - +15 años en la industriia - Consultor de Blockchain - Comunidad EthGuadalajara @ethGDL ---- ### Hiram Perez - Senior Js Dev - Profesor Facultad de ingenieria UNAM - Dog Lover - Learning web3 development --- ## Pre-requisites [developers.rsk.co/tutorials/workshop-prereqs](/tutorials/workshop-prereqs/) [POSIX compliant shell](/tutorials/workshop-prereqs/#posix-compliant-shell) / [curl](/tutorials/workshop-prereqs/#curl) / [NodeJs](/tutorials/workshop-prereqs/#nodejs) / [Code editor](/tutorials/workshop-prereqs/#code-editor) / [Truffle](/tutorials/workshop-prereqs/#truffle) / [Java](/tutorials/workshop-prereqs/#java) / [RSKj](/tutorials/workshop-prereqs/#rskj) NOTE: - Please make sure you have all of these things installed and working on your system --- ## Testing JS - **None** of these: - Smart contracts, Solidity, DApps - **Instead**: - Only Javascript --- ## Testing JS: Objectives - What is testing? - Software engineering principles - Why test? - Writing tests in JS using Mocha ## Testing JS: Objetivos - ¿Qué es testing? - Principios de ingeniería de software - ¿Por qué tests? - Escribiendo tests en JS usando Mocha. Tenemos algunos objetivos por aprender el día de hoy. Empezaremos con lo que es testing y por qué necesitamos hacerlos. Subsecuentemente escribiremos tests en Mocha usando Javascript. --- ## Mocha - A test runner for JS - Can execute "spec" files either in browser, or in NodeJs - Executes tests, outputs reports NOTE: `Dulce` - Mocha is a test runner (or test framework) for Javascript that can run either in the browser or in NodeJs - Today, we'll only be using NodeJs - The main task of a test runner is to execute tests and generate a report - But before we get there, we first need to understand some terms: Implementation, specification, and then, we can loop back to the test runner ## Mocha - Es un `test runner` para JS. - Puede ejecutar archivos ´spec´ en el navegador o en NodeJS. - Ejecuta tests y muestra reportes. - Mocha es un `test runner` (o `test framework`) para javascript que se puede ejecutar en el navegador o en NodeJS. - La función principal de un `test runner` es ejecutar tests y generear un reporte. - Pero antes de que llegemos a eso, necesitamos entender algunos términos: Implementación y especificación, y luego podemos regresar al `test runner` --- ### Implementation - Code that you write - Executes when the program is being used - You are *implementing* the *features* of your software - `impl` NOTE: `Dulce` - Implementations form the actual parts of the code that perform the functionality of your program or application ### Implementación - Es el código que tú escribes. - Se ejecuta cuando el programa es usado. - Tú estás *implementando* los *requerimientos* de tu programa. - `impl` Note: - Las implementaciones son de partes de tu código que pueden realizar las funcionalidades de tu programa o aplicación. --- ### Specification - **Also** code that you write - Does **not** execute when the program is being used - Instead it executes the implementation - You are *specifying* the *features* of your software - `spec` NOTE: `Dulce` - Specifications are similar to implementation because they are also code - However they are not executed by the user of your program or application, instead the specifications run the implementations in certain pre-defined ways. ### Especificación - **También** es código que tú escribes. - **No** se ejecuta cuando el programa está siendo usado. - Si no que ejecuta la implementación. - Tú *especificas* las *funcionalidades* de tu software. - `spec` Notas: - Las especificaciones son similares a la implementación porque también son código. - Aunque no son ejecutaras por el usuario de tu programa, las especificaciones ejecutan las implementaciones en ciertas formas predefinidas. --- ### Test runner - A developer **tool** - **runner** `═exec⟹` **specification** `═exec⟹` **implementation** - **runner** `═observes⟹` **behaviour** `═produces⟹` **report** - Mocha NOTE: `Brendan` - a test runner is sometimes also referred to as a test framework - mocha is the test runner which we will be using today - what it does its it executes your specs, which in turn execute your impls, while it watches the execution, recording which specs pass and which ones fail, outputting a report at the end. ### Test runner - **Una herramienta** del desarrolador. - **runner** `═exec⟹` **especificación** `═exec⟹` **implementación** - **runner** `═observa⟹` **ambiente** `═produce⟹` **reporte** - Mocha Nota: - Algunas veces el `test runner` también se conoce como `test framework`. - Mocha es el `test runner` que usaremos hoy. - Lo que hace es ejecutar tus especificaciones las cuales ejecutan tus implementaciones mientras observa la ejecución para saber cuáles especifaciones pasaron y cuáles no y genera un reporte al final. ---- ### More theory - [Unit](https://en.wikipedia.org/wiki/Unit_testing)/ [Integration](https://en.wikipedia.org/wiki/Integration_testing)/ [Acceptance](https://en.wikipedia.org/wiki/Acceptance_testing) - [Black box](https://en.wikipedia.org/wiki/Black-box_testing)/ [White box](https://en.wikipedia.org/wiki/White-box_testing) - [Code coverage](https://en.wikipedia.org/wiki/Code_coverage) NOTE: `Brendan` - there is a lot more to testing than what we have just covered - so that we don't go over time, here we simply have links to a lot of material on wikipedia, which define various testing related terminology which you're encouraged to read after this webinar - for now, we have covered the basics required to do our hands on with pure javascript, and then move on to testing solidity ### Más teoría - [Unit](https://en.wikipedia.org/wiki/Unit_testing)/ [Integration](https://en.wikipedia.org/wiki/Integration_testing)/ [Acceptance](https://en.wikipedia.org/wiki/Acceptance_testing) - [Black box](https://en.wikipedia.org/wiki/Black-box_testing)/ [White box](https://en.wikipedia.org/wiki/White-box_testing) - [Code coverage](https://en.wikipedia.org/wiki/Code_coverage) Nota: - Hay mucho más de `testing` de lo que vamos a cubrir. - Así que simplemente vamos a dejar los enlaces a wikipedia que cubren mucha de la terminología sobre `testing` la cuál te invitamos a leer después de este webinar. - Por ahora, cubriremos lo básico necesario para realizar nuestra práctica con Javascript puro y luego haremos las pruebas con Solidity. --- ## Testing JS: Hands-on [developers.rsk.co/tutorials/workshop-js-testing](https://developers.rsk.co/tutorials/workshop-js-testing/) NOTE: `Brendan` (pre-reqs next slide) --- ### Pre-requisites [developers.rsk.co/tutorials/workshop-prereqs/](/tutorials/workshop-prereqs/) [POSIX compliant shell](/tutorials/workshop-prereqs/#posix-compliant-shell) / [NodeJs](/tutorials/workshop-prereqs/#nodejs) NOTE: - To follow along in this hands-on section of the workshop, you will need to have these things on your system - For those of you who have just joined us, please check out the pre-requisites section that we covered at the beginning of the webinar, this is merely a quick recap Para continuar con esta sección del taller, necesitarás tener estas cosas en tu sistema Para aquellos que se acaban de unir, por favor verifiquen la sección de prerequisitos que cubrimos al inicio del webinar. --- ## Testing JS: Hands-on [developers.rsk.co/tutorials/workshop-js-testing/](/tutorials/workshop-js-testing/) NOTE: `Brendan` + `Dulce` - Alright, now we're going to do a Javascript testing hands-on. - Please follow the link above and it will take you to a workshop from DApps Dev Club created for a session which I ran last year. - Instead of me presenting and doing the demo at the same time, I'm going to ask Dulce to do this, - (swap over screen share) - We won't be doing this entire exercise, when we get to the "version control with git" section, we'll skip right down to about the halfway mark, all the way to the heading "write some code" `Dulce` - (follow the instructions) - (swap screenshare back) - Está bien, ahora vamos a hacer una práctica de testing en Javascript - Por favor sigan el siguiente enlace --- ## Right/wrong impl/spec ![DApps Dev Club - Implementation Specification Correctness Quadrants](/webinars/202007-005/dapps-dev-club-implementation-specification-correctness-quadrants.png) <!-- .element: style="max-width: 50%; max-height: 50%;" --> NOTE: `Brendan` - Now that we have executed `npm run test`, we have completed writing a correct implementation, and a correct specification - That's the best combination to have, but you cannot know that for sure - The remainder of this hands-on exercise will take you through various commbinations of right and wrong impls, and right and wrong specs, which result in false positives, et cetera - However, we won't be doing this in today's session in light of time - you are of course encouraged to do this in your own time! --- ## Testing Solidity | | Impl | Spec | Test Runner | | --- | --- | --- | --- | | Javascript | `*.js` | `*.spec.js` | `mocha` | | Smart contract | `*.sol` | `*.spec.js` | `truffle test` | NOTE: `Brendan` - As promised earlier, we're going to switch gears from testing pure Javascript to testing smart contracts - This means that we're going to switch from using mocha as the test runner to using truffle as the test runner - Why did we spend all that time earlier learning about mocha? I have a gut feel that some of you are thinking this. - Truffle test is based on Mocha - it is just a wrapper around it, which changes about 1%, and the other 99% of it is the same, from a test writer's point of view. --- ### `mocha` vs `truffle test` | `mocha` | `truffle test` | | --- | --- | | `require()` | `artifacts.require()` | | `describe()` | `contract()` ⃰ | | `describe(() => {...})` | `contract((accounts) => {...})` | NOTE: `Brendan` --- ### State machines - Finite State Automata NOTE: `Dulce` - Before we start the hands-on section, let's talk about some computer science, very briefly, so that we have a better understanding of our approach towards testing. - "State machines" is a term that derives from Mathematics about finite state automata - Smart contracts have properties of state machines, let's get into some specifics ---- ### State - Smart contracts are stateful systems. - This means that a smart contract can be said to be in a particular "state", at any point of time. - This "state" is a set of variables, including their current values, stored by the smart contract. NOTE: `Dulce` ---- ### State transitions - A state transition is a function that allows users to change the state of the smart contract. - When the values of one or more variables in the smart contract is updated, that is a state change. - A transaction added to to the ledger is the vehicle for a smart contract state change. --- ## Testing Solidity: Hands-on - State - State transitions - Events - ~~Mocked functions~~ NOTE: `Dulce` - Here are a few common categories of things to do while testing - We will **not** be doing any mocking in this session in light of time constraints. Instead, we'll give ourselves more time to focus on testing state, state transitions, and events --- ### Pre-requisites: [developers.rsk.co/tutorials/workshop-prereqs](/tutorials/workshop-prereqs/) [POSIX compliant shell](/tutorials/workshop-prereqs/#posix-compliant-shell) [NodeJs](/tutorials/workshop-prereqs/#nodejs) [Truffle](/tutorials/workshop-prereqs/#truffle) / [RSKj](/tutorials/workshop-prereqs/#rskj) NOTE: - To follow along in this hands-on section of the workshop, you will need to have these things on your system - For those of you who have just joined us, please check out the prerequisites section that we covered at the beginning of the webinar, this is merely a quick recap - In this hands-on session, we are going to make use of a demo truffle project which has all of the stuff mostly in place, and you just to `git clone` the starting point - You will also need to install truffle via NodeJs - And finally you will need to have the RSK node, called RSKj, installed on your system and running on the Regtest network - If you do not have this on your system already, please check out our previous webinars in which we go through the steps for this in great detail --- ## Testing Solidity: Hands-on [developers.rsk.co/tutorials/workshop-smart-contract-testing-truffle](/tutorials/workshop-smart-contract-testing-truffle/) NOTE: `Dulce` - Please go ahead and open up the link to that article which is essentially the written form of this tutorial - One of the first few steps will be to git clone the repo at the github link above - Now I'm going to swap over the screenshare to Dulce, who will demo this while I narrate, just like we did in the previous hands-on - (swap screen share) `Dulce` - (does demo) - (swap back screen share) --- ## Summary - Testing - Smart contracts as state machines - Testing Javascript: **Impl** and **spec** were both JS - Testing Solidity: **Impl** was Solidity, **spec** was JS - RSK Regtest NOTE: `Dulce` - While this webinar has been primarily intended as a hands-on workshop, we have covered some theory too, to do with softwate engineering principles around testing, and thinkign about smart contracts in terms of state and state transitions. - And in the hands on section we created a Javascript application and tested it with Javascript, and followed that up with creating a smart contract in Solidity and testing that with Javascript. - You will have noticed that we have used the RSK regtest network for our smart contracts, which runs locally, on your computer only. This is intentional: For these kinds of tests where you're doing active development, and needs faster iterations, a localhost-only blockchain is the right choice. - However, note that you always have the option of running tests against your smart contracts deployed on a real peer-to-peer decentralised blockchain network, such as the RSK Testnet, or even the RSK Mainnet - but usually one would reserve this for a later stage in the project where you have considerations such as economic incentive based attacks or networks congestions or gas price hikes. --- ## Fin Thank you! [developers.rsk.co/webinars](/webinars/) [gitter.im/rsksmart/getting-started](https://gitter.im/rsksmart/getting-started/) NOTE: `Dulce` Thanks to everyone for attending! Be sure to check out developers.rsk.co/webinars for more sessions on RSK and RIF! If you have any questions, please reach out to us at developers [at] iovlabs.org or the gitter link here. Thank you! --- <!-- .slide: data-background="/assets/img/preso/preso-rsk-slide-fin.png" -->

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully