1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-11-01 19:07:38 +01:00
unleash.unleash/src/test/arbitraries.test.ts

188 lines
6.1 KiB
TypeScript
Raw Normal View History

feat: add playground API post endpoint (#1791) * Chore: add unleash-client dependency * Feat: add openapi specs for basic sdk contexts and playground reqs * Feat: add openapi spec for response * Feat: add openAPI entry for playground endpoint * Fix: remove required 'projects' property that doesn't exist * Refactor: add test placeholders for playground api * Chore: improve openAPI description for playground request * Refactor: align example project names * Fix: update openapi snapshot * Fix: summary -> description; example -> examples * Feat: add fast-check and stub out one test. The test doesn't work yet. * Feat: add test and generator for sdk context schema * Feat: add generators and tests for all new schemas * Feat: test that the same input is returned exactly * Feat: add more tests and more schemas * Refactor: clean up tests some * Refactor: simplify url friendliness check * Refactor: fix types for playground request schema generator * Feat: add bad request test * Fix: make parameters the correct shape in generator * Feat: scaffold out tests for service and endpoint Liberal use of @ts-expect-error * Fix: update snapshot with new model * Add missing appName * wip: stub out some extra tests * Feat: model strategies for testing * Feat: model variant payloads better * Refactor: input params for function * Refactor: use email address for user id generation * Chore: update comment * Wip: start stubbing out e2e tests * Refactor: move tests requiring db to e2e file * Fix: make e2e tests run as expected * Fix: make toggle generator test work as expected * Fix: increase timeout for long-running e2e test * Wip: map toggles test * Wip: test movement and cleanup * Refactor: remove `AllowedStrings` in favor of typeof X[number] * Wip: add e2e tests for the service * Wip: tests in progress * Feat: return fuller variant value * Wip: delete redundant test. Both those tests were testing versions of the same thing, so let's delete one of them * Feat: update openAPI snapshot * Feat: hook up the playground service * Feat: fix test cases for e2e api * Refactor: get rid of _one_ 'as unknown as x' cast * Fix: wait for the client to be ready before we pass it back * Fix: weights go to 1000! * Fix: fix some test assertions, add one more test to be sure * Wip: add some test parameters to hopefully avoid timeouts * Fix: don't init the client if there are no toggles If you don't provide it with any toggles to bootstrap, then the client will never be ready. This avoids that. This adds two ways around it because we'll probably get away with a bit less computation if we don't even try to initialize it. However, we also don't want anyone else to make this mistake. * Chore: modify test params * Feat: use the type system to avoid empty lists for initialization * Refactor: make tests simpler * Feat: test basic context values * Feat: test dynamic context values * Fix: make custom context field test more reliable * Feat: use unique arrays for toggles * Feat: make `appName` required in context * Fix: sdk context schema arbitrary: make appName at least 1 char long * Fix: add a minimum length on appName in the context schema * Fix: fix tests that fail due to new requirements * Fix: update a test: remove variant mapping testing * Fix: fix remaining tests * Feat: rename response.toggles -> response.features * Refactor: avoid single-letter predicate variables * Refactor: extract offlineclient into its own file * Refactor: move arbitraries into separate file * Refactor: move playground requests into util function * Fix: remove duplicate declaration of urlFriendlyString * Chore: update comment * Refactor: align on arbitrary generator naming * Feat: Export single strategy arbitrary
2022-07-12 13:01:10 +02:00
import fc, { Arbitrary } from 'fast-check';
import { ALL_OPERATORS } from '../lib/util/constants';
import { ClientFeatureSchema } from '../lib/openapi/spec/client-feature-schema';
import { IVariant, WeightType } from '../lib/types/model';
feat: add playground API post endpoint (#1791) * Chore: add unleash-client dependency * Feat: add openapi specs for basic sdk contexts and playground reqs * Feat: add openapi spec for response * Feat: add openAPI entry for playground endpoint * Fix: remove required 'projects' property that doesn't exist * Refactor: add test placeholders for playground api * Chore: improve openAPI description for playground request * Refactor: align example project names * Fix: update openapi snapshot * Fix: summary -> description; example -> examples * Feat: add fast-check and stub out one test. The test doesn't work yet. * Feat: add test and generator for sdk context schema * Feat: add generators and tests for all new schemas * Feat: test that the same input is returned exactly * Feat: add more tests and more schemas * Refactor: clean up tests some * Refactor: simplify url friendliness check * Refactor: fix types for playground request schema generator * Feat: add bad request test * Fix: make parameters the correct shape in generator * Feat: scaffold out tests for service and endpoint Liberal use of @ts-expect-error * Fix: update snapshot with new model * Add missing appName * wip: stub out some extra tests * Feat: model strategies for testing * Feat: model variant payloads better * Refactor: input params for function * Refactor: use email address for user id generation * Chore: update comment * Wip: start stubbing out e2e tests * Refactor: move tests requiring db to e2e file * Fix: make e2e tests run as expected * Fix: make toggle generator test work as expected * Fix: increase timeout for long-running e2e test * Wip: map toggles test * Wip: test movement and cleanup * Refactor: remove `AllowedStrings` in favor of typeof X[number] * Wip: add e2e tests for the service * Wip: tests in progress * Feat: return fuller variant value * Wip: delete redundant test. Both those tests were testing versions of the same thing, so let's delete one of them * Feat: update openAPI snapshot * Feat: hook up the playground service * Feat: fix test cases for e2e api * Refactor: get rid of _one_ 'as unknown as x' cast * Fix: wait for the client to be ready before we pass it back * Fix: weights go to 1000! * Fix: fix some test assertions, add one more test to be sure * Wip: add some test parameters to hopefully avoid timeouts * Fix: don't init the client if there are no toggles If you don't provide it with any toggles to bootstrap, then the client will never be ready. This avoids that. This adds two ways around it because we'll probably get away with a bit less computation if we don't even try to initialize it. However, we also don't want anyone else to make this mistake. * Chore: modify test params * Feat: use the type system to avoid empty lists for initialization * Refactor: make tests simpler * Feat: test basic context values * Feat: test dynamic context values * Fix: make custom context field test more reliable * Feat: use unique arrays for toggles * Feat: make `appName` required in context * Fix: sdk context schema arbitrary: make appName at least 1 char long * Fix: add a minimum length on appName in the context schema * Fix: fix tests that fail due to new requirements * Fix: update a test: remove variant mapping testing * Fix: fix remaining tests * Feat: rename response.toggles -> response.features * Refactor: avoid single-letter predicate variables * Refactor: extract offlineclient into its own file * Refactor: move arbitraries into separate file * Refactor: move playground requests into util function * Fix: remove duplicate declaration of urlFriendlyString * Chore: update comment * Refactor: align on arbitrary generator naming * Feat: Export single strategy arbitrary
2022-07-12 13:01:10 +02:00
import { FeatureStrategySchema } from '../lib/openapi/spec/feature-strategy-schema';
import { ConstraintSchema } from 'lib/openapi/spec/constraint-schema';
export const urlFriendlyString = (): Arbitrary<string> =>
fc
.array(
fc.oneof(
fc.integer({ min: 0x30, max: 0x39 }).map(String.fromCharCode), // numbers
fc.integer({ min: 0x41, max: 0x5a }).map(String.fromCharCode), // UPPERCASE LETTERS
fc.integer({ min: 0x61, max: 0x7a }).map(String.fromCharCode), // lowercase letters
fc.constantFrom('-', '_', '~', '.'), // rest
fc.lorem({ maxCount: 1 }), // random words for more 'realistic' names
),
{ minLength: 1 },
)
.map((arr) => arr.join(''));
export const commonISOTimestamp = (): Arbitrary<string> =>
fc
.date({
min: new Date('1900-01-01T00:00:00.000Z'),
max: new Date('9999-12-31T23:59:59.999Z'),
})
.map((timestamp) => timestamp.toISOString());
const strategyConstraints = (): Arbitrary<ConstraintSchema[]> =>
fc.array(
fc.record({
contextName: urlFriendlyString(),
operator: fc.constantFrom(...ALL_OPERATORS),
caseInsensitive: fc.boolean(),
inverted: fc.boolean(),
values: fc.array(fc.string()),
value: fc.string(),
}),
);
export const strategy = (
name: string,
parameters: Arbitrary<Record<string, string>>,
): Arbitrary<FeatureStrategySchema> =>
fc.record({
name: fc.constant(name),
parameters,
constraints: strategyConstraints(),
});
export const strategies = (): Arbitrary<FeatureStrategySchema[]> =>
fc.array(
fc.oneof(
strategy('default', fc.constant({})),
strategy(
'flexibleRollout',
fc.record({
groupId: fc.lorem({ maxCount: 1 }),
rollout: fc.nat({ max: 100 }).map(String),
stickiness: fc.constantFrom(
'default',
'userId',
'sessionId',
),
}),
),
strategy(
'applicationHostname',
fc.record({
hostNames: fc
.uniqueArray(fc.domain())
.map((domains) => domains.join(',')),
}),
),
strategy(
'userWithId',
fc.record({
userIds: fc
.uniqueArray(fc.emailAddress())
.map((ids) => ids.join(',')),
}),
),
strategy(
'remoteAddress',
fc.record({
IPs: fc.uniqueArray(fc.ipV4()).map((ips) => ips.join(',')),
}),
),
),
);
export const variant = (): Arbitrary<IVariant> =>
fc.record(
{
name: urlFriendlyString(),
weight: fc.nat({ max: 1000 }),
weightType: fc.constant(WeightType.VARIABLE),
stickiness: fc.constant('default'),
payload: fc.option(
fc.oneof(
fc.record({
type: fc.constant('json' as 'json'),
value: fc.json(),
}),
fc.record({
type: fc.constant('csv' as 'csv'),
value: fc
.array(fc.lorem())
.map((words) => words.join(',')),
}),
fc.record({
type: fc.constant('string' as 'string'),
value: fc.string(),
}),
),
{ nil: undefined },
),
},
{ requiredKeys: ['name', 'weight', 'weightType', 'stickiness'] },
);
export const variants = (): Arbitrary<IVariant[]> =>
fc
.uniqueArray(variant(), {
maxLength: 1000,
selector: (variantInstance) => variantInstance.name,
})
.map((allVariants) =>
allVariants.map((variantInstance) => ({
...variantInstance,
weight: Math.round(1000 / allVariants.length),
})),
);
feat: add playground API post endpoint (#1791) * Chore: add unleash-client dependency * Feat: add openapi specs for basic sdk contexts and playground reqs * Feat: add openapi spec for response * Feat: add openAPI entry for playground endpoint * Fix: remove required 'projects' property that doesn't exist * Refactor: add test placeholders for playground api * Chore: improve openAPI description for playground request * Refactor: align example project names * Fix: update openapi snapshot * Fix: summary -> description; example -> examples * Feat: add fast-check and stub out one test. The test doesn't work yet. * Feat: add test and generator for sdk context schema * Feat: add generators and tests for all new schemas * Feat: test that the same input is returned exactly * Feat: add more tests and more schemas * Refactor: clean up tests some * Refactor: simplify url friendliness check * Refactor: fix types for playground request schema generator * Feat: add bad request test * Fix: make parameters the correct shape in generator * Feat: scaffold out tests for service and endpoint Liberal use of @ts-expect-error * Fix: update snapshot with new model * Add missing appName * wip: stub out some extra tests * Feat: model strategies for testing * Feat: model variant payloads better * Refactor: input params for function * Refactor: use email address for user id generation * Chore: update comment * Wip: start stubbing out e2e tests * Refactor: move tests requiring db to e2e file * Fix: make e2e tests run as expected * Fix: make toggle generator test work as expected * Fix: increase timeout for long-running e2e test * Wip: map toggles test * Wip: test movement and cleanup * Refactor: remove `AllowedStrings` in favor of typeof X[number] * Wip: add e2e tests for the service * Wip: tests in progress * Feat: return fuller variant value * Wip: delete redundant test. Both those tests were testing versions of the same thing, so let's delete one of them * Feat: update openAPI snapshot * Feat: hook up the playground service * Feat: fix test cases for e2e api * Refactor: get rid of _one_ 'as unknown as x' cast * Fix: wait for the client to be ready before we pass it back * Fix: weights go to 1000! * Fix: fix some test assertions, add one more test to be sure * Wip: add some test parameters to hopefully avoid timeouts * Fix: don't init the client if there are no toggles If you don't provide it with any toggles to bootstrap, then the client will never be ready. This avoids that. This adds two ways around it because we'll probably get away with a bit less computation if we don't even try to initialize it. However, we also don't want anyone else to make this mistake. * Chore: modify test params * Feat: use the type system to avoid empty lists for initialization * Refactor: make tests simpler * Feat: test basic context values * Feat: test dynamic context values * Fix: make custom context field test more reliable * Feat: use unique arrays for toggles * Feat: make `appName` required in context * Fix: sdk context schema arbitrary: make appName at least 1 char long * Fix: add a minimum length on appName in the context schema * Fix: fix tests that fail due to new requirements * Fix: update a test: remove variant mapping testing * Fix: fix remaining tests * Feat: rename response.toggles -> response.features * Refactor: avoid single-letter predicate variables * Refactor: extract offlineclient into its own file * Refactor: move arbitraries into separate file * Refactor: move playground requests into util function * Fix: remove duplicate declaration of urlFriendlyString * Chore: update comment * Refactor: align on arbitrary generator naming * Feat: Export single strategy arbitrary
2022-07-12 13:01:10 +02:00
export const clientFeature = (name?: string): Arbitrary<ClientFeatureSchema> =>
fc.record(
{
name: name ? fc.constant(name) : urlFriendlyString(),
type: fc.constantFrom(
'release',
'kill-switch',
'experiment',
'operational',
'permission',
),
description: fc.lorem(),
project: urlFriendlyString(),
enabled: fc.boolean(),
createdAt: commonISOTimestamp(),
lastSeenAt: commonISOTimestamp(),
stale: fc.boolean(),
impressionData: fc.option(fc.boolean()),
strategies: strategies(),
variants: variants(),
feat: add playground API post endpoint (#1791) * Chore: add unleash-client dependency * Feat: add openapi specs for basic sdk contexts and playground reqs * Feat: add openapi spec for response * Feat: add openAPI entry for playground endpoint * Fix: remove required 'projects' property that doesn't exist * Refactor: add test placeholders for playground api * Chore: improve openAPI description for playground request * Refactor: align example project names * Fix: update openapi snapshot * Fix: summary -> description; example -> examples * Feat: add fast-check and stub out one test. The test doesn't work yet. * Feat: add test and generator for sdk context schema * Feat: add generators and tests for all new schemas * Feat: test that the same input is returned exactly * Feat: add more tests and more schemas * Refactor: clean up tests some * Refactor: simplify url friendliness check * Refactor: fix types for playground request schema generator * Feat: add bad request test * Fix: make parameters the correct shape in generator * Feat: scaffold out tests for service and endpoint Liberal use of @ts-expect-error * Fix: update snapshot with new model * Add missing appName * wip: stub out some extra tests * Feat: model strategies for testing * Feat: model variant payloads better * Refactor: input params for function * Refactor: use email address for user id generation * Chore: update comment * Wip: start stubbing out e2e tests * Refactor: move tests requiring db to e2e file * Fix: make e2e tests run as expected * Fix: make toggle generator test work as expected * Fix: increase timeout for long-running e2e test * Wip: map toggles test * Wip: test movement and cleanup * Refactor: remove `AllowedStrings` in favor of typeof X[number] * Wip: add e2e tests for the service * Wip: tests in progress * Feat: return fuller variant value * Wip: delete redundant test. Both those tests were testing versions of the same thing, so let's delete one of them * Feat: update openAPI snapshot * Feat: hook up the playground service * Feat: fix test cases for e2e api * Refactor: get rid of _one_ 'as unknown as x' cast * Fix: wait for the client to be ready before we pass it back * Fix: weights go to 1000! * Fix: fix some test assertions, add one more test to be sure * Wip: add some test parameters to hopefully avoid timeouts * Fix: don't init the client if there are no toggles If you don't provide it with any toggles to bootstrap, then the client will never be ready. This avoids that. This adds two ways around it because we'll probably get away with a bit less computation if we don't even try to initialize it. However, we also don't want anyone else to make this mistake. * Chore: modify test params * Feat: use the type system to avoid empty lists for initialization * Refactor: make tests simpler * Feat: test basic context values * Feat: test dynamic context values * Fix: make custom context field test more reliable * Feat: use unique arrays for toggles * Feat: make `appName` required in context * Fix: sdk context schema arbitrary: make appName at least 1 char long * Fix: add a minimum length on appName in the context schema * Fix: fix tests that fail due to new requirements * Fix: update a test: remove variant mapping testing * Fix: fix remaining tests * Feat: rename response.toggles -> response.features * Refactor: avoid single-letter predicate variables * Refactor: extract offlineclient into its own file * Refactor: move arbitraries into separate file * Refactor: move playground requests into util function * Fix: remove duplicate declaration of urlFriendlyString * Chore: update comment * Refactor: align on arbitrary generator naming * Feat: Export single strategy arbitrary
2022-07-12 13:01:10 +02:00
},
{ requiredKeys: ['name', 'enabled', 'project', 'strategies'] },
);
export const clientFeatures = (constraints?: {
minLength?: number;
}): Arbitrary<ClientFeatureSchema[]> =>
fc.uniqueArray(clientFeature(), {
...constraints,
selector: (v) => v.name,
});
// TEST ARBITRARIES
test('url-friendly strings are URL-friendly', () =>
fc.assert(
fc.property(urlFriendlyString(), (input: string) =>
/^[\w~.-]+$/.test(input),
),
));
test('variant payloads are either present or undefined; never null', () =>
fc.assert(
fc.property(
variant(),
(generatedVariant) =>
!!generatedVariant.payload ||
generatedVariant.payload === undefined,
),
));