Files
shields/services/base-xml.spec.js
Paul Melnikow 54a36e9474 Refactor cache-header handling and config, create NonMemoryCachingBaseService, rewrite [flip] (#2360)
There's a lot going on in this PR, though it's all interdependent, so the only way I can see to break it up into smaller pieces would be serially.

1. I completely refactored the functions for managing cache headers. These have been added to `services/cache-headers.js`, and in some ways set the stage for the rest of this PR.

    - There are ample higher-level test of the functionality via `request-handler`. Refactoring these tests was deferred. Cache headers were previously dealt with in three places:
        - `request-handler.js`, for the dynamic badges. This function now calls `setCacheHeaders`.
        - `base-static.js`, for the static badges. This method now calls the wordy `serverHasBeenUpSinceResourceCached` and `setCacheHeadersForStaticResource`.
        - The bitFlip badge in `server.js`. 👈 This is what set all this in motion. This badge has been refactored to a new-style service based on a new `NoncachingBaseService` which does not use the Shields in-memory cache that the dynamic badges user.
    - I'm open to clearer names for `NoncachingBaseService`, which is kind of terrible. Absent alternatives, I wrote a short essay of clarification in the docstring. 😝 

2. In the process of writing `NoncachingBaseService`, I discovered it takes several lines of code to instantiate and invoke a service. These would be duplicated in three or four places in production code, and in lots and lots of tests. I kept the line that goes from regex to namedParams (for reasons) and moved the rest into a static method called `invoke()`, which instantiates and invokes the service. This _replaced_ the instance method `invokeHandler`.
    - I gently reworked the unit tests to use `invoke` instead of `invokeHandler`– generally for the better.
    - I made a small change to `BaseStatic`. Now it invokes `handle()` async as the dynamic badges do. This way it could use `BaseService.invoke()`.

3. There was logic in `request-handler` for processing environment variables, validating them, and setting defaults. This could have been lifted whole-hog to `services/cache-headers.js`, though I didn't do that. Instead I moved it to `server-config.js`. Ideally `server-config` is the only module that should access `process.env`. This puts the defaults and config validation in one place, decouples the config schema from the entire rest of the application, and significantly simplifies our ability to test different configs, particularly on small units of code. (We were doing this well enough before in `request-handler.spec`, though it required mutating the environment, which was kludgy.) Some of the `request-handler` tests could be rewritten at a higher level, with lower-level data-driven tests directly against `cache-headers`.
2018-12-01 13:57:34 -05:00

161 lines
4.3 KiB
JavaScript

'use strict'
const Joi = require('joi')
const { expect } = require('chai')
const sinon = require('sinon')
const BaseXmlService = require('./base-xml')
const dummySchema = Joi.object({
requiredString: Joi.string().required(),
}).required()
class DummyXmlService extends BaseXmlService {
static get category() {
return 'cat'
}
static get route() {
return {
base: 'foo',
}
}
async handle() {
const { requiredString } = await this._requestXml({
schema: dummySchema,
url: 'http://example.com/foo.xml',
})
return { message: requiredString }
}
}
describe('BaseXmlService', function() {
describe('Making requests', function() {
let sendAndCacheRequest
beforeEach(function() {
sendAndCacheRequest = sinon.stub().returns(
Promise.resolve({
buffer: '<requiredString>some-string</requiredString>',
res: { statusCode: 200 },
})
)
})
it('invokes _sendAndCacheRequest', async function() {
await DummyXmlService.invoke(
{ sendAndCacheRequest },
{ handleInternalErrors: false }
)
expect(sendAndCacheRequest).to.have.been.calledOnceWith(
'http://example.com/foo.xml',
{ headers: { Accept: 'application/xml, text/xml' } }
)
})
it('forwards options to _sendAndCacheRequest', async function() {
class WithCustomOptions extends BaseXmlService {
async handle() {
const { value } = await this._requestXml({
schema: dummySchema,
url: 'http://example.com/foo.xml',
options: { method: 'POST', qs: { queryParam: 123 } },
})
return { message: value }
}
}
await WithCustomOptions.invoke(
{ sendAndCacheRequest },
{ handleInternalErrors: false }
)
expect(sendAndCacheRequest).to.have.been.calledOnceWith(
'http://example.com/foo.xml',
{
headers: { Accept: 'application/xml, text/xml' },
method: 'POST',
qs: { queryParam: 123 },
}
)
})
})
describe('Making badges', function() {
it('handles valid xml responses', async function() {
const sendAndCacheRequest = async () => ({
buffer: '<requiredString>some-string</requiredString>',
res: { statusCode: 200 },
})
expect(
await DummyXmlService.invoke(
{ sendAndCacheRequest },
{ handleInternalErrors: false }
)
).to.deep.equal({
message: 'some-string',
})
})
it('parses XML response with custom parser options', async function() {
const customParserOption = { trimValues: false }
class DummyXmlServiceWithParserOption extends DummyXmlService {
async handle() {
const { requiredString } = await this._requestXml({
schema: dummySchema,
url: 'http://example.com/foo.xml',
parserOptions: customParserOption,
})
return { message: requiredString }
}
}
const sendAndCacheRequest = async () => ({
buffer:
'<requiredString>some-string with trailing whitespace </requiredString>',
res: { statusCode: 200 },
})
expect(
await DummyXmlServiceWithParserOption.invoke(
{ sendAndCacheRequest },
{ handleInternalErrors: false }
)
).to.deep.equal({
message: 'some-string with trailing whitespace ',
})
})
it('handles xml responses which do not match the schema', async function() {
const sendAndCacheRequest = async () => ({
buffer: '<unexpectedAttribute>some-string</unexpectedAttribute>',
res: { statusCode: 200 },
})
expect(
await DummyXmlService.invoke(
{ sendAndCacheRequest },
{ handleInternalErrors: false }
)
).to.deep.equal({
color: 'lightgray',
message: 'invalid response data',
})
})
it('handles unparseable xml responses', async function() {
const sendAndCacheRequest = async () => ({
buffer: 'not xml',
res: { statusCode: 200 },
})
expect(
await DummyXmlService.invoke(
{ sendAndCacheRequest },
{ handleInternalErrors: false }
)
).to.deep.equal({
color: 'lightgray',
message: 'unparseable xml response',
})
})
})
})