You've already forked The-API-Book
mirror of
https://github.com/twirl/The-API-Book.git
synced 2025-08-10 21:51:42 +02:00
testing environment
This commit is contained in:
@@ -1,13 +1,13 @@
|
||||
### The Documentation
|
||||
|
||||
Regretfully, many API providers pay miserable attention to the documentation quality. Meanwhile, the documentation is the face of the product and the entry point to it. The problem becomes even worse if we acknowledge that it's almost impossible to write the help docs the developers will consider being at least satisfactory.
|
||||
Regretfully, many API providers pay miserable attention to the documentation quality. Meanwhile, the documentation is the face of the product and the entry point to it. The problem becomes even worse if we acknowledge that it's almost impossible to write the help docs the developers will consider at least satisfactory.
|
||||
|
||||
Before we start describing documentation types and formats, we should stress one important statement: developers interact with your help materials totally unlike you expect them to. Remember yourself working on the project: you make quite specific actions.
|
||||
Before we start describing documentation types and formats, we should stress one important statement: developers interact with your help articles totally unlike you expect them to. Remember yourself working on the project: you make quite specific actions.
|
||||
|
||||
1. First, you need to determine whether this service covers your needs in general (as quickly as possible);
|
||||
2. If yes, you look for specific functionality to resolve your specific case.
|
||||
|
||||
In fact, newcomers (e.g. those developers who are not familiar with the API) usually want just one thing: to assemble the code that solves their problem out of existing code samples and never return to this issue again. Sounds not exactly reassuringly, given the amount of work invested into the API and its documentation development, but that's what the reality looks like. Also, that's the root cause of developers' dissatisfaction with the docs: it's literally impossible to have articles covering exactly that problem the developer comes with being detailed exactly to the extent the developer knows the API concepts. In addition, non-newcomers (e.g. those developers who have already learned the system's basics and now looking for solving some advanced problems) do not need these ‘mixed examples’ articles as they look for some deeper understanding.
|
||||
In fact, newcomers (e.g. those developers who are not familiar with the API) usually want just one thing: to assemble the code that solves their problem out of existing code samples and never return to this issue again. Sounds not exactly reassuringly, given the amount of work invested into the API and its documentation development, but that's what the reality looks like. Also, that's the root cause of developers' dissatisfaction with the docs: it's literally impossible to have articles covering exactly that problem the developer comes with being detailed exactly to the extent the developer knows the API concepts. In addition, non-newcomers (e.g. those developers who have already learned the basics concepts and are now trying to solve some advanced problems) do not need these ‘mixed examples’ articles as they look for some deeper understanding.
|
||||
|
||||
#### Introductory notes
|
||||
|
||||
@@ -19,7 +19,7 @@ Also, keep in mind that documentation will be used for searching as well, so eve
|
||||
|
||||
##### Specification / Reference
|
||||
|
||||
Any documentation starts with a formal functional description. This content type is the most inconvenient to use, but you must provide it. A reference is the hygienic minimum of the API documentation. If you don't have a doc that describes all methods, parameters, options, variable types, and their allowed values, then it's not an API but amateur dramatics. Importantly, a reference must contain not only formal definitions but the descriptions of the implicit agreements either, such as the event generation sequence, side-effects of the methods, etc.
|
||||
Any documentation starts with a formal functional description. This content type is the most inconvenient to use, but you must provide it. A reference is the hygienic minimum of the API documentation. If you don't have a doc that describes all methods, parameters, options, variable types, and their allowed values, then it's not an API but amateur dramatics.
|
||||
|
||||
Today, a reference must be also a machine-readable specification, e.g. comply with some standard, for example, OpenAPI.
|
||||
|
||||
@@ -38,7 +38,7 @@ From the above mentioned, it's obvious that code samples are the crucial tool to
|
||||
|
||||
Ideally, examples should be linked to all other kinds of documentation, i.e. the reference should contain code samples relevant to the entity being described.
|
||||
|
||||
**Sandboxes**
|
||||
##### Sandboxes
|
||||
|
||||
Code samples will be much more useful to developers if they are ‘live’, e.g. provided as live pieces of code that might be modified and executed. In the case of library APIs, the online sandbox featuring a selection of code samples will suffice, and existing online services like JSFiddle might be used. With other types of APIs, developing sandboxes might be much more complicated:
|
||||
* if the API provides access to some data, then the sandbox must allow working with a real dataset, either a developer's own one (e.g. bound to their user profile) or some test data;
|
||||
@@ -83,7 +83,7 @@ A significant problem that harms documentation clarity is the API versioning: ar
|
||||
* if a version of the current page exists for newer API versions, there is an explicit link to the actual version;
|
||||
* docs for deprecated API versions are pessimized or even excluded from indexing.
|
||||
|
||||
If you're strictly maintaining backwards compatibility, it is possible to create single documentation for all API versions. To do so, each entity is to be marked with the API version it is supported from. However, there is an apparent problem with this approach: it's not that simple to get docs for a specific (outdated) API version (and, generally speaking, to understand which capabilities this API version provides). (Though the offline documentation we mentioned earlier will help.)
|
||||
If you're strictly maintaining backwards compatibility, it is possible to create the single documentation for all API versions. To do so, each entity is to be marked with the API version it is supported from. However, there is an apparent problem with this approach: it's not that simple to get docs for a specific (outdated) API version (and, generally speaking, to understand which capabilities this API version provides). (Though the offline documentation we mentioned earlier will help.)
|
||||
|
||||
The problem becomes worse if you're supporting not only different API versions but also different environments / platforms / programming languages; for example, if your UI lib supports both iOS and Android. Then both documentation versions are equal, and it's impossible to pessimize one of them.
|
||||
|
||||
|
@@ -1,3 +1,34 @@
|
||||
### Testing Environment
|
||||
### The Testing Environment
|
||||
|
||||
Let us now discuss providing possibility for developers to test a full API cycle automatically. In many subject areas, that's totally not that simple — for example, in our imaginative coffee-machine API. In the real life, a full happy path of an order, beginning from searching for relevant offers and ending with giving order feedback, takes minutes, maybe tens of of minutes. To test some edge cases (let's say, a user asking for a refund because of quality issue) will require making several dozens of steps. The problem becomes even worse if we remember that directly testing money-related scenarios, both explicit and implicit (like sending SMS) might be costly. To ease working with such APIs, a testing environment is needed, in which developers might check-run their code.
|
||||
If the operations executed via the API imply consequences for end users or partners (cost money, in particular) you must provide a test version of the API. In this test API, real-world actions either don't happen at all (for instance, orders are created but nobody serves them) or are simulated by cheaper means (let's say, instead of sending an SMS to a user, an email is sent to the developer's mailbox).
|
||||
|
||||
However, in many cases having a test version is not enough — like in our coffee-machine API example. If an order is created but not served, partners are not able to test the functionality of delivering the order or requesting a refund. To run the full cycle of testing, developers need the capability of pushing the order through statuses, as this would happen in reality.
|
||||
|
||||
A direct solution to this problem is providing a full set of testing API and administrative interfaces. It means that developers will need to run a second application in parallel — the one you're giving to coffee shops so they might get and serve orders (and if there is a delivery functionality, the third app as well: the courier's one) — and make all these actions that coffee shop staff normally does. Obviously, that's not an ideal solution, because of several reasons:
|
||||
* end user application developers will need to additionally learn how coffee shop and courier apps work, which has nothing to do with the task they're solving;
|
||||
* you will need to invent and implement some matching algorithm: an order made through a test application must be assigned to a specific virtual courier; this actually means creating an isolated virtual ‘sandbox’ (meaning — a full set of services) for each specific partner;
|
||||
* executing a full ‘happy path’ of an order will take minutes, maybe tens of minutes, and will require making a multitude of actions in several different interfaces.
|
||||
|
||||
There are two main approaches to tackling these problems.
|
||||
|
||||
##### The testing environment API
|
||||
|
||||
The first option is providing a meta-API to the testing environment itself. Instead of running the coffee-shop app in a separate simulator, developers are provided with helper methods (like `simulateOrderPreparation`) or some visual interface that allows controlling the order execution pipeline with minimum effort.
|
||||
|
||||
Ideally, you should provide helper methods for any actions that are conducted by people in production environment. It makes sense to ship this meta-API complete with ready-to-use scripts or request collections that show the correct API call orders for standard scenarios.
|
||||
|
||||
The disadvantage of this approach is that client developers still need to know how the ‘flip side’ of the system works, though in simplified terms.
|
||||
|
||||
##### The pre-defined scenario simulator
|
||||
|
||||
The alternative to providing the testing environment API is simulating the working scenarios. In this case, the testing environment takes control over ‘underwater’ parts of the system. In our coffee example, that means that, after the order is submitted, the system will simulate all the preparation steps and then the delivery of the beverage to the customer.
|
||||
|
||||
The advantage of this approach is that it demonstrates vividly how the system works according to the API vendor design plans, e.g. in which sequence the events are generated, and which steps the order passes through. It also reduces the chance of making mistakes in testing scripts, as the API vendor guarantees the actions will be executed in the correct order with the right parameters.
|
||||
|
||||
The main disadvantage is the necessity to create a separate scenario for each unhappy path (effectively, for every possible error), and give developers the capability of denoting which scenario they want to run. (For example, like that: if there is a pre-agreed comment to the order, the system will simulate a specific error, and developers will be able to write and debug the code that deals with the error.)
|
||||
|
||||
#### The automation of testing
|
||||
|
||||
Your final goal in implementing testing APIs, regardless of which option you choose, is allowing partners to automate the QA process for their products. The testing environment should be developed with this purpose in mind; for example, if an end user might be brought to a 3-D Secure page to pay for the order, the testing environment API must provide some way of simulating the successful (or not) passing of this step. Also, in both variants, it's possible (and desirable) to allow running the scenarios in a fast-forward manner that will allow making auto-testing much faster than manual testing.
|
||||
|
||||
Of course, not every partner will be able to employ this possibility (which also means that ‘manual’ way of testing usage scenarios must also be supported alongside the programmatical one) simply because not every business might afford to hire a QA automation engineer. Nevertheless, the ability to write such auto-tests is a huge competitive advantage from a technically advanced partner's point of view.
|
1
src/en/drafts/04-Section III. The API Product/13.md
Normal file
1
src/en/drafts/04-Section III. The API Product/13.md
Normal file
@@ -0,0 +1 @@
|
||||
### Managing expectations
|
@@ -37,7 +37,7 @@
|
||||
|
||||
В идеале примеры должны быть провязаны со всеми остальными видами документации. В частности, референс должен содержать примеры, релевантные описанию сущностей.
|
||||
|
||||
**Песочницы**
|
||||
##### Песочницы
|
||||
|
||||
Примеры станут намного полезнее для разработчиков, если будут представлены в виде «живого» кода, который можно модифицировать и запустить на исполнение. В случае библиотечных API это может быть просто онлайн-песочница с заранее заготовленными примерами (в качестве такой песочницы можно использовать и существующие онлайн-сервисы типа JSFiddle); в случае других API разработка песочницы может оказаться сложнее:
|
||||
* если через API предоставляется доступ к данным, то и песочница должна позволять работать с настоящими данными — либо своими собственными (привязанными к профилю разработчика), либо с некоторым тестовым набором данных;
|
||||
|
@@ -1,15 +1,32 @@
|
||||
### Тестовая среда
|
||||
|
||||
Отдельно стоит обсудить предоставление разработчику возможности протестировать полный цикл работы API автоматически. Во многих предметных областях сделать это отнюдь не просто — в частности, и в нашем выдуманном примере с API кофе-машин. В реальной жизни полный happy path заказа, от запроса пользователем информации о доступных предложениях до выставления обратной связи по завершению занимает минуты, иногда десятки минут. Чтобы протестировать какие-то крайние случаи (например, запрос пользователем возврата денежных средств из-за проблем с качеством заказа) требует совершения нескольких десятков последовательных шагов. Ситуация осложняется также тем, что сценарии, связанные с деньгами прямо или косвенно (например, в виде отправки SMS) тестировать «в лоб» накладно. Для облегчения работы с такими API необходима полноценная тестовая среда, с помощью которой разработчики будут обкатывать свой код.
|
||||
Если через ваш API исполняются операции, которые имеют последствия для пользователей или партнёров (в частности, стоят денег), то вам необходимо иметь тестовую версию этого API. В тестовом API реальные действия либо не происходят совсем (например, заказ создаётся, но никем не исполняется), либо симулируется дешёвыми способами (например, вместо отправки SMS на номер пользователя уходит электронное письмо на почту разработчика).
|
||||
|
||||
Однако во многих случаях этого недостаточно — как, например, в нашем выдуманном примере с API кофе-машин. Если заказ просто создаётся, но не исполняется — партнёры не смогут протестировать, как в их приложении работает функциональность выдачи заказа или, скажем, запроса возврата денег. Для проведения полного цикла тестирования необходимо, чтобы этот виртуальный заказ можно было переводить в другие статусы — так, как это будет происходить в реальности.
|
||||
|
||||
Решение этой проблемы «в лоб» — это предоставление полного комплекта тестовых API и административных интерфейсов. Т.е. разработчик должен будет запустить параллельно второе приложение — то, которое вы предоставляете кофейням, чтобы они могли принять и исполнить заказ (а если предусмотрена курьерская доставка, то ещё и третье — приложение курьера) — и выполнять в этом приложении действия, которые в норме выполняет сотрудник кофейни. Очевидно, что это далеко не самый удобный вариант, по многим причинам:
|
||||
* разработчику пользовательского приложения придётся дополнительно разбираться в работе приложений для кофеен и курьеров, которые, вообще говоря, никакого отношения к его задачам не имеют;
|
||||
* необходимо будет придумать и реализовать какие-то алгоритмы связывания: заказ, сделанный через тестовое приложение, должен попадать на исполнение нужному виртуальному курьеру; это фактически означает, что в тестовом API вам нужно будет создавать виртуальную «песочницу» (читай — полный набор сервисов) для каждого партнёра в отдельности;
|
||||
* полный happy path заказа будет занимать минуты, иногда десятки минут, и требовать выполнения множества действий в нескольких интерфейсах.
|
||||
|
||||
#### API среды тестирования
|
||||
Избежать подобного рода проблем вы можете двумя основными способами.
|
||||
|
||||
Исправить ситуацию помогает метапрограммирование: если предоставить API к самой тестовой среде, все эти действия по работе с приложением можно автоматизировать и тем самым существенно ускорить и упростить. Вместо того, чтобы открывать приложение и вручную создавать заказ, разработчик вызывает специальные методы API, которые эмулируют действия пользователя. Это могут быть как реально существующие методы (т.е. по сути внутренний API приложения), так и синтетические функции, разработанные специально для тестирования. Для работы с таким API часто целесообразно предоставлять отдельный SDK или библиотеку готовых вызовов типа коллекции для Postman.
|
||||
##### API среды тестирования
|
||||
|
||||
Следует отметить, что API среды тестирования существенно сокращает количество ручной работы, но не время, затраченное на прогон одного сценария: в идеале работа с таким API должна происходить в таком же масштабе времени, что и работа реального приложения, иначе велик шанс пропустить какие-то ошибки, связанные с плохо настроенными интервалами ожидания ответа на запрос, а также увеличивается вероятность false negative ошибок при тестировании, связанных с тем, что реальный код всё-таки работает не мгновенно, а требует определённого (и не всегда предсказуемого) времени для исполнения.
|
||||
Первый вариант — это предоставление мета-API к самой тестовой среде. Вместо того, чтобы запускать приложение кофейни в отдельном эмуляторе, разработчику предоставляются хелперные методы (типа `simulateOrderPreparation`) или специальный визуальный интерфейс, позволяющие управлять сценарием исполнения заказа с минимальными усилиями.
|
||||
|
||||
В идеале вы должны иметь хелперные методы среды тестирования на все действия, которые в реальном продакшн-окружении выполняются людьми. Имеет смысл поставлять такие мета-API сразу с готовыми скриптами или коллекциями запросов, демонстрирующих правильную последовательность вызовов разных API для симуляции стандартных сценариев.
|
||||
|
||||
Недостаток этого подхода заключается в том, что разработчику клиентского приложения всё ещё необходимо разбираться в том, как работает «изнанка» системы, пусть и в упрощённых терминах.
|
||||
|
||||
#### Предопределённые сценарии
|
||||
|
||||
Альтернативой API среды является эмуляция сценариев работы, когда тестовая среда берёт на себя управление недоступными разработчику действиями. В нашем кофейном примере это будет выглядеть так: после размещения заказа система автоматически эмулирует все шаги его приготовления, а потом и получение заказа конечным пользователем — как правило, в ускоренном масштабе времени. Плюсом такого подхода является наглядная демонстрация, каким образом система работает согласно задумке провайдера API, какие события в какой последовательности генерируются. Основным минусом является необходимость предусмотреть в такой песочнице все возможные unhappy path, т.е. возникающие ошибки, причём также необходимо и предоставить возможность разработчику указать, какой именно из сценариев он хочет воспроизвести. Например, если заказ создан с комментарием определённого вида, будет эмулирована ошибка его исполнения, и разработчик сможет отладить правильную реакцию на такого рода ошибку.
|
||||
Альтернативой API среды тестирования является симуляция сценариев работы, когда тестовая среда берёт на себя управление «подводной» частью системы. В нашем кофейном примере это будет выглядеть так: после размещения заказа система автоматически симулирует все шаги его приготовления, а потом и получение заказа конечным пользователем. Плюсом такого подхода является наглядная демонстрация, каким образом система работает согласно задумке провайдера API, какие события в какой последовательности генерируются. Кроме того, уменьшается возможность ошибки, поскольку провайдером API гарантируется, что действия будут выполнены в правильном порядке и с правильными параметрами.
|
||||
|
||||
Основным минусом является необходимость разработать отдельный сценарий для всех возможных unhappy path, т.е. для каждой возможной ошибки, причём также необходимо и предоставить возможность разработчику указать, какой именно из сценариев он хочет воспроизвести. (Например, следующим образом: если заказ создан с комментарием определённого вида, будет эмулирована ошибка его исполнения, и разработчик сможет отладить правильную реакцию на такого рода ошибку.)
|
||||
|
||||
#### Автоматизация тестирования
|
||||
|
||||
Ваша конечная цель при разработке тестового API, независимо от выбранного варианта — это позволить партнёрам автоматизировать тестирование их продуктов. Разработку тестовой среды нужно вести именно с этим прицелом; например, если для оплаты заказа необходимо перевести пользователя на страницу 3DS, в API тестовой среды должен быть предусмотрена возможность программно симулировать прохождение (или непрохождение) пользователем этого вида проверки. Кроме того, в обоих вариантах возможно (и скорее даже желательно) выполнение сценариев в ускоренном масштабе времени, что позволяет производить автоматическое тестирование гораздо быстрее ручного.
|
||||
|
||||
Конечно, далеко не все пользователи этой возможностью смогут воспользоваться (что помимо прочего означает, что «ручной» способ протестировать пользовательские сценарии тоже должен поддерживаться наряду с программным) просто потому что далеко не все бизнесы могут позволить себе нанять автоматизатора тестирования. Тем не менее, сама возможность такие автотесты писать — огромное конкурентное преимущество вашего API в глазах технически продвинутых партнёров.
|
Reference in New Issue
Block a user