Showing posts with label Outside-In TDD. Show all posts
Showing posts with label Outside-In TDD. Show all posts

Tuesday, September 10, 2019

How to solve it? Crafting web apps using finite state machines - Part I

Code: https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps
Presentation: http://www.danbunea.ro/presentations/crafting%20web%20apps.html

PROBLEM


How should you start crafting a web app?


The requirements come, you have some UI mockups and now you need to start developing a web app. What is the first step you need to do?

Let's go back a bit. If this was not a specific web app, but rather generic:

  • What would our strategy be like?
  • What would be our goals?
  • Which steps would we have to do?
  • Which patterns could help us?
  • What tactics could we use?

In the following lines I will try to address exactly this questions. First we'll discuss the theory and then we'll develop a web app.

we'll start with a little bit of theory, then we'll put it in practice:



THEORY 

Strategy


We'll have to think a bit strategically and a little bit tactically. For the strategy, what would be our goals:

Goals

  • Break the complexity down (state machines, separation of concerns)
  • Build robustness into the system (atomicity with rollback)
Ok, but how can this be done?

Well, we'll do it in 4 Steps
  1. Finite state machine diagram (state/transitions starting from the UI)
  2. States (domain modelling for the states)
  3. Transitions (TDD the controller)
  4. Presentation/UI for the states (TDD the view)

Steps don't need to be sequential, in fact it is recommended to do the last two in parallel.

Tactics


We will be using a few Patterns:
  • finite state machines
  • separation of concerns using MVC
  • atomicity = all or nothing
and a few Techniques:
  • TDD - for the non UI
  • TDD - for the UI
  • Design by contract

PRACTICE


TodoMVC web application, because everyone loves to prove their framework with it, but we'll focus on what we said before.




Step 1 Draw the diagram of the UI state machine


So let's start with Step 1 Finite state machine

Our purpose is to create a state diagram with all the states and transitions we think we'll need. This is not an easy step, but it can clarify the entire development process further on. Let's see what can be done

Actions:
  • list
  • filter
  • add
  • check/unckeck
  • edit
  • delete
From the screens it also look like we'll have the following States:
  • list (filtered or not)
  • add
  • edit
and now let's put it in a diagram:




or:



Now using theis diagram we'll move to step 2 and we'll do the code according to it.


Step 2: Domain modelling



We will separate the different concerns using the MVC pattern. All the logic will be in the controller, the data in the model and we'll add the presentation later or someone else could do it in parallel.

Our data will have to be able to represent all the states in the diagram above: list/filter, add and edit

;What is a todo?

{:text "todo", :done? true}


;How do we know the status?
;When do we filter?


{:context {:status "list"
          :filter true}
:todos [{:text "todo 1" :done? true}
        {:text "todo 2" :done? false}]}


;What about edit?
;How do we know which do we edit?
;How do we order the todos?

{:context {:status "edit"
          :filter true
          :selected-id 1},
:todos {
        :1 {:id 1, :text "todo 1", :done? true, :time 1}
        :2 {:id 2, :text "todo 2", :done? false, :time 2}
        }}

;Let's carve it in stone:

(require '[clojure.spec.alpha :as s])

;SPEC
(s/def ::status #{"list" "edit" "add"})
(s/def ::filter #(or (false? %) (true? %)))
(s/def ::filter-with-nil #(or (nil? %) (false? %) (true? %)))
(s/def ::selected-id nat-int?)
(s/def ::context (s/keys :req-un [::status] :opt-un [::filter-id ::selected-id]))


(s/def ::id nat-int?)
(s/def ::text string?)
(s/def ::done? boolean?)
(s/def ::time number?)
(s/def ::todo (s/keys :req-un [::id ::text ::done? ::time]))
(s/def ::todos (s/map-of keyword? ::todo))

(defn edit-mode-has-a-valid-selected-id? [state]
  (if (= "edit" (get-in state [:context :status]))
    (some (into #{} (map :id (vals (:todos state)))) [(get-in state [:context :selected-id])])
    true
    ))

(s/def ::model (s/and
                 (s/keys :req-un [::context] :opt-un [::todos])
                 edit-mode-has-a-valid-selected-id?
                 ))

(comment 
(s/valid? ::model {:context {:status "edit"
          :filter true
          :selected-id 1}
:todos {
        :1 {:id 1, :text "todo 1", :done? true, :time 1}
        :2 {:id 2, :text "todo 2", :done? false, :time 2}
        }}))

Step 3: Solve the data problem


Now we know how we could represent our states as data in the model, let's test drive the different transitions which will al be functions in the controller. Normally I start with a plan, where I will know what I want to test.

The plan of the tests

 [ ] controller-should
 [ ] initialize-in-list-mode
 [ ] check&uncheck
 [ ] delete
 [ ] toggle-filters
 [ ] set a filter
 [ ] remove all filters
 [ ] set-add-mode
 [ ] save-a-new-todo
 [ ] set-list-mode
 [ ] set-one-for-edit
 [ ] save-a-changed-todo

Then we'll write the first one:

(deftest initialize-in-list-mode
         (is (= {:context {:status "list"} :todos   {}}
                (init!))))

which will obviously

Test fails! Good... now we write the code to make it pass:

;THE MODEL
(def model (atom {:context {:status "list"}}))



;THE CONTROLLER
(defn commit! [value atom-to-change]
  (reset! atom-to-change value))

(defn init! []
  (-> @model
    (assoc :todos {})
    (assoc-in [:context :status] "list")
    (commit! model)))



;THE TEST
(deftest initialize-in-list-mode
         (is (= {:context {:status "list"} :todos {}}
                (init!))))


Or:


Any refactorings? No, let's move to the second test and so on until we solve the entire data problem, one test at a time, making sure it fails, then making it pass, then refactoring the code. We end up with this:

The code is merged here:
https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps/merge_requests/1/diffs

The final code:
https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps/blob/master/test/todomvc/controller_should.cljs
https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps/blob/master/src/todomvc/controller.cljs

You'll probably be able to see that the names of the functions in our controller closely follow our transitions from the diagram.



Solve the data problem (TDD the model/controller) Done!

Now let's have another look again to see the correspondence between the transitions and the controller functions:





while the data in the model corresponds to:



Step 4: Build the UI


We will need now to make sure that our states can be represented on the screen.

For instance when we're in list mode, filtered:



How about edit state:



Now that we know how the data corresponds to the UI,
we can move on to doing the actual UI. We'll use react/reagent to break the UI into components:


Then we'll test drive the entire UI starting by planning the tests:

 [ ] views_should
 [ ] ender-the-main-screen
 [ ] render all sections
 [ ] not render main section when no todos
 [ ] render-input-text-component
 [ ] use-keys-on-input-text-component
 [ ] write something and hit enter
 [ ] hitting enter with no text
 [ ] hitting esc
 [ ] render todo input component
 [ ] add-a-new-todo-when-clicking-enter-or-go-to-list-on-escape
 [ ] render-todos-list-component
 [ ] no filter
 [ ] filter active
 [ ] filter completed
 [ ] render-todo-item-component
 [ ] normal mode
 [ ] completed mode
 [ ] editing mode
 [ ] toggle a todo item component
 [ ] render-todos-count-component
 [ ] no item left
 [ ] 1 item left
 [ ] 2 items left
 [ ] render-todos-filters-component
 [ ] render no filter
 [ ] render filter active
 [ ] render filter completed
 [ ] invoke-controller-filter-when-clicking-filters-in-todos-filters-component

It is worth mentioning that TDD-ing the UI can be split into two types of tests:
- render tests and
- interaction tests

For the render tests you send some data to your components, render it then check how it's rendered.
We start with a render test (we'll use enzyme):

(deftest render-the-main-screen
  (testing "render all sections"
    (let [component [views/screen-component data/one-todo-list-mode-no-filter]
          mounted (->> (r/as-element component)
                       (.mount js/enzyme))]
      (is (= 1 (-> mounted (.find ".header") .-length)))
      (is (= 1 (-> mounted (.find ".main") .-length)))
      (is (= 1 (-> mounted (.find ".footer") .-length)))
      (is (= 1 (-> mounted (.find "li.todo") .-length)))
      (is (= "0 items left" (-> mounted (.find "strong") .getDOMNode .-innerText)))
      )))

the test fails, so then we start writing our first component, making it pass, refactoring etc.

For the interaction tests, you render some data, then click a button and make sure the mocked function that should be invoked is actually invoked:

(deftest invoke-controller-filter-when-clicking-filters-in-todos-filters-component
  (let [invocations (atom [])
        component [views/todos-filters-component nil]
        mounted (->> (r/as-element component)
                     (.mount js/enzyme))]
    (with-redefs [controller/filter! #(swap! invocations conj [%])]
                 (testing "unfilter"
                   (reset! invocations [])
                   (-> mounted
                       (.find "#all")
                       (.simulate "click"))
                   (is (= [[nil]] @invocations)))
                ))

The code is merged here:
https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps/merge_requests/2/diffs

The final code:
https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps/blob/master/test/todomvc/views_should.cljs
https://gitlab.com/danbunea/how-to-solve-it-crafting-web-apps/blob/master/src/todomvc/views.cljs




Goals revised


Complexity problem -solved by making a state machine and using separation of concerns.
Robustness problem - TDD is a clear step forward but we can go further:

  • add atomicity into the transitions/operations (all or nothing)
  • design by contract, always making sure the states are valid states
But we'll see that in part II


Friday, September 21, 2018

Outside-In TDD for the functional python server with Flask and SqlAlchemy




In the following video, you will see a graph and how in time we expand the code using the Outside-in TDD 

Requirements


We have an web API where we should be able to write and read articles and their comments.

Acceptance Test

We save an article:

POST /api/1/save/Article
{
"title":"New article",
"content":"The content"
}
and we receive the article + id
{
id: 13, - can be any value
title:"New article",
content:"The content"
}
We then add 2 new comments:
POST /api/1/save/Article
{
id: 13, - can be any value
comments:[
    {"comment":"This was awesome!"},
    {"comment":"I loved it as well!"},
]
}
response:
{
id: 13, - can be any value
title:"New article",
content:"The content"
}
and now reading the articles and the comments:
POST api/1/query/Article
{
    find: [id,title,content,{comments:[id,comment]}],
    where:{id:13}
}
should return
{"13":{

    id: 13, - can be any value
    comments:{
    "113":{"comment":"This was awesome!"},
    "114":{"comment":"I loved it as well!"},
    }
   }
   }

Outside-In TDD approach


Unlike classicist TDD, in Outside-In, you start the code from the outside, designing it along the way. You start with an acceptance test, then with the unit/integration tests and code needed until you make the acceptance test work:




So let's begin:

Step 1: Acceptance test






When we run it:




2. Step 2 moving in, 


From the outside, writing the first test for the service that will handle the url. A little bit of design, while writing the test: we consider, that we will use a function that will get the object from the database if we have an id in the json or will give us a brand new Article object if we have no id in the json.













Now if we properly do the code, the test will pass:








Step 3: moving furher in, database_services and get_database_object


However, we did not implement the get_database_object, which will work with the database. So for that we'll write the tests first:


or:



and






Now let's write the code to make it pass:







We write in fact 2 tests to cover both scenarios:  when editing or when adding a new article.


Step 4: now we move back and extend the api


We design it to read the data from json and transfer it to the database object. For that we'll use a function transfer_from_json





Once it passes, we move further:

Step 5: writing the transfer service













Now we make the test pass:





Step 6: back to extending the api

We now need to save the object with the data from the json into the db



For this, we extend the test:



and make it pass, then we move back to implementing using TDD the save_database_object

Step 7 extending the database_service to also save



Once we write the test, the code and make it pass:



we move back to the api

Step 7 extend the api





Step 8: TDD the extension:



Until we make it pass:




After a few more intermediary steps:

...

We will TDD all the necessary code to make the acceptance test pass:




Wednesday, August 29, 2018

Outside-In TDD the bank kata in Clojure/ClojureScript


Code: https://github.com/DanBunea/katas/tree/master/outside-in%20tdd%20bank%20kata 


In "London school" TDD or Outside-In we start from an acceptance test, then write unit tests. This is better explained as the double loop of TDD:




Some time ago, I found this great step by step explanation of Outside-In TDD, by Sandro Mancuso from Codurance:



However it was all Java and obviously OOP, so I wanted do the same thing but in Clojure, and fully functional: functions and not classes. So here we go:





Restrictions (adapted for functional):

1. Start with a module account that has the following functions:

(defn deposit [account amount] ...)
(defn withdraw [account amount] ...)
(defn print-statement [account] ...)

Threat the methods, as if they cannot return any values!

2. You're not allowed to add any new functions to the module
3. Strings and integeres are to be used for dates and amounts for simplicity
4. Don't worry about spacing in the statement printed at the console


Step 1: The acceptance test (the big loop)





we need to take this test, unit it fails for the right reason: the results of the console-print are not what was expected, so we write two modules:



and account.cljs:



and now the test:



Step 2: The first unit test - account module - the business layer (the small loop)


The very first module we should test is account, so we make account_tests. For account, we could test the deposit function. Considering we might have a module which will actually do the depositing/withdrawals in a database or something, that module will be separate and we'll call it transaction-repository. So we could test the interactions between modules like:



We expect that when we invoke deposit from the account module, the add-deposit from the transaction-repository will be invoked.



we make it pass,



and continue with withdraw and later with print-statement for which we'll do a separate module: statement-printer. The final test will be:



and:



and:




Step 3: the unit tests for the "data layer" (the small loop)

Like for the account, we start with a simple test, where we make a deposit and check if all-transactions will return it. We also need to make sure it's on a certain date. We make the test pass, and we move on to withdraw, ending up with:



and:



and:




Step 4: Unit testing the statement-printer (the small loop)


Now, we'll go straight to the results, even though I used TDD to get to it:

The tests:




The code obtained:



The tests result:



Let's not forget that our console-print function is still mocked, and the implementation is:



and we can now implement it:



Tests still pass.

Step 5: Going back to the acceptance test (the big loop)


We will modify the test, mocking the dates delivered, as well as console-print:




And when we run all the tests:




Conclusion


Starting from the outside, we could test-drive the design and the code.

acceptance-test -> 
      account-tests->account->
      transaction-respository-tests->transaction-repository->
      statement-printer-tests->statement-printer->console