Bestand wählen
Merken

Foreign API Simulation with Sinatra

Zitierlink des Filmsegments
Embed Code

Automatisierte Medienanalyse

Beta
Erkannte Entitäten
Sprachtranskript
and this is where the the the the the the the the the end of the the or a 1 on my name is constant
Internet and on the left to warn you this is not going to be funny talk I'm German we don't do that so I but I don't actually don't in a journey anymore and last year moved to Ottawa Canada and as so many Ruby developers spin on other LA
actually work for and in fact we have so many you Ruby developers so that we just don't know where to put them and we sent them all down to Kansas to speak Everett's can't and so can't already give a talk on this too was speaking later in the afternoon about how we test and and about rockets on to continue with the
shameless self-promotion you can find me on Twitter and get up my handle 60 and in my spare time I am maintaining a couple of libraries that you might find interesting on 1 of them is section widgets which is the UI Component micro framework that say for Ruby on Rails in fact about the slides you just see here screen are powered by action widgets on and maintaining smart properties which is supercharged on Ruby attribute assesses as well as the processing pipeline for Ruby on Rails to model complex business processes and finally the 1 I wanna talk today about request intercept the which of my most recent 1 and it allows you to simulate for an API space and
outright so at its core this talk is
all about testing and so specifically of 1 type of test tests that involve HTTP connections so most of you might know the libraries of the CR in that mark on which we usually used to stab out individual requests or in case of PCR replay requests that have previously been sent to remote API um I would presented different approach today and talk about how we can use Sinatra to simulate a for an API within our test suite and that is essentially the core idea behind on request intercept yeah so on this on this show you how to use the library 1st and then on throughout the talk we dive deeper and deeper into how it actually works internally on to the point where cultural with kind of metaprogramming techniques they to continue on the net HTTP library and to make all that magic happen so yeah I just mentioned it request intercepted dust modifying at http on just like wept mock and we see our there's no clean way to sort of interject yourself into what makes an at http does so some trickery is required to make that work what's on my get back to that later the the idea is that you can use any rub compatible apps and use it as a request interceptor that sort of intercepts an HTTP requests send out by our your application and rerouted to your cap which will then handle the request in line ends In fact all you need
to know essentially is that request interceptor implements the run method which takes on and wreck application as well as the hostname pattern so the husband pattern is important to know when a request intercepted sort of starts intercepting requests it will actually look at the HTTP request and only redirect the request to your own rack up if it matches the hostname otherwise the HDP request will be made of just as a regular remote request and a code example here it defines the probably most minimal rack up by you could potentially implement it's simply lumped a statement and that returns an array with the status code no headers and the message Hello and then I use request intercepted to intercept all requests that beauty anything that ends with any horse that ends with an example that comes from I do my http request and then the search on the quality of the response being hello yeah the problem with
bare-metal rock apps is that they are very inconvenient to sort of implement something more feature complete you wouldn't necessarily want to go with direct directly in city wanna pick something that has a little more on that provides you with a little more convenience and for me this convenience sort of on given by Sinatra which sort of combined simplicity as well as provides you with the way with a lot of flexibility on how to assimilate these API and points and for those of you who don't know Sinatra on it is a Ruby micro wept framework and it's all based around a very simple idea on have Sinatra
application that provides you with some more less well most important methods are GET POST PUT and delete which correspond to the idea HTTP methods and they allow you to define request handlers in Europe set of replication so that they take a path as the 1st argument and then a block and the block defines how requests are being handled the it so simple Sinatra
look something like that you don't even need to rapid in the class or anything on it provides you with some magic to make this work and you require the library you defined that your of your application is handling anything that comes into slash low and in this case it returns have Sinatra so given this conciseness and the simplicity on snapper was an excellent choice to sort of model on API so
and and therefore makes a great combination with a request interceptor In
fact I I went on further because of this great combination it's the combination I would suggest and for you to use instead of using request intercepted that run on with just any recap I would recommend using after and request interceptor gives you define method which allows you to define a new arms and use another application and with this you know with some extract are goodness so you In theory intercept allows you to define the hostname pattern and again just as we've seen before where we can submit the cost in pattern and the application to run method we now define and repair right on the application and then we just define it as a regular so trapped with all of our and points that we need to the In the end the result of and this defined call is a class again which is is another application with the added benefits and 1 of
those benefits is that the this application provides you with an intercept method and the intercept method is just a convenient wrapper for you around run so instead of having to pass in everywhere where you want to use an interceptor remember which hostname you won a match and which application to class and you can just and call intercept on interceptor provided with the block and then again off I often http request and asserted that the court messages returned and then more
importantly in order to past this you probably want to know how many requests you made on which requests actually made and what the risk of request and response data on and was and to make this possible on the intercept method returns the transaction lock so it's simply an array of on request interceptor transactions and these transactions are non
simply structs which give you access to the request and response on that was that was made within on the block and these are instances of rack-mount request and wreck response justice at the library so usually use for testing and wreck applications on I essentially use these to carry all the data for further inspection and any example down below shows you how you can for instance the search on the path of the 1st part transaction log entry and in this case I'm just asserting that my program called on the past hello arm of example outcome you can also nest them
in case you on you want to have you you communicate with multiple API as and are much of a fire was on on the team that implemented you were Russian integration we did that as a separate out so for ice and troubled by was and we also treated shopify as an API just as you would if you develop maps for shop and then we treated over as our other service so on our application was actually had to communicate with both of these services and on is often necessary that you on know exactly on which requests were sent where Mom and those why because interceptors to support nesting so both of these interceptors ride a separate transactional and yes of course the innermost intercepted takes precedence so if you you can actually have 2 interceptors responding to the same the main on support to the same cost and in which case the innermost would win and intercept request it and
important feature is so that you can customize an interceptor for an individual test because the idea is that you generally outlined your service that you work on modeling in a single file and then and customize it to certain behavior that if it's sort of the needs of your test on let's say the 1 model on a response on for 1 particular endpoint you would take your interceptor called the duck customized method on it and then overwrite the previously defined and point and Sinatra smart enough that if you redefine and N . 8 in then the new endpoint will take precedence over the old 1 and in this case what we're just switching the hello endpoint from but to send another message previously was high risk on the analysis on the usual its con
so now that you have a basic understanding on how they work on I wanna talk a little about the advantages and in comparison to the CR and about work that I think exist when using because interceptors but for me 1 of the biggest advantages is that the code isn't flooded throughout your on test instead of what we do is we have 1 that's new 1 file that defines a particular service in our case girl trouble finding that implements all the end points we're usually communicating with and then we customized this interceptor to specific needs in our test suite but if you sort of wanna see in 1 go to what your app is actually communicating with you would just open the file and look at the intercepted information another wanted for me is that interceptors provide greater power and flexibility because on we're talking about on a sonata application you can literally go as far as you want with that on the could have theoretically and in the memory database that sort of keeps state on if you wanna when in simulate entire workflow so you can keep it super simple and returned static responses from the end points so it's really up to you then of course since its essentially just 1 file you can also go further and package it into ruby gem that say on you build a surface that other part that other developers use and you have a public API and now you want to make it easier for people to sort of I integrate your service on you could provide them with predefined intercepted they can use in a test suite so that they don't even think about on hitting your API with like requests from that has with it and finally and that is firstly from the super important important is that the code is just very readable which is in the nature of this and other applications on and I personally think it's more readable than having these back mark on stubs on sort of St gathered around it has tweet is said you have to say how 1 single application that defines how your interceptor works and then there's more this feature is then I am not sure if you can't simulate them with you on that market we see art and so wanna talk a little bit about more advanced concepts on how to use these interceptors on a big
1 for me is simulating network requests the because interceptors or a set up in a way that they propagate arrows or exceptions that are being raised in 1 of them points so specifically disabled on defined sonatas functionality to handle exceptions and propagated through the entire stack on which allows for instance to simulate that a horse is unreachable on simply by raising the appropriate exception which makes it very easy to test your application or at the library of building whether it's robust enough to handle these cases it and then of course Sinatra
gives you a lot on of tools that you can leverage to make intercepted definition even easier and make the code more readable and 1 of the most
important things is probably that of being a standard Ruby class you can just define private helper methods on that you can use throughout the interceptor and throughout the customizations using a test suite In fact you can just apply standard object-oriented design principles to on and all that really gives you to sort of make your interceptors as readable and it's easy to use as possible
it it then there is the possibility of using Sinatra's before and after callbacks that run before or after a particular point is it on and you could for instance utilize and after call back to automatically and code and data into Jason let's say your modelling adjacent API on it's tedious if in any any point you always have to remember that you have the as last step have to you are called to Jason on whatever he's sending over the wire so just define it once in a block and in this case I look at the response and if it's an array or hash I encoded into a Jason and then of course you have the ability to
use a wreck middleware on and in this case of the model below shopify and over the interceptors as API as Jason API eyes and on so we always wanted to decode the incoming Jason so we can easily work with that in our interceptors and and Sinatra provides you with a method called that allows you to inject the rack middleware on that runs before the actual at point set
now that you have sort of an understanding on the part of how you use interceptors and on the way you might provide a nice alternative to BCR about what actually wanna dive in deeper into some of the internals on because I just think it's interesting to see some of the node powerful features Ruby provides and I just as a sort of learning exercise so in the
beginning of the talk I should you that a request intercepted at run a sort of a core of on of the whole idea and in fact this is the concrete method implementation as it exists in the library and on this essentially so 6 steps and I will go over all the 6 steps to sort of showcase how you can mess with our an existing ruby library that doesn't provide and the with the ability to on sort of do this in a clean way and so the 1st step is because you can reuse interceptor is to clear the transaction that's very easy I just clear the array that keeps all the transaction locked entries from the previous round and then I cash the original net HDP methods because we have to make sure that once the block finished its execution we restore net http so as to its default behavior and then i override the net HTTP methods with the custom implementation and just as Web models as well and then I execute my test and now my test on will essentially use on these overridden that HTTP methods and then finally I collect my transactions and and then eventually restore net http to its former glory and of the last point happens in in and ensure part and so it's always guaranteed to run and I said that it doesn't happen that it tests we actually on gets into a state where so when net HDP is not on its original state yeah so
long as I said it's easy to clear the transaction log so just 1 skip that and talk about catching the original methods on this 3 methods you need to override if you wanna and do something like in 7 things on http requests to start finishing request that information I sort of take care of the of opening the TCP connection and then request performs the actual heavy lifting and the way caching works main request interceptor you have now a concrete request intercepted instance at you and that is currently handling all your test case and they just signed on these methods to instance variables and would instance method gives me is an unbound method on so I essentially save the original method implementation and just put them for now in an instance variable for and then
I replaced these 3 methods with my own implementation start and finish are pretty boring I just make sure that led HTP things it has a lot of an open TCP connection it is communicating with but in fact I don't need 1 because of how the redirect on to to snap ratification is working on an I show that in a 2nd and then I define a new request method which is a little more interesting on the Interceptor instance itself is currently handling your test case has a request method of its own and all I really do is they take the data that would usually go to net http request and redirect it on to my interceptor and then I'm also passed in the interceptor itself I won't show the code for
rechristened receptor on request i'm because it's on that's a little more complex but I at least 1 explain what is going on and you can always take a look at the source code if you're interested so the 1st thing I do is I try to find an appropriate interceptor meaning and I look at the HTTP requests and then look at the host name of this request and now go through my list of Austin patents and and stored applications and see if 1 matches if I find 1 I now build a mock request and mock request on the initializer of mock request takes and wreck application as its 1st argument the when they have led somewhat request initialized I can call the methods GET POST PUT delete on them to simulate an actual HTTP transactions and and once that happens I get back to a mock response which I now have to transform into a net HTTP response to make that HDP believe that it actually just talk to on to remote servers and then I logged a transaction meaning now I'm taking the mock request and mock response and just writing them in my transaction log so they can be further analyzed in the test the interesting thing is what happens if no interceptor actually matches your hostname because and I wanted to implemented in a number of intrusive way I didn't want it to block just any on HEP communication and especially to beef still compatible with about market on so what happens is my current net http instance of which is now in this we have stated that it talks to this another application has to be restored on to actually be able and perform on that work requests yeah and on the way I is shown on the next slide but that one's a restored it essentially on perform the request as if they would never have been any interceptors find way yeah
and method on restoring works by utilizing rubies defined method would actually can not just take a block but it can also take an unbound on but so the ones we previously stored in an instance variables we can now read bind to net HDP and we can even read rebind them to concrete instances and often at http then it is sort of happening when the request intercepted doesn't find a matching application is free binds the original methods to the concrete on that http request that's currently going on and then just called request again and performs the request as if nothing ever happened
so that was essentially on the internals of how the request cycle works in request interceptor and on if you compared to web more based on certainly similarities but with the difference that on you define a stop within your test and in this case as the direct to the Sinatra applications on I previously mentioned that this error propagation on that you can utilize to sort of simulated network arrows and I just want to quickly show how this works on this very
simple because Sinatra supports it on by just using particular configuration statements so all you need to do to sort of on campus out ratifications actually raise an exception and not handle it and have the calling code take care of that exception is you disable on the show exceptions and you and will raise arrows and by that you sort of switch Sinatra into an aggressive mode thought which does not make sense if the number of runs in product as your production application but it makes a lot of sense to sort of simulate these network requests arrows
on what I'd like to have a further plans for a request interceptor the on so 1 thing I
want implement is in of the support of traits on sort of similarly named like the factory girl on mechanism where you can and define what you factories building and then give it a certain trade of how it is actually building and I want that for interceptors as well because it was running into the issue that I was simulating the same end points of several times and what I did so far was just having a lot of these a customized request interceptors but what I actually want is just in a particular test case I wanna have a name where can refer to an end point definition and say I want my intercepted to run with a faulty implementation of my hello then the for the implementation could be that be raising a 500 word on raising a network error and I wanna support different adapters
so I don't wanna just stop at MIT http the next thing I want implement would be faraday because faradaic would give me exposure to several other libraries because I don't really want to do the mess around with each of these libraries individual on that but it's sort of that 2 golds I have in mind right now to bring this library forward the and that basically brings me to the end of my talk on and I just want to quickly summarize from what I've been talking about on so because interceptors sort of provide a 3rd alternative to BCR and but not on the thing I like most of them is that I have a concise service definition in 1 place instead of scattering this definition across the entire test suite and they provide me with an easy mechanism to customize them if days the requirement in test and finally Sinatra provides me with a lot of simplicity and flexibility and which ultimately leads to very readable code it's just something I greatly enjoyed if you're interested to take a look at the slides again because I know it was a lot of content I was going over and they are available online thanks a lot for your attention Thank who in the world and the way you do you do you know
Softwareentwickler
Simulation
Computeranimation
Softwaretest
Ruby on Rails
Prozess <Physik>
Kategorie <Mathematik>
Gruppenoperation
Komplex <Algebra>
Framework <Informatik>
Raum-Zeit
Computeranimation
Rechenschieber
Informationsmodellierung
Widget
Programmbibliothek
Zusammenhängender Graph
Garbentheorie
Softwareentwickler
Touchscreen
Einfach zusammenhängender Raum
Softwaretest
App <Programm>
Suite <Programmpaket>
Subtraktion
Punkt
Gewicht <Mathematik>
Kartesische Koordinaten
Quick-Sort
Computeranimation
Kugelkappe
Strahlensätze
RPC
Datentyp
Programmbibliothek
Speicherabzug
Gerade
App <Programm>
Punkt
Implementierung
Kartesische Koordinaten
Code
Quick-Sort
Framework <Informatik>
Computeranimation
Endogene Variable
Zufallszahlen
Mustersprache
Endogene Variable
p-Block
E-Mail
Message-Passing
Parametersystem
Informationsmodellierung
Menge
Code
Klasse <Mathematik>
Datenreplikation
Programmbibliothek
Kartesische Koordinaten
p-Block
p-Block
Gerade
Auswahlaxiom
Quick-Sort
Punkt
Schaltnetz
Güte der Anpassung
Klasse <Mathematik>
Konfigurationsraum
Systemaufruf
Kartesische Koordinaten
Physikalische Theorie
Computeranimation
Mustersprache
Message-Passing
Strahlensätze
Rechter Winkel
Mustersprache
Matching <Graphentheorie>
Strahlensätze
Klasse <Mathematik>
Kartesische Koordinaten
p-Block
Computervirus
Wrapper <Programmierung>
Computeranimation
Endogene Variable
Transaktionsverwaltung
Message-Passing
Wrapper <Programmierung>
Endogene Variable
Ordnung <Mathematik>
Transaktionsverwaltung
Message-Passing
Softwaretest
Element <Gruppentheorie>
Kartesische Koordinaten
p-Block
Instantiierung
Computeranimation
Endogene Variable
Integral
Mapping <Computergraphik>
Transaktionsverwaltung
Dienst <Informatik>
Mereologie
Endogene Variable
Programmbibliothek
Optimierung
Transaktionsverwaltung
Instantiierung
Bit
Punkt
Natürliche Zahl
Kartesische Koordinaten
Code
Computeranimation
Message-Passing
Informationsmodellierung
Softwaretest
Flächentheorie
Endogene Variable
Softwareentwickler
Analysis
Leistung <Physik>
Softwaretest
Suite <Programmpaket>
App <Programm>
Fehlermeldung
Datenhaltung
Paarvergleich
Computervirus
Elektronische Publikation
Quick-Sort
Dienst <Informatik>
Twitter <Softwareplattform>
Festspeicher
Mereologie
Information
Message-Passing
Lineares Funktional
Fehlermeldung
Datennetz
Ausnahmebehandlung
Ausnahmebehandlung
Code
Computeranimation
Komponente <Software>
Message-Passing
Datennetz
Programmbibliothek
Zeitrichtung
Simulation
Instantiierung
Softwaretest
Suite <Programmpaket>
Hash-Algorithmus
Punkt
Klasse <Mathematik>
Softwarewerkzeug
Systemaufruf
Code
Computeranimation
Endogene Variable
Task
Objektorientierte Programmiersprache
Endogene Variable
Hash-Algorithmus
Standardabweichung
Instantiierung
Middleware
Middleware
Knotenmenge
Informationsmodellierung
Punkt
Menge
Mereologie
Speicherabzug
Äußere Algebra eines Moduls
Quick-Sort
Computeranimation
Leistung <Physik>
Gewicht <Mathematik>
Punkt
Implementierung
Unrundheit
Computeranimation
Benutzerbeteiligung
Informationsmodellierung
Variable
Programmbibliothek
Speicherabzug
Ordnungsbegriff
Default
Transaktionsverwaltung
Softwaretest
Einfach zusammenhängender Raum
Caching
p-Block
Mechanismus-Design-Theorie
Quick-Sort
Transaktionsverwaltung
Funktion <Mathematik>
Mereologie
Information
Programmbibliothek
Versionsverwaltung
Aggregatzustand
Instantiierung
Softwaretest
Einfach zusammenhängender Raum
Telekommunikation
Parametersystem
Gewicht <Mathematik>
Implementierung
Zahlenbereich
Strömungsrichtung
Mailing-Liste
Kartesische Koordinaten
Quellcode
Instantiierung
Arithmetisches Mittel
Transaktionsverwaltung
Task
Gewicht <Mathematik>
Offene Menge
Endogene Variable
Server
Transaktionsverwaltung
Instantiierung
Schnelltaste
Subtraktion
Datennetz
Kartesische Koordinaten
p-Block
Instantiierung
Quick-Sort
Computeranimation
Eins
Variable
Benutzerbeteiligung
Diskrete Simulation
Dreiecksfreier Graph
Zeitrichtung
Fehlerfortpflanzung
Instantiierung
ATM
Fehlermeldung
Befehl <Informatik>
Ausnahmebehandlung
Datennetz
Konfigurationsraum
Automatische Handlungsplanung
Zahlenbereich
Kartesische Koordinaten
Ausnahmebehandlung
Biprodukt
Quick-Sort
Code
Computeranimation
Zeitrichtung
Konfigurationsraum
Softwaretest
Suite <Programmpaket>
Kraftfahrzeugmechatroniker
Subtraktion
Implementierung
Code
Quick-Sort
Computeranimation
Rechenschieber
Dienst <Informatik>
Anpassung <Mathematik>
Ablöseblase
Programmbibliothek
Äußere Algebra eines Moduls
Faktor <Algebra>
Wort <Informatik>
Inhalt <Mathematik>
Ganze Funktion
Fehlermeldung

Metadaten

Formale Metadaten

Titel Foreign API Simulation with Sinatra
Serientitel RailsConf 2016
Teil 82
Anzahl der Teile 89
Autor Tennhard, Konstantin
Lizenz CC-Namensnennung - Weitergabe unter gleichen Bedingungen 3.0 Unported:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben.
DOI 10.5446/31512
Herausgeber Confreaks, LLC
Erscheinungsjahr 2016
Sprache Englisch

Inhaltliche Metadaten

Fachgebiet Informatik
Abstract Nowadays, we often rely on third party services that we integrate into our product, instead of building every aspect of an application. In many cases, well written API clients exist, but on occasion you run into the issue that there isn't a ready to use client or it simply doesn't fit your needs. How do you write a good API client and more importantly how do you test it without hitting the remote API. So far, the standard approach has been replaying requests with VCR or stubbing them with Webmock. There is a third option: simulating foreign APIs with Sinatra from within your test suite!

Ähnliche Filme

Loading...
Feedback