Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: refactor mocks to its own project #284

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ module.exports = {
ignorePatterns: ['**/dist/**', '**/vercel/examples/**'],
rules: {
'@typescript-eslint/lines-between-class-members': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{ ignoreRestSiblings: true, argsIgnorePattern: '^_', varsIgnorePattern: '^__' },
],
Comment on lines +14 to +17
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was concerned with increased usage of disabling of this rule and so this is a more sustainable practice going forward.

'prettier/prettier': ['error'],
'class-methods-use-this': 'off',
'import/no-extraneous-dependencies': [
Expand All @@ -19,5 +23,11 @@ module.exports = {
devDependencies: ['**/jest*.ts', '**/*.test.ts', '**/rollup.config.ts'],
},
],
'import/default': 'error',
'import/export': 'error',
'import/no-self-import': 'error',
'import/no-cycle': 'error',
'import/no-useless-path-segments': 'error',
'import/no-duplicates': 'error',
Comment on lines +26 to +31
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional sensible rules which are good to have.

},
};
24 changes: 24 additions & 0 deletions .github/workflows/mocks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: sdk/cloudflare

on:
push:
branches: [main, 'feat/**']
paths-ignore:
- '**.md' #Do not need to run CI for markdown changes.
pull_request:
branches: [main, 'feat/**']
paths-ignore:
- '**.md'

jobs:
build-test-mocks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- id: shared
name: Shared CI Steps
uses: ./actions/ci
with:
workspace_name: '@launchdarkly/private-js-mocks'
workspace_path: packages/shared/mocks
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "@launchdarkly/js-core",
"workspaces": [
"packages/shared/common",
"packages/shared/mocks",
"packages/shared/sdk-client",
"packages/shared/sdk-server",
"packages/shared/sdk-server-edge",
Expand Down
3 changes: 1 addition & 2 deletions packages/sdk/akamai-base/example/ldClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ const flagData = `

class MyCustomStoreProvider implements EdgeProvider {
// root key is formatted as LD-Env-{Launchdarkly environment client ID}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async get(rootKey: string): Promise<string> {
async get(_rootKey: string): Promise<string> {
// you should provide an implementation to retrieve your flags from launchdarkly's https://sdk.launchdarkly.com/sdk/latest-all endpoint.
// see https://docs.launchdarkly.com/sdk/features/flags-from-files for more information.
return flagData;
Expand Down
7 changes: 3 additions & 4 deletions packages/sdk/server-node/__tests__/LDClientNode.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { internal, LDContext } from '@launchdarkly/js-server-sdk-common';
import { LDContext } from '@launchdarkly/js-server-sdk-common';
import { logger } from '@launchdarkly/private-js-mocks';

import { init } from '../src';

const { mocks } = internal;

it('fires ready event in offline mode', (done) => {
const client = init('sdk_key', { offline: true });
client.on('ready', () => {
Expand All @@ -18,7 +17,7 @@ it('fires the failed event if initialization fails', async () => {
const failedHandler = jest.fn().mockName('failedHandler');
const client = init('sdk_key', {
sendEvents: false,
logger: mocks.logger,
logger,
updateProcessor: (clientContext, dataSourceUpdates, initSuccessHandler, errorHandler) => ({
start: () => {
setTimeout(() => errorHandler?.(new Error('Something unexpected happened')), 0);
Expand Down
14 changes: 3 additions & 11 deletions packages/sdk/server-node/__tests__/LDClientNode.tls.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,14 @@ import {
TestHttpServer,
} from 'launchdarkly-js-test-helpers';

import { internal } from '@launchdarkly/js-server-sdk-common';
import { logger } from '@launchdarkly/private-js-mocks';

import { basicLogger, LDClient, LDLogger } from '../src';
import { LDClient } from '../src';
import LDClientNode from '../src/LDClientNode';

const { mocks } = internal;
describe('When using a TLS connection', () => {
let client: LDClient;
let server: TestHttpServer;
let logger: LDLogger;

beforeEach(() => {
logger = basicLogger({
destination: () => {},
});
});

it('can connect via HTTPS to a server with a self-signed certificate, if CA is specified', async () => {
server = await TestHttpServer.startSecure();
Expand Down Expand Up @@ -90,7 +82,7 @@ describe('When using a TLS connection', () => {
stream: false,
tlsParams: { ca: server.certificate },
diagnosticOptOut: true,
logger: mocks.logger,
logger,
});

await client.waitForInitialization();
Expand Down
1 change: 1 addition & 0 deletions packages/sdk/server-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"launchdarkly-eventsource": "2.0.1"
},
"devDependencies": {
"@launchdarkly/private-js-mocks": "0.0.1",
"@trivago/prettier-plugin-sort-imports": "^4.1.1",
"@types/jest": "^29.4.0",
"@typescript-eslint/eslint-plugin": "^6.1.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ class NoopResponse implements Response {
}

export default class EdgeRequests implements Requests {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fetch(url: string, options: Options = {}): Promise<Response> {
fetch(url: string, _options: Options = {}): Promise<Response> {
return Promise.resolve(new NoopResponse());
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
// eslint-disable-next-line import/prefer-default-export
export const createCallbacks = () => ({
onError: (err: Error) => {},
onFailed: (err: Error) => {},
onError: (_err: Error) => {},
onFailed: (_err: Error) => {},
onReady: () => {},
onUpdate: (key: string) => {},
onUpdate: (_key: string) => {},
hasEventListeners: () => false,
});
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { clientContext, ContextDeduplicator } from '@launchdarkly/private-js-mocks';

import { Context } from '../../../src';
import { LDDeliveryStatus, LDEventType } from '../../../src/api/subsystem';
import { LDContextDeduplicator, LDDeliveryStatus, LDEventType } from '../../../src/api/subsystem';
import { EventProcessor, InputIdentifyEvent } from '../../../src/internal';
import { EventProcessorOptions } from '../../../src/internal/events/EventProcessor';
import { clientContext } from '../../../src/internal/mocks';
import ContextDeduplicator from '../../../src/internal/mocks/contextDeduplicator';
import BasicLogger from '../../../src/logging/BasicLogger';
import format from '../../../src/logging/format';

Expand Down Expand Up @@ -84,7 +84,7 @@ function makeFeatureEvent(
}

describe('given an event processor', () => {
let contextDeduplicator: ContextDeduplicator;
let contextDeduplicator: LDContextDeduplicator;
let eventProcessor: EventProcessor;

const eventProcessorConfig: EventProcessorOptions = {
Expand Down
1 change: 1 addition & 0 deletions packages/shared/common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
},
"license": "Apache-2.0",
"devDependencies": {
"@launchdarkly/private-js-mocks": "0.0.1",
"@trivago/prettier-plugin-sort-imports": "^4.1.1",
"@types/jest": "^29.4.0",
"@typescript-eslint/eslint-plugin": "^6.1.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { basicPlatform } from '../mocks';
import { basicPlatform } from '@launchdarkly/private-js-mocks';

import DiagnosticsManager from './DiagnosticsManager';

describe('given a diagnostics manager', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
import { basicPlatform } from '@launchdarkly/private-js-mocks';

import { Info, PlatformData, SdkData } from '../../api';
import { LDDeliveryStatus, LDEventSenderResult, LDEventType } from '../../api/subsystem';
import { ApplicationTags, ClientContext } from '../../options';
import { basicPlatform } from '../mocks';
import EventSender from './EventSender';

jest.mock('../../utils', () => {
Expand Down
1 change: 0 additions & 1 deletion packages/shared/common/src/internal/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './diagnostics';
export * from './events';
export * from './stream';
export * as mocks from './mocks';
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good riddance.

14 changes: 0 additions & 14 deletions packages/shared/common/src/internal/mocks/clientContext.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { basicPlatform, clientContext, logger } from '@launchdarkly/private-js-mocks';

import { EventName, ProcessStreamResponse } from '../../api';
import { LDStreamProcessor } from '../../api/subsystem';
import { LDStreamingError } from '../../errors';
import { defaultHeaders } from '../../utils';
import { DiagnosticsManager } from '../diagnostics';
import { basicPlatform, clientContext, logger } from '../mocks';
import StreamingProcessor from './StreamingProcessor';

const dateNowString = '2023-08-10';
Expand Down
3 changes: 2 additions & 1 deletion packages/shared/common/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"sourceMap": true,
"declaration": true,
"declarationMap": true, // enables importers to jump to source
"stripInternal": true
"stripInternal": true,
"composite": true
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mocks need types from common. This composite allows common to be referred to in mocks so we can import common types.

},
"exclude": ["**/*.test.ts", "dist", "node_modules", "__tests__"]
}
3 changes: 3 additions & 0 deletions packages/shared/mocks/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Changelog

All notable changes to `@launchdarkly/private-js-mocks` will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org).
13 changes: 13 additions & 0 deletions packages/shared/mocks/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2023 Catamorphic, Co.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
28 changes: 28 additions & 0 deletions packages/shared/mocks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# LaunchDarkly SDK JavaScript Mocks

[![Actions Status][mocks-ci-badge]][mocks-ci]

**Internal use only.**

This project contains JavaScript mocks that are consumed in unit tests in client-side and server-side JavaScript SDKs.

## Contributing

See [Contributing](../shared/CONTRIBUTING.md).

## About LaunchDarkly

- LaunchDarkly is a continuous delivery platform that provides feature flags as a service and allows developers to iterate quickly and safely. We allow you to easily flag your features and manage them from the LaunchDarkly dashboard. With LaunchDarkly, you can:
- Roll out a new feature to a subset of your users (like a group of users who opt-in to a beta tester group), gathering feedback and bug reports from real-world use cases.
- Gradually roll out a feature to an increasing percentage of users, and track the effect that the feature has on key metrics (for instance, how likely is a user to complete a purchase if they have feature A versus feature B?).
- Turn off a feature that you realize is causing performance problems in production, without needing to re-deploy, or even restart the application with a changed configuration file.
- Grant access to certain features based on user attributes, like payment plan (eg: users on the ‘gold’ plan get access to more features than users in the ‘silver’ plan). Disable parts of your application to facilitate maintenance, without taking everything offline.
- LaunchDarkly provides feature flag SDKs for a wide variety of languages and technologies. Check out [our documentation](https://docs.launchdarkly.com/sdk) for a complete list.
- Explore LaunchDarkly
- [launchdarkly.com](https://www.launchdarkly.com/ 'LaunchDarkly Main Website') for more information
- [docs.launchdarkly.com](https://docs.launchdarkly.com/ 'LaunchDarkly Documentation') for our documentation and SDK reference guides
- [apidocs.launchdarkly.com](https://apidocs.launchdarkly.com/ 'LaunchDarkly API Documentation') for our API documentation
- [blog.launchdarkly.com](https://blog.launchdarkly.com/ 'LaunchDarkly Blog Documentation') for the latest product updates

[mocks-ci-badge]: https://github.com/launchdarkly/js-core/actions/workflows/mocks.yml/badge.svg
[mocks-ci]: https://github.com/launchdarkly/js-core/actions/workflows/mocks.yml
7 changes: 7 additions & 0 deletions packages/shared/mocks/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
transform: { '^.+\\.ts?$': 'ts-jest' },
testMatch: ['**/*.test.ts?(x)'],
testEnvironment: 'node',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
collectCoverageFrom: ['src/**/*.ts'],
};
50 changes: 50 additions & 0 deletions packages/shared/mocks/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "@launchdarkly/private-js-mocks",
"private": true,
Comment on lines +2 to +3
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • We are not publishing mocks to npm because it's internal use only.
  • I'm open to improving the name of this package. It's the best I can come up with right now.

"version": "0.0.1",
"type": "commonjs",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"homepage": "https://github.com/launchdarkly/js-core/tree/main/packages/shared/common",
"repository": {
"type": "git",
"url": "https://github.com/launchdarkly/js-core.git"
},
"description": "LaunchDarkly SDK for JavaScript - mocks",
"files": [
"dist"
],
"keywords": [
"mocks",
"unit",
"tests",
"launchdarkly",
"js",
"client"
],
"scripts": {
"test": "",
"build": "npx tsc",
"clean": "npx tsc --build --clean",
"lint": "npx eslint --ext .ts",
"lint:fix": "yarn run lint -- --fix"
},
"license": "Apache-2.0",
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^4.2.0",
"@types/jest": "^29.5.5",
"@typescript-eslint/eslint-plugin": "^6.7.3",
"@typescript-eslint/parser": "^6.7.3",
"eslint": "^8.50.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-airbnb-typescript": "^17.1.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-import": "^2.28.1",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.7.0",
"launchdarkly-js-test-helpers": "^2.2.0",
"prettier": "^3.0.3",
"ts-jest": "^29.0.5",
"typescript": "^5.2.2"
}
}
13 changes: 13 additions & 0 deletions packages/shared/mocks/src/clientContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { ClientContext } from '@common';

import platform from './platform';

const clientContext: ClientContext = {
basicConfiguration: {
sdkKey: 'testSdkKey',
serviceEndpoints: { events: '', polling: '', streaming: 'https://mockstream.ld.com' },
},
platform,
};

export default clientContext;
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { LDContextDeduplicator } from '../../api/subsystem';
import { Context } from '../../index';
import type { Context, subsystem } from '@common';

export default class ContextDeduplicator implements LDContextDeduplicator {
export default class ContextDeduplicator implements subsystem.LDContextDeduplicator {
flushInterval?: number | undefined = 0.1;

seen: string[] = [];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Crypto, Hasher, Hmac } from '../../api';
import type { Crypto, Hasher, Hmac } from '@common';

export const hasher: Hasher = {
update: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import clientContext from './clientContext';
import ContextDeduplicator from './contextDeduplicator';
import { crypto, hasher } from './hasher';
import logger from './logger';
import basicPlatform from './platform';
Expand All @@ -10,6 +11,7 @@ export {
crypto,
logger,
hasher,
ContextDeduplicator,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was a bug before this PR where this export was missing. This is to fix that bug.

MockStreamingProcessor,
setupMockStreamingProcessor,
};
Loading