Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    luvarqpp
    @luvarqpp
    new question. if I have doc like this:
    [[]some-section-custom-anchor]
    == some section
    
    lorem ipsum...
    Andy Wilkinson
    @wilkinsona
    Thanks for the PR. Could you please update it to just add the snapshot plugin repository? The other changes aren't needed or aren't appropriate for 2.0.x.
    luvarqpp
    @luvarqpp
    yes, of course
    Andy Wilkinson
    @wilkinsona
    Thanks
    luvarqpp
    @luvarqpp
    can I make links like this:
    some section <<some-section-custom-anchor,here>> or linked also <<_some_section,here>>.
    if I am not wrong, section title, gets autogenerated anchors prefixed by _ and all spaces replaced by _
    it is autogenerated also in case when there is custom anchor defined?
    PR changed
    Andy Wilkinson
    @wilkinsona
    AFAIK, once you have defined an anchor for a section, Asciidoctor will not auto-generate one any more.
    luvarqpp
    @luvarqpp
    I am trying it now, but it souds reasonable..
    luvarqpp
    @luvarqpp
    sidenote: PR is still showing me something like " Changes requested \n 1 review requesting changes ", but I have resolved them all in single edit of commit... I see them both as resolved.
    yes, defining custom anchor for section title, does cause that autogenerated anchor is not generated.
    luvarqpp
    @luvarqpp
    Is there any "canonical" way, how to document associative endpoint? I.e., POST-ing "text/uri-list" content type and some url in body... Native approach leads me to PayloadHandlingException
    Andy Wilkinson
    @wilkinsona
    REST Docs doesn't have any built-in support for documenting URI bodies, but the standard request body and HTTP request snippets shouldn't care what the request's content type is. What are you trying to use that's throwing the PayloadHandlingException?
    luvarqpp
    @luvarqpp
    I have actually tried to document "asdf" attribute of payload... I see it now :) On the other side, can I add some description to whole body? Perhaps using title attribute... My original code was (webclient):
                    .consumeWith(document("buplication/associateWithBook",
                            requestFields(
                                    fieldWithPath("asdf").description("TODO add")
                            ),
                            responseFields(
                                    PUBLICATION_FIELD_DESCRIPTORS
                            )
                    ))
    luvarqpp
    @luvarqpp

    My current code:

                    .consumeWith(document("testCases/associateWithRelease",
                            requestFields(
                                    attributes(key("title").value("single url to Release"))
                            ),
                            responseFields(
                                    TESTCASE_FIELD_DESCRIPTORS
                            )
                    ))

    is still throwing exception... partial stacktrace:

    org.springframework.restdocs.payload.PayloadHandlingException: Cannot handle text/uri-list content as it could not be parsed as JSON or XML
    
        at org.springframework.restdocs.payload.ContentHandler.forContentWithDescriptors(ContentHandler.java:69)
        at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:157)
        at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:78)
        at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:191)
        at org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.lambda$document$0(WebTestClientRestDocumentation.java:77)
        at org.springframework.test.web.reactive.server.DefaultWebTestClient$DefaultBodySpec.lambda$consumeWith$4(DefaultWebTestClient.java:437)
        at org.springframework.test.web.reactive.server.ExchangeResult.assertWithDiagnostics(ExchangeResult.java:206)
        at org.springframework.test.web.reactive.server.DefaultWebTestClient$DefaultBodySpec.consumeWith(DefaultWebTestClient.java:437)

    I do not expect it. Is it due to use of requestFields(...)? Perhaps it does not make sense to generate any request-parameters.adoc, when I do not have ability to document its content... Do you have any suggestion? My goal is to have some sentence about request parameters (actually about whole request body) included in documentation in exactly same way, as I include snippet for json type request...

    Andy Wilkinson
    @wilkinsona
    requestFields is intended for documenting a structured JSON or XML payload. In the absence of a Content-Type REST Docs will assume that it's JSON. I would use the existing HTTP request or request body snippets.
    luvarqpp
    @luvarqpp
    @wilkinsona seems fair. I will use snippet of whole request and prepend some paragraph of text before it. It will not look (when just scrolling and looking for some pattern) same as documented json attributes (in table), but it seems as acceptable workaround. operation::someEndpoint/someUsecase[snippets='http-request']
    Marcus Mosttler
    @mmosttler_gitlab

    I am trying to run a JUnit 5 test with RestDocs for a webflux app using WebTestClient using @WebFluxTest, @AutoConfigureRestDocs, @ExtendWith(RestDocumentation.class, SpringExtension.class) with WebTestClient autowired.

    If I have 1 @Test with restdocs document calls it works fine, but when I add a 2nd rest docs test to show a different example of calling the service I get failures during the maven test phase.
    For test #1:
    java.lang.IllegalStateException: Context already exists. Did you forget to call afterTest()?
    at org.springframework.restdocs.ManualRestDocumentation.beforeTest(ManualRestDocumentation.java:70)
    at org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener$DocumentationHandler.beforeTestMethod(RestDocsTestExecutionListener.java:66)
    ...

    For test #2:
    java.lang.NullPointerException
    at org.springframework.restdocs.ManualRestDocumentation.beforeOperation(ManualRestDocumentation.java:85)
    at org.springframework.restdocs.webtestclient.WebTestClientRestDocumentationConfigurer.createConfiguration(WebTestClientRestDocumentationConfigurer.java:73)
    ...

    So I guess my question is 2 part. Is it possible to have more than 1 document tests in 1 test class for WebTestClient with WebFlux or does it have to be 1 to 1?
    If you can have multiple, then what do I need to do to get the tests to pass consistently for RestDocs?

    Andy Wilkinson
    @wilkinsona
    @mmosttler_gitlab Can you share a small sample project that reproduces the problem? I'm not totally sure that I've understood what's happening.
    Patrick Cornelißen
    @pcornelissen
    Hi there! I’m trying to convince the team to get rid of serenity and I’d like to combine allure with spring restdocs as replacement. Has someone tried that already? I could not find any blogs about that which made me suspicious that it might not play well together ;-)
    alexeiakatov
    @alexeiakatov

    Hi everyone! I'm currently trying to document the type of the array elements in json response. I use standalone MockMvc configuration and mock target service. The idea is to have a mechanism that alerts, if the endpoint contract has changed. One thing in that is to control changes of types.
    It is not a problem to realize it against named response fields like this:

    {
        person: {
            name: "some_name",
            age: 33,
            married: false,
    
            hobbies: ["movies", "coocking", "dancing"]
        }
    }

    fieldWithPath("['person']").type(JsonFieldtype.OBJECT).description(...)
    fieldWithPath("['person']['name']").type(JsonFieldtype.STRING).description(...)
    fieldWithPath("['person']['age']).type(JsonFieldtype.NUMBER).description(...)
    fieldWithPath("['person']['married']").type(JsonFieldtype.BOOLEAN).description(...)
    fieldWithPath("['person']['hobbies']").type(JsonFieldtype.ARRAY).description(...)

    If someone adds a new field or delete any field in root object or in "person" object, the test will fail and enforce one to update the documentation.
    The same will happen if someone changes the type of field, for ex. age: 33 -> age: "33".
    The same will happen if someone changes the type of elements in "hobbies" to object like

    {
        /* ... */,
        hobbies: [
        {name: "name", communitySite: "site"},
        /*...*/
        ]
    }

    In this case the exception will say that there are some undocumented fields in response json.

    In this case the solution is in documenting like this:
    fieldWithPath("['person']['hobbies'][]['name']").type(JsonFieldtype.STRING).description(...)
    fieldWithPath("['person']['hobbies'][]['communitySite']").type(JsonFieldtype.STRING).description(...)

    The question is how can I control the simple types of array elements in json response?
    For example, if the interaction has changed and it was decided to pass not a hobbie name, but an id of hobbie. So the response will have been changed to:

    {
        /* ... */,
        hobbies: [123, 91, 87]
    }

    In this case we surely need an exception to be thrown to be aware of need to update the text documentation.

    Need some help. Thanks a lot in advance.

    Andy Wilkinson
    @wilkinsona
    I would expect that to result in an exception as there are no longer and objects within the hobbies array with name fields.
    @pcornelissen I hadn’t heard of Serenity before and I haven’t seen anyone talking about switching from it to REST Docs. If you are replacing one with the other, why would them not playing nicely together be a problem?
    Patrick Cornelißen
    @pcornelissen
    @wilkinsona Serenity is a BDD Framework with a very nice html output for the test results, which seems to be compelling to our business people. But the BDD stuff is a nightmare during test development, that is why I want to get rid of it. To have the nice test reporting I’m checking out allure, which looks nice and should be sufficient for the business people, but we also want to have the detailed input/output documentation for the API, which is why I like Spring RestDocs. Because we would loose that when we replace serenity. So the question I tried to ask is, had someone tried to combine allure and spring restdocs to test spring apps
    alexeiakatov
    @alexeiakatov

    I would expect that to result in an exception as there are no longer and objects within the hobbies array with name fields.

    Sure, that would, if the initial state was {name: "name", communitySite: "site"}. But we currently have the array with ids (JsonFieldType.NUMBER) and need to be informed if the type will have been changed. Is there any way to do that?

    Andy Wilkinson
    @wilkinsona
    @alexeiakatov That’s not possible at the moment using REST Docs itself, but support may be added in the future: spring-projects/spring-restdocs#505. For now I would add an assertion that doesn’t use REST Docs that checks the type of the values in the array.
    @pcornelissen Sorry, I missed that you were introducing Allure when replacing Serenity. I’m afraid I don’t know much about it either.
    Patrick Cornelißen
    @pcornelissen
    @wilkinsona OK, thanks. When we decide to go that road I’ll share my experiences ;)
    alexeiakatov
    @alexeiakatov
    @wilkinsona ok, thanks.
    James Howe
    @OrangeDog
    When documenting responseFields, how do you skip deeper paths?
    e.g. I want to document foo, not foo.bar and foo.baz separately.
    jeffbswope
    @jeffbswope
    I landed on the following:
    fieldWithPath("r").type(JsonFieldType.OBJECT).description("The xxxx resource."),
    fieldWithPath("r.*").ignored(),
    James Howe
    @OrangeDog
    ooooh, subsectionWithPath
    jeffbswope
    @jeffbswope
    felt a bit odd for reasons I can't exactly recall now... but the outcome was good or at least hasn't been revisited.
    jeffbswope
    @jeffbswope
    Yes, subsectionWithPath seems to do that in one step which cures the oddness. nice...
    Andy Wilkinson
    @wilkinsona
    :thumbsup: subsectionWithPath was added for exactly this requirement
    Carlos Adolfo Ortiz Q
    @cortizqgithub

    Hi Team

    [source,http,options="nowrap"]
    ----
    HTTP/1.1 200 OK
    X-time-stamp: 2020-07-24T22:49:15.456146500
    X-all-media: All Media
    Content-Type: application/json
    Content-Length: 21
    
    {
      "2020" : true
    }
    ----

    I have this response in one of my RestDocs tests. I need to add the documentation for the fields, I tried something like 'year' but it failed.

    Here is the endpoint definition

    @GetMapping("/check")
        public Mono<Map<Integer, Boolean>> checkYear(@RequestParam Integer leapYear) {
            return Mono.just(leapYear).map(transformLeapYearToMap());
        }

    NOTE: This entry is for one item, another sample follows, showing a list of years.

    [source,options="nowrap"]
    ----
    [ {
      "1600" : true
    }, {
      "1700" : false
    }, {
      "1800" : false
    }, {
      "1900" : false
    }, {
      "2000" : true
    }, {
      "2019" : false
    }, {
      "2020" : true
    } ]
    ----

    Here is the endopoint definition.

    @GetMapping("/check/years")
        public Flux<Map<Integer, Boolean>> checkYears(@RequestParam List<Integer> leapYears) {
            return Flux.fromIterable(leapYears).map(transformLeapYearToMap());
        }

    Thanks!

    Andy Wilkinson
    @wilkinsona
    As the field names are variable, you'll have to use a wildcard (*).
    In the second case, [].* would be the full path I think. In the first case, it'd just be *.
    Knut Schleßelmann
    @kschlesselmann
    It seems that your test depends on the order of your documentation parts. If I use responseFields,links the test does not fail if I document a missing link. If I switch to links,responseFields the test fails. In either case I have to mark the response subsection _links as ignored because even though I explicitly document links restdocs still wants me to document the "JSON" part. Do we misuse the API? It's feeling kinda unintuitive this way.
    4 replies
    Simon Lenz
    @koala7_gitlab

    I'm new to spring-restdocs and am trying to integrate it into my existing project.

    I'm generating my snippets with rest assured in the integration tests. With maven and the failsafe plugin that defaults to the verify phase. Problem is, that asciidoctor runs before that in prepare-package.

    If I configure asciidoctor to run at post-integration-test, it succeeds, but then the finished html page is not in my jar, cause that was already created in the package phase.

    I wonder if there is a best practice I'm ignoring, which would enable me to run the tests, compile the documentation and then package everything in a jar in the correct order.

    2 replies
    Carlos Adolfo Ortiz Q
    @cortizqgithub

    Hi everyone here.

    I would like to know if there is a comparison of pros/cons between Spring RestDocs and Swagger(OpenAPI)????

    Thanks

    4 replies
    Marcel Widmer
    @marzelwidmer

    hello I try the write a base class for Contracts for a API with Webflux. and RestDocs Snippets

    I can't get generate the snippets I try already a lot of combinations. maybe somebody have any idea or this done already ?
    And also It don't load the rest-messages.properties where I deine some HATEOAS title stuff.

    https://docs.spring.io/spring-restdocs/docs/current/reference/html5/#getting-started-sample-applications
    https://docs.spring.io/spring-framework/docs/5.0.x/spring-framework-reference/testing.html#webtestclient

    Base Class:

    @ExtendWith(RestDocumentationExtension::class, SpringExtension::class)
    @SpringBootTest(classes = [QuickStartApplication::class], webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = ["server.port=8080"])
    @AutoConfigureRestDocs(outputDir = "target/generated-snippets")
    abstract class BaseClass {
    
        @Autowired
        lateinit var context: ApplicationContext
        private var webTestClient: WebTestClient? = null
    
        @BeforeEach
        fun setUp(restDocumentation: RestDocumentationContextProvider?) {
            webTestClient = WebTestClient.bindToApplicationContext(context)
                .configureClient()
                .filter(documentationConfiguration(restDocumentation))
                .build()
        }
    }

    To get it green my test I have to comment it out the title definitions. I have already up&running the same stack with WebMVC there it just works fine :(.

    Contracts Groovy

                            "_links": [
                                    "self"         : [
                                            "href" : value(
                                                    consumer("http://${fromRequest().header('Host')}/api/contact-n-support"),
                                                    producer("http://localhost:8080/api/contact-n-support"))
    //                                        "title": value(
    //                                                consumer("Aktuelle Resource"),
    //                                                producer("Aktuelle Resource"))
    target
    ├── classes
    ├── generated-sources
    ├── generated-test-sources
    ├── maven-status
    ├── stubs
    ├── surefire-reports
    └── test-classes

    The outputDirectory are null

    Marcel Widmer
    @marzelwidmer
    image.png
    Andy Wilkinson
    @wilkinsona
    As chance would have it, I was chatting with Marcin this week about Spring Cloud Contract, REST Docs, and WebTestClient. There are some known limitations and this may be one of them. Probably best to raise this in https://gitter.im/spring-cloud/spring-cloud-contract and find out whether or not it's expected to work.
    2 replies
    Charly
    @nekperu15739
    Any advance on that?
    3 replies
    Jeremy Loy
    @JeremyLoy

    Hi all: Is there a way to have multiple document calls for a single response? If not, what is the recommended way of making multiple pieces of documentation/tables for a response with nested objects?

    {
        "weather": {
            "wind": {
                "speed": 15.3,
                "direction": 287.0
            },
            "temperature": {
                "high": 21.2,
                "low": 14.8
            }
        }
    }

    e.g. using the above weather example from the documentation, how would one create docs for both wind and temperature in a single test?

    3 replies
    Jochen Szostek
    @Drane

    Hi all,

    I was wondering what most people consider of being the best practice between these 2 different approaches:

    • design first - write your API spec up front - maybe using tools such as stoplight.io - that you implement the API. To make sure the implementation follows your specification you can use tools such as swagger-request-validator
    • test-driven - you describe and introspect your API in your test using spring-restdocs - you can use the extension restdocs-api-spec to also generate an openAPI specification for your API - so you rather generate the specification from the knowledge you put into your testt

    Partially quoting a post from 2018 here... so maybe we have a more general sense of what might be the better practise.

    I'm using the first approach, and have no experience with the test-driven / spring-restdocs way.
    Atm I use the openapi spec during pre-development to discuss what we are planning to build with the analists. To define models and operations + document them. And we start from there generating code (interfaces and DTO's mostly), from the API specs. (analogous to ws-import in SOAP) And I like the possibility to work this way. So both analists en software architects are on the same page.

    So I wonder: Can I work the same way if I switch to the TDD way, using spring-restdocs?

    1 reply
    Marcel Widmer
    @marzelwidmer

    Hello is it possible now to create RestDocs now from a WebFlux Setup ?
    Here is a sample project https://github.com/marzelwidmer/kboot-template

    The pom.xml I add the follwoing :

    <dependency>
        <groupId>org.springframework.restdocs</groupId>
         <artifactId>spring-restdocs-webtestclient</artifactId>
          <scope>test</scope>
    </dependency>

    my BaseClass Looks like follow

    @ExtendWith(RestDocumentationExtension::class, SpringExtension::class)
    @SpringBootTest(
        classes = [DemoApplicationService::class], webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
        properties = ["spring.main.web-application-type=reactive", "server.port=8080"]
    )
    @AutoConfigureRestDocs(outputDir = "target/generated-snippets")
    @WithMockCustomUser(username = "jane@doe.ch", authorities = ["keepcalm.admin", "keepcalm.user"], firstname = "jane", lastname = "doe")
    abstract class BaseClass {
    
        @Autowired
        private lateinit var applicationContext: ApplicationContext
    
        private lateinit var webTestClient: WebTestClient
    
        @BeforeEach
        fun setUp(restDocumentation: RestDocumentationContextProvider?) {
            runBlocking {
                webTestClient = WebTestClient.bindToApplicationContext(applicationContext)
                    .configureClient()
                    .filter(
                        documentationConfiguration(restDocumentation)
                            .operationPreprocessors()
                            .withRequestDefaults(prettyPrint())
                            .withResponseDefaults(prettyPrint())
                    )
                    .build()
            }
        }
    }
    tree -L 2
    .
    └── target
        ├── classes
        ├── generated-sources
        ├── generated-test-sources
        ├── maven-status
        └── test-classes
    5 replies