From b659306ebcfee4a860c89b8ea8984fda99637eba Mon Sep 17 00:00:00 2001 From: Erik Kieckhafer Date: Mon, 16 Sep 2019 09:26:12 -0700 Subject: [PATCH 1/8] chore: remove fixtures no longer used Signed-off-by: Erik Kieckhafer --- .../core/core/server/fixtures/accounts.js | 109 ------ .../plugins/core/core/server/fixtures/cart.js | 262 -------------- .../core/core/server/fixtures/groups.js | 20 -- .../core/core/server/fixtures/index.js | 30 -- .../core/core/server/fixtures/orders.js | 262 -------------- .../core/core/server/fixtures/packages.js | 76 ---- .../core/core/server/fixtures/products.js | 228 ------------ .../core/core/server/fixtures/shops.js | 326 ------------------ .../core/core/server/fixtures/users.js | 164 --------- 9 files changed, 1477 deletions(-) delete mode 100755 imports/plugins/core/core/server/fixtures/accounts.js delete mode 100755 imports/plugins/core/core/server/fixtures/cart.js delete mode 100755 imports/plugins/core/core/server/fixtures/groups.js delete mode 100644 imports/plugins/core/core/server/fixtures/index.js delete mode 100755 imports/plugins/core/core/server/fixtures/orders.js delete mode 100644 imports/plugins/core/core/server/fixtures/packages.js delete mode 100755 imports/plugins/core/core/server/fixtures/products.js delete mode 100755 imports/plugins/core/core/server/fixtures/shops.js delete mode 100755 imports/plugins/core/core/server/fixtures/users.js diff --git a/imports/plugins/core/core/server/fixtures/accounts.js b/imports/plugins/core/core/server/fixtures/accounts.js deleted file mode 100755 index 96cef50686d..00000000000 --- a/imports/plugins/core/core/server/fixtures/accounts.js +++ /dev/null @@ -1,109 +0,0 @@ -/* eslint-disable require-jsdoc */ -/* eslint-disable node/no-unsupported-features/es-syntax */ -import faker from "faker"; -import _ from "lodash"; -import { Factory } from "meteor/dburles:factory"; -import { Accounts } from "/lib/collections"; -import { getUser } from "./users"; -import { getShop } from "./shops"; - -/** - * @method getAccount - * @memberof Fixtures - * @returns {Object} Existing account or Factory account - */ -export function getAccount() { - const existingAccount = Accounts.findOne(); - return existingAccount || Factory.create("account"); -} - -/** - * @method getAddress - * @memberof Fixtures - * @param {Object} [options={}] Address options, optional - * @param {String} [options._id] - id of CartItem - * @param {String} [options.fullName] fullName - * @param {String} [options.address1] address1 - * @param {String} [options.address2] address2 - * @param {String} [options.city] city - * @param {String} [options.company] company - * @param {String} [options.phone] phone - * @param {String} [options.region] region - * @param {String} [options.postal] postal - * @param {String} [options.country] country - * @param {Boolean} [options.isCommercial] isCommercial - * @param {Boolean} [options.isShippingDefault] isShippingDefault - * @param {Boolean} [options.isBillingDefault] isBillingDefault - * @param {Array} [options.metafields] metafields - * @returns {Object} Address object - */ -export function getAddress(options = {}) { - const defaults = { - fullName: options.fullName || faker.name.findName(), - address1: options.address1 || faker.address.streetAddress(), - address2: options.address2 || faker.address.secondaryAddress(), - city: options.city || faker.address.city(), - company: faker.company.companyName(), - phone: faker.phone.phoneNumber(), - region: options.region || faker.address.stateAbbr(), - postal: options.postal || faker.address.zipCode(), - country: options.country || faker.address.countryCode(), - isCommercial: options.isCommercial || faker.random.boolean(), - isShippingDefault: options.isShippingDefault || faker.random.boolean(), - isBillingDefault: options.isBillingDefault || faker.random.boolean(), - metafields: [] - }; - return _.defaults(options, defaults); -} - -/** - * @name account - * @memberof Fixtures - * @summary Factory for Account - * @example Factory.create("account", { _id: "12345678", shopId }); - * @property {String} shopID - `getShop()._id` - * @property {String} userId id - `Factory.get("user")` - * @property {Array} emails `[{ - address: faker.internet.email(), - verified: faker.random.boolean() - }]` - * @property {Boolean} acceptsMarketing - `true` - * @property {String} state - `"new"` - * @property {Note} note - `faker.lorem.sentences()` - * @property {Object} profile - `{ - addressBook: [ - getAddress() - ] - }` - * @property {Array} metafields - '[]' - * @property {Date} createdAt - `new Date()` - * @property {Date} updatedAt - `new Date()` - * @returns {undefined} - */ -export function createAccountFactory() { - // there are many places in code which require that an Account's _id be equal - // to the User's _id (and therefore equal to userId) - Factory.define("account", Accounts, { - shopId: getShop()._id, - userId: getUser()._id, - emails: [{ - address: faker.internet.email(), - verified: faker.random.boolean() - }], - acceptsMarketing: true, - state: "new", - note: faker.lorem.sentences(), - profile: { - addressBook: [ - getAddress() - ] - }, - metafields: [], - createdAt: new Date(), - updatedAt: new Date() - }); -} - -export default function () { - createAccountFactory(); -} diff --git a/imports/plugins/core/core/server/fixtures/cart.js b/imports/plugins/core/core/server/fixtures/cart.js deleted file mode 100755 index 2d5a3aedeeb..00000000000 --- a/imports/plugins/core/core/server/fixtures/cart.js +++ /dev/null @@ -1,262 +0,0 @@ -/* eslint-disable require-jsdoc */ -import faker from "faker"; -import _ from "lodash"; -import Random from "@reactioncommerce/random"; -import { Factory } from "meteor/dburles:factory"; -import getGraphQLContextInMeteorMethod from "/imports/plugins/core/graphql/server/getGraphQLContextInMeteorMethod"; -import publishProductToCatalog from "/imports/plugins/core/catalog/server/no-meteor/utils/publishProductToCatalog"; -import { Cart, Products } from "/lib/collections"; -import { getShop } from "./shops"; -import { getAddress } from "./accounts"; -import { addProduct } from "./products"; - -/** - * @method getCartItem - * @memberof Fixtures - * @param {Object} [options] - Options object (optional) - * @param {String} [options._id] - id of CartItem - * @param {String} [options.productId] - _id of product that item came from - * @param {String} [options.shopId] - _id of shop that item came from - * @param {number} [options.quantity] - quantity of item in CartItem - * @param {Object} [options.variants] - _single_ variant object. ¯\_(ツ)_/¯ why called variants - * - * @returns {Object} - randomly generated cartItem/orderItem data object - */ -export function getCartItem(options = {}) { - const product = addProduct(); - const context = Promise.await(getGraphQLContextInMeteorMethod(null)); - Promise.await(publishProductToCatalog(product, context)); - const variant = Products.findOne({ ancestors: [product._id] }); - const childVariants = Products.find({ - ancestors: [ - product._id, variant._id - ] - }).fetch(); - const selectedOption = Random.choice(childVariants); - const quantity = 1; - const price = _.random(1, 100); - const defaults = { - _id: Random.id(), - addedAt: new Date(), - createdAt: new Date(), - isTaxable: false, - optionTitle: selectedOption.optionTitle, - price: { - amount: price, - currencyCode: "USD" - }, - priceWhenAdded: { - amount: price, - currencyCode: "USD" - }, - productId: product._id, - productSlug: product.handle, - productType: product.type, - quantity, - shopId: options.shopId || getShop()._id, - subtotal: { - amount: price * quantity, - currencyCode: "USD" - }, - title: product.title, - updatedAt: new Date(), - variantId: selectedOption._id, - variantTitle: selectedOption.title - }; - return _.defaults(options, defaults); -} - -/** - * @method getSingleCartItem - * @memberof Fixtures - * @param {Object} [options] - Options object (optional) - * @param {String} [options._id] - id of CartItem - * @param {String} [options.productId] - _id of product that item came from - * @param {String} [options.shopId] - _id of shop that item came from - * @returns {Object} - randomly generated cartItem/orderItem data object with only one cart item - */ -function getSingleCartItem(options = {}) { - const cartItem = getCartItem(options); - const quantity = options.cartQuantity || 1; - cartItem.quantity = quantity; - return cartItem; -} - -/** - * @method createCart - * @memberof Fixtures - * @param {String} productId ID of Product - * @param {String} variantId ID of Product Variant - * @returns {Object} Inserted cart object - */ -export function createCart(productId, variantId) { - const product = Products.findOne(productId); - const variant = Products.findOne(variantId); - const user = Factory.create("user"); - const account = Factory.create("account", { userId: user._id }); - const quantity = 1; - const cartItem = { - _id: Random.id(), - addedAt: new Date(), - createdAt: new Date(), - isTaxable: false, - optionTitle: variant.optionTitle, - price: { - amount: variant.price, - currencyCode: "USD" - }, - priceWhenAdded: { - amount: variant.price, - currencyCode: "USD" - }, - productId: product._id, - productSlug: product.handle, - productType: product.type, - quantity, - shopId: getShop()._id, - subtotal: { - amount: variant.price * quantity, - currencyCode: "USD" - }, - title: product.title, - updatedAt: new Date(), - variantId: variant._id, - variantTitle: variant.title - }; - - const cart = { - shopId: getShop()._id, - accountId: account._id, - email: faker.internet.email(), - items: [cartItem], - currencyCode: "USD", - shipping: [ - { - _id: Random.id(), - shopId: getShop()._id, - address: getAddress() - } - ], - createdAt: faker.date.past(), - updatedAt: new Date() - }; - const newCartId = Cart.insert(cart); - const insertedCart = Cart.findOne({ _id: newCartId }); - return insertedCart; -} - -/** - * @description exports cart fixtures - * @returns {undefined} undefined - */ -export default function () { - /** - * @name Cart - * @memberof Fixtures - * @summary Define cart Factory - * @example const cart = Factory.create("cartMultiItems"); - * @property {string} shopId id - `getShop().id` - * @property {string} accountId id - `Factory.get("account")` - * @property {string} email - `faker.internet.email()` - * @property {Array} items - `[getCartItem(), getCartItem()]` - * @property {Array} shipping - `[ - { - _id: Random.id(), - shopId: getShop()._id, - address: addressForOrder - } - ]` - * @property {Date} createdAt - `faker.date.past()` - * @property {Date} updatedAt - `new Date()` - * @description Types of Cart Factories: - * - `cart`: A cart with a user and two items - * - `cartToOrder`: A cart with shipping, billing info and at the Checkout workflow state - * - `anonymousCart`: An empty cart with an anonymous user - * - `cartOne`: A cart with one item - * - `cartTwo`: A cart with one item with quantity 2 - * - `cartMultiItems`: A cart with two items, 1 each - * - `cartMultiShop`: A cart with two items, from different shops - * - `cartNoItems`: A cart with a user and no items - */ - const cartNoItems = { - shopId: getShop()._id, - accountId: Factory.get("account", { userId: Factory.get("user") }), - currencyCode: "USD", - email: faker.internet.email(), - items: [], - shipping: [], - workflow: { - status: "new", - workflow: [] - }, - createdAt: faker.date.past(), - updatedAt: new Date() - }; - - const cart = { - shopId: getShop()._id, - accountId: Factory.get("account"), - currencyCode: "USD", - email: faker.internet.email(), - items: [ - getCartItem(), - getCartItem() - ], - shipping: [], - workflow: { - status: "new", - workflow: [] - }, - createdAt: faker.date.past(), - updatedAt: new Date() - }; - - const cartOne = { - items: [ - getSingleCartItem() - ] - }; - - const cartTwo = { - items: [ - getSingleCartItem({ cartQuantity: 2 }) - ] - }; - - const cartMultiItems = { - items: [getSingleCartItem(), getSingleCartItem()] - }; - - const cartMultiShopItems = { - items: [getSingleCartItem(), getSingleCartItem({ shopId: Random.id() })] - }; - - const addressForOrder = getAddress(); - const cartToOrder = { - shopId: getShop()._id, - shipping: [ - { - _id: Random.id(), - shopId: getShop()._id, - address: addressForOrder, - payment: { - _id: Random.id(), - shopId: getShop()._id, - address: addressForOrder - } - } - ] - }; - - const anonymousCart = { - accountId: Factory.get("account", { userId: Factory.get("anonymous") }) - }; - - Factory.define("cart", Cart, Object.assign({}, cart)); - Factory.define("anonymousCart", Cart, Object.assign({}, cart, anonymousCart)); - Factory.define("cartOne", Cart, Object.assign({}, cart, cartToOrder, cartOne)); - Factory.define("cartTwo", Cart, Object.assign({}, cart, cartToOrder, cartTwo)); - Factory.define("cartMultiItems", Cart, Object.assign({}, cart, cartToOrder, cartMultiItems)); - Factory.define("cartMultiShop", Cart, Object.assign({}, cart, cartToOrder, cartMultiShopItems)); - Factory.define("cartNoItems", Cart, Object.assign({}, cart, cartToOrder, cartNoItems)); -} diff --git a/imports/plugins/core/core/server/fixtures/groups.js b/imports/plugins/core/core/server/fixtures/groups.js deleted file mode 100755 index c5dc95937e0..00000000000 --- a/imports/plugins/core/core/server/fixtures/groups.js +++ /dev/null @@ -1,20 +0,0 @@ -import { Factory } from "meteor/dburles:factory"; -import { Groups } from "/lib/collections"; -import { getShop } from "./shops"; - -/** - * @summary define group factory - * @returns {undefined} - */ -export default function () { - const group = { - name: "default", - slug: "default", - permissions: ["test"], - shopId: getShop()._id, - createdAt: new Date(), - updatedAt: new Date() - }; - - Factory.define("group", Groups, group); -} diff --git a/imports/plugins/core/core/server/fixtures/index.js b/imports/plugins/core/core/server/fixtures/index.js deleted file mode 100644 index 00bf29c022f..00000000000 --- a/imports/plugins/core/core/server/fixtures/index.js +++ /dev/null @@ -1,30 +0,0 @@ -import accounts from "./accounts"; -import cart from "./cart"; -import orders from "./orders"; -import products from "./products"; -import { examplePaymentMethod, examplePackage } from "./packages"; -import shops from "./shops"; -import users from "./users"; -import groups from "./groups"; - -/** - * @file Fixtures and Factories for testing - Use these factories to test shops, users, example payment methods, example packages, orders, products, accounts, carts and user groups. - * See the [meteor-factory](https://github.com/versolearning/meteor-factory/) documentation to learn how to define, extend and create your own factories. - * - * @namespace Fixtures -*/ - -/** - * @returns {undefined} - */ -export default function fixtures() { - shops(); - users(); - examplePaymentMethod(); - examplePackage(); - accounts(); - products(); - cart(); - orders(); - groups(); -} diff --git a/imports/plugins/core/core/server/fixtures/orders.js b/imports/plugins/core/core/server/fixtures/orders.js deleted file mode 100755 index 91ccb9edea1..00000000000 --- a/imports/plugins/core/core/server/fixtures/orders.js +++ /dev/null @@ -1,262 +0,0 @@ -/* eslint-disable node/no-unsupported-features/es-syntax */ -import faker from "faker"; -import _ from "lodash"; -import Random from "@reactioncommerce/random"; -import { Factory } from "meteor/dburles:factory"; -import { Orders, Products } from "/lib/collections"; -import { getShop } from "./shops"; -import { getAccount, getAddress } from "./accounts"; -import { addProduct } from "./products"; - -/** - * @method randomProcessor - * @memberof Fixtures - * @summary Return a random payment processor string, either: `"Stripe"` `"Braintree"` - * @returns {String} Name of payment processor - */ -export function randomProcessor() { - return _.sample(["Stripe", "Braintree"]); -} - -const itemIdOne = Random.id(); -const itemIdTwo = Random.id(); - -/** - * @method randomStatus - * @memberof Fixtures - * @summary Return a random payment status, from: `"created", "approved", "failed", "canceled", "expired", "pending", "voided", "settled"` - * @returns {String} Payment status string - */ -export function randomStatus() { - return _.sample([ - "created", - "approved", - "failed", - "canceled", - "expired", - "pending", - "voided", - "settled" - ]); -} - -/** - * @method randomMode - * @memberof Fixtures - * @summary Return a random credit card status, from: `"authorize", "capture", "refund", "void"` - * @returns {String} Payment status string - */ -export function randomMode() { - return _.sample(["authorize", "capture", "refund", "void"]); -} - -/** - * @method getAccountId - * @memberof Fixtures - * @returns {String} ID - */ -export function getAccountId() { - return getAccount()._id; -} - -/** - * @method getShopId - * @memberof Fixtures - * @returns {String} ID - */ -export function getShopId() { - return getShop()._id; -} - -/** - * @method defineOrders - * @memberof Fixtures - * @returns {undefined} - */ -export default function defineOrders() { - const shopId = getShopId(); - const accountId = getAccountId(); - - /** - * @name order - * @memberof Fixtures - * @summary Create an Order Factory - * @example order = Factory.create("order") - * @property {String} status OrderItems - `faker.lorem.sentence(3)` - * @property {Array} history OrderItems History - `[]` - * @property {Array} documents OrderItems Document - `[]` - * @property {String} cartId Order - `Random.id()` - * @property {Array} notes Order - `[]` - * @property {String} shopId Cart - `shopId` - * @property {String} shopId.accountId Cart - `accountId` - * @property {String} shopId.email Cart - `faker.internet.email()` - * @property {String} shopId.workflow Cart - Object - * @property {String} shopId.workflow.status Cart - `"new"` - * @property {String} shopId.workflow Cart - `"coreOrderWorkflow/created"` - * @property {Array} shopId.items Array of products - * @property {String} shopId.items._id Cart - Product - cart ID - * @property {String} shopId.items.title Cart - Product - `"itemOne"` - * @property {String} shopId.items.shopId Cart - Product - store ID - * @property {String} shopId.items.productId Cart - Product - product ID - * @property {Number} shopId.items.quantity Cart - Product - `1` - * @property {Object} shopId.items.variants Cart - Product - variants - * @property {Object} shopId.items.workflow Cart - Product - Object - * @property {String} shopId.items.workflow.status Cart - Product - `"new"` - * @property {String[]} supportedFulfillmentTypes - ["shipping"] - * @property {Array} shipping - Shipping - `[{}]` - * @property {String[]} shipping.itemIds - * @property {Object} shipping.payment - A payment - * @property {String} shipping.payment._id - Billing - `Random.id()` - * @property {Object} shipping.payment.address - Billing - Address object - * @property {String} shipping.payment.displayName - `"MasterCard 2346"` - * @property {String} shipping.payment.method - `"credit"` - * @property {String} shipping.payment.processor - `"Example"` - * @property {String} shipping.payment.paymentPluginName - `"example-paymentmethod"` - * @property {String} shipping.payment.mode - `"authorize"` - * @property {String} shipping.payment.status - `"created"` - * @property {Number} shipping.payment.amount - `12.4` - * @property {Object} shipping.payment.invoice - Object - * @property {Number} shipping.payment.invoice.total - `12.45` - * @property {Number} shipping.payment.invoice.subtotal - `12.45` - * @property {Number} shipping.payment.invoice.discounts - `0` - * @property {Number} shipping.payment.invoice.taxes - `0.12` - * @property {Number} shipping.payment.invoice.shipping - `4.0` - * @property {String} state - `"new"` - * @property {Date} createdAt - `new Date()` - * @property {Date} updatedAt - `new Date()` - */ - Factory.define("order", Orders, { - // Schemas.OrderItems - status: faker.lorem.sentence(3), - history: [], - documents: [], - - // Schemas.Order - cartId: Random.id(), - notes: [], - - // Schemas.Cart - shopId, - accountId, - email: faker.internet.email(), - workflow: { - status: "new", - workflow: [ - "coreOrderWorkflow/created" - ] - }, - supportedFulfillmentTypes: ["shipping"], - shipping() { - const product = addProduct({ shopId }); - const variant = Products.findOne({ ancestors: [product._id] }); - const childVariants = Products.find({ - ancestors: [ - product._id, variant._id - ] - }).fetch(); - const selectedOption = Random.choice(childVariants); - const product2 = addProduct({ shopId }); - const variant2 = Products.findOne({ ancestors: [product2._id] }); - const childVariants2 = Products.find({ - ancestors: [ - product2._id, variant2._id - ] - }).fetch(); - const selectedOption2 = Random.choice(childVariants2); - return [{ - _id: Random.id(), - address: getAddress({ isShippingDefault: true }), - type: "shipping", - invoice: { - currencyCode: "USD", - discounts: 0, - effectiveTaxRate: 0.05, - shipping: 4.00, - subtotal: 12.45, - surcharges: 0, - taxableAmount: 12.45, - taxes: 0.12, - total: 12.45 - }, - items: [{ - _id: itemIdOne, - addedAt: new Date(), - createdAt: new Date(), - updatedAt: new Date(), - price: { - amount: 1, - currencyCode: "USD" - }, - subtotal: 1, - title: "firstItem", - shopId: product.shopId, - productId: product._id, - quantity: 1, - product, - variants: selectedOption, - workflow: { - status: "new" - } - }, { - _id: itemIdTwo, - addedAt: new Date(), - createdAt: new Date(), - updatedAt: new Date(), - price: { - amount: 1, - currencyCode: "USD" - }, - subtotal: 1, - title: "secondItem", - shopId: product2.shopId, - productId: product2._id, - quantity: 1, - product: product2, - variants: selectedOption2, - workflow: { - status: "new" - } - }], - itemIds: [itemIdOne, itemIdTwo], - shipmentMethod: { - _id: Random.id(), - currencyCode: "USD", - handling: 0, - rate: 0, - name: "name", - label: "label" - }, - totalItemQuantity: 2, - shopId, - workflow: { - status: "new" - } - }]; - }, // fulfillment group Schema - payments: [ - { - _id: Random.id(), - address: getAddress({ isBillingDefault: true }), - amount: 12.45, - createdAt: new Date(), - currencyCode: "USD", - displayName: "MasterCard 2346", - method: "credit", - mode: "authorize", - name: "iou_example", - paymentPluginName: "example-paymentmethod", - processor: "Example", - shopId, - status: "created", - transactionId: "txID", - transactions: [] - } - ], - state: "new", - currencyCode: "USD", - referenceId: () => Random.id(), - totalItemQuantity: 2, - createdAt: new Date(), - updatedAt: new Date() - }); -} diff --git a/imports/plugins/core/core/server/fixtures/packages.js b/imports/plugins/core/core/server/fixtures/packages.js deleted file mode 100644 index a3e1fc394d3..00000000000 --- a/imports/plugins/core/core/server/fixtures/packages.js +++ /dev/null @@ -1,76 +0,0 @@ -import { Factory } from "meteor/dburles:factory"; -import { Packages } from "/lib/collections"; -import { getShopId } from "./shops"; - -/** - * @method getPkgData - * @memberof Fixtures - * @summary Get package data object, given a package name - * @example getPkgData("example-paymentmethod") ? getPkgData("example-paymentmethod")._id : "uiwneiwknekwewe" - * @param {String} pkgName name of package - * @returns {Object} Package object - */ -export const getPkgData = (pkgName) => { - const pkgData = Packages.findOne({ - name: pkgName - }); - return pkgData; -}; - -/** - * @name examplePaymentMethod - * @memberof Fixtures - * @summary Create a new fixture based off an example payment package method - * @example example = Factory.create("examplePaymentPackage"); - * @property {String} name - `"example-paymentmethod"` - * @property {String} icon - `"fa fa-credit-card-alt"` - * @property {String} shopId - `getShopId()` - * @property {Boolean} enabled - `true` - * @property {Object} settings - Object - * @property {Boolean} settings.mode - `false` - * @property {String} settings.apikey - `""` - * @property {Array} registry - `[]` - * @property {Object} layout - `null` - * @returns {undefined} - */ -export function examplePaymentMethod() { - const examplePaymentMethodPackage = { - name: "example-paymentmethod", - icon: "fa fa-credit-card-alt", - shopId: getShopId(), - enabled: true, - settings: { - mode: false, - apikey: "" - }, - registry: [], - layout: null - }; - - Factory.define("examplePaymentPackage", Packages, Object.assign({}, examplePaymentMethodPackage)); -} - -/** - * @name examplePackage - * @memberof Fixtures - * @summary Create a new fixture based off of the Packages collection. - * @since 1.5.5 - * @property {String} name `"example-package"` - * @property {Object} settings - * @property {Boolean} settings.enabled `false` - * @property {String} settings.apiUrl `http://example.com/api` - * @property {String} shopId `"random-shop-id"` - * @returns {undefined} - */ -export function examplePackage() { - const examplePkg = { - name: "example-package", - settings: { - enabled: false, - apiUrl: "http://example.com/api" - }, - shopId: "random-shop-101" - }; - - Factory.define("examplePackage", Packages, examplePkg); -} diff --git a/imports/plugins/core/core/server/fixtures/products.js b/imports/plugins/core/core/server/fixtures/products.js deleted file mode 100755 index c12a9429e8b..00000000000 --- a/imports/plugins/core/core/server/fixtures/products.js +++ /dev/null @@ -1,228 +0,0 @@ -import faker from "faker"; -import _ from "lodash"; -import { Factory } from "meteor/dburles:factory"; -import { Products, Tags } from "/lib/collections"; -import getSlug from "../Reaction/getSlug"; -import { getShop } from "./shops"; - -/** - * @method metaField - * @memberof Fixtures - * @param {Object} [options] - options object to override generated default values - * @param {String} [options.key] - metaField key - * @param {String} [options.value] - metaField value - * @param {String} [options.scope] - metaField scope - * @returns {Object} - randomly generated metaField - */ -export function metaField(options = {}) { - const defaults = { - key: faker.commerce.productAdjective(), - value: faker.commerce.productMaterial(), - scope: "detail" - }; - return _.defaults(options, defaults); -} - -/** - * @method productVariant - * @memberof Fixtures - * @param {Object} [options] - Options object - * @param {String} [options._id] - id - * @param {String} [options.parentId] - variant's parent's ID. Sets variant as child. - * @param {String} [options.compareAtPrice] - MSRP Price / Compare At Price - * @param {String} [options.weight] - productVariant weight - * @param {String} [options.price] - productVariant price - * @param {String} [options.title] - productVariant title - * @param {String} [options.optionTitle] - productVariant option title - * @param {String} [options.sku] - productVariant sku - * @param {Object[]} [options.metafields] - productVariant metaFields - * - * @returns {Object} - randomly generated productVariant - */ -export function productVariant(options = {}) { - const defaults = { - ancestors: [], - attributeLabel: "Variant", - compareAtPrice: _.random(0, 1000), - weight: _.random(0, 10), - isTaxable: faker.random.boolean(), - isVisible: true, - price: _.random(10, 1000), - title: faker.commerce.productName(), - optionTitle: faker.commerce.productName(), - shopId: getShop()._id, - sku: _.random(0, 6), - type: "variant", - metafields: [ - metaField(), - metaField({ - key: "facebook", - scope: "socialMessages" - }), - metaField({ - key: "twitter", - scope: "socialMessages" - }) - ] - }; - return _.defaults(options, defaults); -} - -/** - * @method addProduct - * @summary Create a product with variants - * @memberof Fixtures - * @param {Object} [options={}] [description] - * @param {String} [options._id] - id - * @param {String} [options.parentId] - variant's parent's ID. Sets variant as child. - * @param {String} [options.compareAtPrice] - MSRP Price / Compare At Price - * @param {String} [options.weight] - productVariant weight - * @param {String} [options.price] - productVariant price - * @param {String} [options.title] - productVariant title - * @param {String} [options.optionTitle] - productVariant option title - * @param {String} [options.sku] - productVariant sku - * @param {Object[]} [options.metafields] - productVariant metaFields - * @returns {Object} Product - */ -export function addProduct(options = {}) { - const product = Factory.create("product", options); - // top level variant - const variant = Factory.create("variant", Object.assign({}, productVariant(options), { ancestors: [product._id] })); - Factory.create("variant", Object.assign({}, productVariant(options), { ancestors: [product._id, variant._id] })); - Factory.create("variant", Object.assign({}, productVariant(options), { ancestors: [product._id, variant._id] })); - return product; -} - -/** - * @method addProductSingleVariant - * @summary Create a product with 1 variant - * @memberof Fixtures - * @param {Object} [options={}] Product variant options object - * @returns {Object} Product with Variant - */ -export function addProductSingleVariant() { - const product = Factory.create("product"); - // top level variant - const variant = Factory.create("variant", Object.assign({}, productVariant(), { ancestors: [product._id] })); - return { product, variant }; -} - -/** - * @method getProduct - * @summary Get a product - * @memberof Fixtures - * @param {Object} [options={}] Product variant options object - * @returns {Object} Product - */ -export function getProduct() { - const existingProduct = Products.findOne(); - return existingProduct || Factory.create("product"); -} - -/** - * @method getProducts - * @summary Get a number of products - * @memberof Fixtures - * @param {Object} [limit=2] Number of products - * @returns {Array} Array of products - */ -export function getProducts(limit = 2) { - const products = []; - const existingProducts = Products.find({}, { limit }).fetch(); - for (let inc = 0; inc < limit; inc += 1) { - const product = existingProducts[inc] || Factory.create("product"); - products.push(product); - } - return products; -} - -/** - * @returns {undefined} undefined - */ -export default function () { - /** - * @name tag - * @memberof Fixtures - * @example Factory.create("tag") - * @summary Define a Tag for Products - * @property {String} name - `"Tag"` - * @property {String} slug - `"tag"` - * @property {Number} position - `_.random(0, 100000)` - * @property {Boolean} isVisible - `true` - * @property {Boolean} isTopLevel - `true` - * @property {String} shopId - `getShop()._id` - * @property {Date} createdAt - `faker.date.past()` - * @property {Date} updatedAt - `new Date()` - */ - Factory.define("tag", Tags, { - name: "Tag", - slug: "tag", - position: _.random(0, 100000), - // relatedTagIds: [], - isVisible: true, - isTopLevel: true, - shopId: getShop()._id, - createdAt: faker.date.past(), - updatedAt: new Date() - }); - - /** - * @name Product - * @memberof Fixtures - * @example const product = Factory.create("product") - * @example Factory.create("variant", Object.assign({}, productVariant(options), { ancestors: [product._id, variant._id] })); - * @summary Define a factory for Product - * @property {Array} ancestors `[]` - * @property {String} shopId `getShop()._id` - * @property {String} title `faker.commerce.productName()` - * @property {String} pageTitle `faker.lorem.sentence()` - * @property {String} description `faker.lorem.paragraph()` - * @property {String} type `"simple"` or `"variant"` for Product Variant - * @property {String} vendor `faker.company.companyName()` - * @property {Object} price `priceRange` - * @property {String} price.range `"1.00 - 12.99"` - * @property {Number} price.min `1.00` - * @property {Number} price.max `12.9` - * @property {Array} metafields `[]` - * @property {String[]} supportedFulfillmentTypes - ["shipping"] - * @property {Array} hashtags `[]` - * @property {Boolean} isVisible `true` - * @property {Date} publishedAt `new Date()` - * @property {Date} createdAt `new Date()` - * @property {Date} updatedAt `new Date()` - */ - const base = { - ancestors: [], - shopId: () => getShop()._id - }; - - const priceRange = { - range: "1.00 - 12.99", - min: 1.00, - max: 12.99 - }; - - const productTitle = faker.commerce.productName(); - - const product = { - title: productTitle, - pageTitle: faker.lorem.sentence(), - description: faker.lorem.paragraph(), - handle: getSlug(productTitle), - type: "simple", - vendor: faker.company.companyName(), - price: priceRange, - metafields: [], - supportedFulfillmentTypes: ["shipping"], - hashtags: [], - isVisible: true, - publishedAt: new Date(), - createdAt: new Date(), - updatedAt: new Date() - }; - - Factory.define("product", Products, Object.assign({}, base, product)); - Factory.define("variant", Products, { - type: "variant" - }); -} diff --git a/imports/plugins/core/core/server/fixtures/shops.js b/imports/plugins/core/core/server/fixtures/shops.js deleted file mode 100755 index d3dd06c373c..00000000000 --- a/imports/plugins/core/core/server/fixtures/shops.js +++ /dev/null @@ -1,326 +0,0 @@ -import faker from "faker"; -import _ from "lodash"; -import Random from "@reactioncommerce/random"; -import { Factory } from "meteor/dburles:factory"; -import { Shops } from "/lib/collections"; - -/** - * @method getShop - * @memberof Fixtures - * @summary Get an existing shop or create a shop factory - * @returns {Object} Shop - */ -export function getShop() { - createShopFactory(); - const existingShop = Shops.findOne(); - return existingShop || Factory.create("shop"); -} - -/** - * @method getShopId - * @memberof Fixtures - * @summary Get the first shop found and return the shop id - * @returns {String} Shop ID - */ -export function getShopId() { - const shop = Shops.find({}).fetch()[0]; - return shop && shop._id; -} - -/** - * @method getAddress - * @memberof Fixtures - * @summary Get an address, supplying options (optional) - * @param {Object} [options={}] Address options, optional - * @param {String} [options.fullName] fullName - `faker.name.findName()` - * @param {String} [options.address1] address1 - `faker.address.streetAddress()` - * @param {String} [options.address2] address2 - `faker.address.secondaryAddress()` - * @param {String} [options.city] city - `faker.address.city()` - * @param {String} [options.company] company - `faker.company.companyName()` - * @param {String} [options.phone] phone - `faker.phone.phoneNumber()` - * @param {String} [options.region] region - `faker.address.stateAbbr()` - * @param {String} [options.postal] postal - `faker.address.zipCode()` - * @param {String} [options.country] country - `faker.address.countryCode()` - * @param {String} [options.isCommercial] isCommercial - `faker.random.boolean()` - * @param {Boolean} [options.isShippingDefault] isShippingDefault - `faker.random.boolean()` - * @param {Boolean} [options.isBillingDefault] isBillingDefault - `faker.random.boolean()` - * @param {Array} [options.metafields] metafields - `[]` - * @returns {Object} Address object - */ -export function getAddress(options = {}) { - const defaults = { - fullName: faker.name.findName(), - address1: faker.address.streetAddress(), - address2: faker.address.secondaryAddress(), - city: faker.address.city(), - company: faker.company.companyName(), - phone: faker.phone.phoneNumber(), - region: faker.address.stateAbbr(), - postal: faker.address.zipCode(), - country: faker.address.countryCode(), - isCommercial: faker.random.boolean(), - isShippingDefault: faker.random.boolean(), - isBillingDefault: faker.random.boolean(), - metafields: [] - }; - return _.defaults(options, defaults); -} - -const shop = { - name: () => faker.internet.domainName(), - description: faker.company.catchPhrase(), - keywords: faker.company.bsAdjective(), - addressBook: [getAddress()], - domains: ["localhost"], - emails: [ - { - address: faker.internet.email(), - verified: faker.random.boolean() - } - ], - currency: "USD", // could use faker.finance.currencyCode() - currencies: { - USD: { - format: "%s%v", - symbol: "$" - }, - EUR: { - format: "%v %s", - symbol: "€", - decimal: ",", - thousand: "." - } - }, - locale: "en", - locales: { - continents: { - NA: "North America" - }, - countries: { - US: { - name: "United States", - native: "United States", - phone: "1", - continent: "NA", - capital: "Washington D.C.", - currency: "USD,USN,USS", - languages: "en" - } - } - }, - baseUOL: "in", - unitsOfLength: [{ - uol: "in", - label: "Inches", - default: true - }, { - uol: "cm", - label: "Centimeters" - }, { - uol: "ft", - label: "Feet" - }], - baseUOM: "oz", - unitsOfMeasure: [{ - uom: "oz", - label: "Ounces", - default: true - }, { - uom: "lb", - label: "Pounds" - }, { - uom: "g", - label: "Grams" - }, { - uom: "kg", - label: "Kilograms" - }], - defaultParcelSize: { - weight: () => faker.random.number(), - length: () => faker.random.number(), - width: () => faker.random.number(), - height: () => faker.random.number() - }, - layout: [{ - layout: "coreLayout", - workflow: "coreLayout", - theme: "default", - enabled: true - }, { - layout: "coreLayout", - workflow: "coreCartWorkflow", - collection: "Cart", - theme: "default", - enabled: true - }, { - layout: "coreLayout", - workflow: "coreOrderWorkflow", - collection: "Orders", - theme: "default", - enabled: true - }, { - layout: "coreLayout", - workflow: "coreOrderShipmentWorkflow", - collection: "Orders", - theme: "default", - enabled: true - }], - workflow: { - status: "new" - }, - public: true, - brandAssets: [ - { - mediaId: "J8Bhq3uTtdgwZx3rz", - type: "navbarBrandImage" - } - ], - timezone: "US/Pacific", - metafields: [], - shopType: "primary", - createdAt: new Date(), - updatedAt: new Date() -}; - -const activeShop = { - workflow: { - status: "active" - }, - _id: Random.id() -}; - -/** - * @method createActiveShop - * @memberof Fixtures - * @summary Find and return an existing shop from option parameters, or create an active shop factory - * @param {Object} [options={}] Any shop properties - * @returns {Object} Shop, with active status - */ -export function createActiveShop(options = {}) { - const existingActiveShop = Shops.findOne({ "workflow.status": "active", ...options }); - - // If we found an existingActiveShop, return it - if (existingActiveShop) { - return existingActiveShop; - } - // Otherwise, we need to create a new shop from the factory - - // Setup the activeShop factory definition - createActiveShopFactory(); - - // Create a new shop from the factory with the provided options - return Factory.create("activeShop", options); -} - -/** - * @method createShopFactory - * @memberof Fixtures - * @summary Create Shop factory. Shop name should be unique for the slug to be unique. - * @property {String} name - `faker.internet.domainName()` - * @property {String} description - `faker.company.catchPhrase()` - * @property {String} keywords - `faker.company.bsAdjective()` - * @property {Array} addressBook - `[getAddress()]` - * @property {Array} domains - `["localhost"]` - * @property {Array} emails - `[]` - * @property {String} emails.address - `faker.internet.email()` - * @property {Boolean} emails.verified - `faker.random.boolean()` - * @property {String} currency - `"USD"` - Could use faker.finance.currencyCode() - * @property {Object} currencies - `{}` - * @property {Object} currencies.USD - `{}` - * @property {String} currencies.USD.format - `"%s%v"` - * @property {String} currencies.USD.symbol - `"$"` - * @property {Object} currencies.EUR - `{}` - * @property {String} currencies.EUR.format - `"%v %s"` - * @property {String} currencies.EUR.symbol - `"€"` - * @property {String} currencies.EUR.decimal - `","` - * @property {String} currencies.EUR.thousand - `"."` - * @property {String} locale - `"en"` - * @property {Object} locales - `{}` - * @property {Object} locales.continents - `{}` - * @property {String} locales.continents.NA - `"North America"` - * @property {Object} locales.countries - `{}` - * @property {Object} locales.countries.US - `{}` - * @property {String} locales.countries.name - `"United States"` - * @property {String} locales.countries.native - `"United States"` - * @property {String} locales.countries.phone - `"1"` - * @property {String} locales.countries.continent - `"NA"` - * @property {String} locales.countries.capital - `"Washington D.C."` - * @property {String} locales.countries.currency - `"USD,USN,USS"` - * @property {String} locales.countries.languages - `"en"` - * @property {String} baseUOL - `"in"` - * @property {Array} unitsOfLength - `[{}]` - * @property {String} unitsOfLength.uol - `"in"` - * @property {String} unitsOfLength.label - `"Inches"` - * @property {String} unitsOfLength.default - `true` - * @property {String} unitsOfLength.uol - `"cm"` - * @property {String} unitsOfLength.label - `"Centimeters"` - * @property {String} unitsOfLength.uol - `"ft"` - * @property {String} unitsOfLength.label - `"Feet"` - * @property {String} baseUOM - `"oz"` - * @property {Array} unitsOfMeasure - `[{}]` - * @property {String} unitsOfMeasure.uom - `"oz"` - * @property {String} unitsOfMeasure.label - `"Ounces"` - * @property {String} unitsOfMeasure.default - `true` - * @property {String} unitsOfMeasure.uom - `"lb"` - * @property {String} unitsOfMeasure.label - `"Pounds"` - * @property {String} unitsOfMeasure.uom - `"g"` - * @property {String} unitsOfMeasure.label - `"Grams"` - * @property {String} unitsOfMeasure.uom - `"kg"` - * @property {String} unitsOfMeasure.label - `"Kilograms"` - * @property {Array} layout - `[{}]` - * @property {String} layout - `"coreLayout"` - * @property {String} workflow - `"coreLayout"` - * @property {String} theme - `"default"` - * @property {Boolean} enabled - `true` - * @property {String} layout - `"coreLayout"` - * @property {String} workflow - `"coreCartWorkflow"` - * @property {String} collection - `"Cart"` - * @property {String} theme - `"default"` - * @property {Boolean} enabled - `true` - * @property {String} layout - `"coreLayout"` - * @property {String} workflow - `"coreOrderWorkflow"` - * @property {String} collection - `"Orders"` - * @property {String} theme - `"default"` - * @property {Boolean} enabled - `true` - * @property {String} layout - `"coreLayout"` - * @property {String} workflow - `"coreOrderShipmentWorkflow"` - * @property {String} collection - `"Orders"` - * @property {String} theme - `"default"` - * @property {Boolean} enabled - `true` - * @property {Object} workflow - `{}` - * @property {String} workflow.status - `"active"` - * @property {Boolean} public - `true` - * @property {Array} brandAssets - `[]` - * @property {String} mediaId - `"J8Bhq3uTtdgwZx3rz"` - * @property {String} type - `"navbarBrandImage"` - * @property {String} timezone - `"US/Pacific"` - * @property {Array} metafields - `[]` - * @property {String} shopType - `"primary"` - Not having a primary shop will cause test failures. one shop in the marketplace is required as default shop. This is used to control marketplace settings. - * @property {Date} createdAt - `new Date()` - * @property {Date} updatedAt - `new Date()` - * @returns {Object} Shop with status `"active"` - */ -export function createShopFactory() { - Factory.define("shop", Shops, shop); -} - -/** - * @name createActiveShopFactory - * @memberof Fixtures - * @summary Returns an active shop factory - * @property {Object} workflow - * @property {String} status - `"active"` - * @property {String} id - `Random.id()` - * @returns {Object} Shop with status `"active"` - */ -export function createActiveShopFactory() { - Factory.define("activeShop", Shops, Object.assign({}, shop, activeShop)); -} - -/** - * @returns {undefined} - */ -export default function () { - createShopFactory(); - createActiveShopFactory(); -} diff --git a/imports/plugins/core/core/server/fixtures/users.js b/imports/plugins/core/core/server/fixtures/users.js deleted file mode 100755 index 4eea34856b6..00000000000 --- a/imports/plugins/core/core/server/fixtures/users.js +++ /dev/null @@ -1,164 +0,0 @@ -import faker from "faker"; -import _ from "lodash"; -import Random from "@reactioncommerce/random"; -import { Meteor } from "meteor/meteor"; -import { Factory } from "meteor/dburles:factory"; -import { getShop } from "./shops"; - -/** - * @method getUser - * @memberof Fixtures - * @returns {Object} Existing user or Factory user - */ -export function getUser() { - const existingUser = Meteor.users.findOne(); - return existingUser || Factory.create("user"); -} - -/** - * @method getUsers - * @memberof Fixtures - * @param {Number} limit Default set to 2 - * @returns {Array} Array of existing users or Factory user - */ -export function getUsers(limit = 2) { - const users = []; - const existingUsers = Meteor.users.find({}, { limit }).fetch(); - for (let inc = 0; inc < limit; inc += 1) { - const user = existingUsers[inc] || Factory.create("user"); - users.push(user); - } - return users; -} - -/** - * @name user - * @memberof Fixtures - * @summary Define user Factory - * @example const user1 = Factory.create("user"); - * @description Types of User factories - * - `user` - A user - * - `registeredUser` - A user with a password, loginTokens and roles: `account/profile, guest, product, tag, index, cart/completed` - * - `anonymous` - A user without an account with rules: `guest, anonymous, product, tag, index, cart/completed` - * @property {String} username - `faker.internet.userName() + _.random(0, 1000)` - * @property {String} name - `faker.name.findName()` - * @property {Array} emails - `[{address: faker.internet.email(), verified: true}]` - * @property {Object} profile - `{ - name: this.name, - email: faker.internet.email(), - profilePictureUrl: faker.image.imageUrl() - }` - * @property {String} gender - String: `"Male", "Female", "Either"` - * @property {String} description - `faker.lorem.paragraphs(3)` - * @property {Date} startTime - `calculatedStartTime` - * @property {Date} createdAt - `new Date()` - * @property {Object} roles - `{shopId: ["guest", "anonymous", "product"]}` - */ -const user = { - username() { - return faker.internet.userName() + _.random(0, 1000); - }, - - name() { - return faker.name.findName(); - }, - - emails() { - const email = faker.internet.email(); - return [{ - address: email, - verified: true - }]; - }, - - profile() { - return { - name: this.name, - email: faker.internet.email(), - profilePictureUrl: faker.image.imageUrl() - }; - }, - - gender() { - return ["Either", "Male", "Female"][_.random(0, 2)]; - }, - - description() { - return faker.lorem.paragraphs(3); - }, - - startTime() { - const numDaysToAdd = Math.floor(Math.random() * 32); // random number of days between 0 and 31 - const numHoursToAdd = Math.floor(Math.random() * 25); // random number of hours between 0 and 24 - const secondsInDay = 24 * 60 * 60 * 1000; - const secondsInHour = 24 * 60 * 60 * 1000; - - const calculatedStartTime = Date.now() + (numDaysToAdd * secondsInDay) + (numHoursToAdd + secondsInHour); - - return new Date(calculatedStartTime); - }, - - createdAt: new Date() -}; - -/** - * @summary Users factory setup - * @returns {undefined} - */ -export default function () { - const numDaysToAdd = Math.floor(Math.random() * 32); // random number of days between 0 and 31 - const numHoursToAdd = Math.floor(Math.random() * 25); // random number of hours between 0 and 24 - const secondsInDay = 24 * 60 * 60 * 1000; - const secondsInHour = 24 * 60 * 60 * 1000; - - const timeOffset = Date.now() + (numDaysToAdd * secondsInDay) + (numHoursToAdd + secondsInHour); - - const shop = getShop(); - - const registered = { - roles: { - [shop._id]: [ - "account/profile", - "guest", - "product", - "tag", - "index", - "cart/completed" - ] - }, - services: { - password: { - bcrypt: Random.id(29) - }, - resume: { - loginTokens: [ - { - when: timeOffset - } - ] - } - } - }; - - - Factory.define("user", Meteor.users, user); - Factory.define( - "registeredUser", Meteor.users, - Object.assign({}, user, registered) - ); - - const anonymous = { - roles: { - [shop._id]: [ - "guest", - "anonymous", - "product", - "tag", - "index", - "cart/completed" - ] - } - }; - - Factory.define("anonymous", Meteor.users, Object.assign({}, user, anonymous)); -} From 8951c4f096b6690e44935c8978b02754435e04b9 Mon Sep 17 00:00:00 2001 From: Erik Kieckhafer Date: Mon, 16 Sep 2019 09:26:31 -0700 Subject: [PATCH 2/8] chore: remove meteor-app-tests Signed-off-by: Erik Kieckhafer --- .../meteor-app-tests/absoluteUrl.app-test.js | 98 ----------- .../accounts-validation.app-test.js | 120 ------------- imports/meteor-app-tests/accounts.app-test.js | 65 ------- imports/meteor-app-tests/core.app-test.js | 161 ------------------ .../generate-sitemaps.app-test.js | 132 -------------- .../get-sitemap-xml.app-test.js | 37 ---- .../members-publications.app-test.js | 84 --------- imports/meteor-app-tests/methods.app-test.js | 98 ----------- .../packages-update.app-test.js | 78 --------- imports/meteor-app-tests/shops.app-test.js | 139 --------------- imports/meteor-app-tests/tags.app-test.js | 86 ---------- 11 files changed, 1098 deletions(-) delete mode 100644 imports/meteor-app-tests/absoluteUrl.app-test.js delete mode 100644 imports/meteor-app-tests/accounts-validation.app-test.js delete mode 100644 imports/meteor-app-tests/accounts.app-test.js delete mode 100644 imports/meteor-app-tests/core.app-test.js delete mode 100644 imports/meteor-app-tests/generate-sitemaps.app-test.js delete mode 100644 imports/meteor-app-tests/get-sitemap-xml.app-test.js delete mode 100644 imports/meteor-app-tests/members-publications.app-test.js delete mode 100644 imports/meteor-app-tests/methods.app-test.js delete mode 100644 imports/meteor-app-tests/packages-update.app-test.js delete mode 100644 imports/meteor-app-tests/shops.app-test.js delete mode 100644 imports/meteor-app-tests/tags.app-test.js diff --git a/imports/meteor-app-tests/absoluteUrl.app-test.js b/imports/meteor-app-tests/absoluteUrl.app-test.js deleted file mode 100644 index b25f9286bf2..00000000000 --- a/imports/meteor-app-tests/absoluteUrl.app-test.js +++ /dev/null @@ -1,98 +0,0 @@ -import { DDP } from "meteor/ddp-client"; - -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; - -import { composeUrl } from "/lib/core/url-common"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; - -/** - * @returns {String} A random string - */ -function randomString() { - return Math.random().toString(36); -} - -describe("AbsoluteUrlMixin", () => { - let sandbox; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - beforeEach(() => { - sandbox = sinon.sandbox.create(); - }); - - afterEach(() => { - sandbox.restore(); - }); - - describe("#absoluteUrl", () => { - let path; - let connectionHost; - let rootUrl; - let meteorRootUrl; - - beforeEach(() => { - // commonly used test vars - path = randomString(); - connectionHost = `${randomString()}.reactioncommerce.com`; - rootUrl = `https://${randomString()}.reactioncommerce.com`; - - // mocking Meteor - meteorRootUrl = composeUrl.defaultOptions.rootUrl; - // this is a round-about way of mocking $ROOT_URL - composeUrl.defaultOptions.rootUrl = rootUrl; - }); - - afterEach(() => { - // restore Meteor - composeUrl.defaultOptions.rootUrl = meteorRootUrl; - }); - - describe("outside of a connection", () => { - it("defaults to $ROOT_URL", () => { - expect(Reaction.absoluteUrl()).to.include(rootUrl); - }); - }); - - describe("within a connection", () => { - beforeEach(() => { - // for reference: https://github.com/meteor/meteor/blob/ed98a07125cd072552482ca2244239f034857814/packages/ddp-server/livedata_server.js#L279-L295 - sinon.stub(DDP._CurrentMethodInvocation, "get").returns({ - connection: { httpHeaders: { host: connectionHost } } - }); - }); - - afterEach(() => { - DDP._CurrentMethodInvocation.get.restore(); - }); - - it("uses the current connection's host", () => { - expect(Reaction.absoluteUrl()).to.include(connectionHost); - }); - - it("uses $ROOT_URL's protocol/scheme", () => { - // this would he http:// if $ROOT_URL had not used https:// - expect(Reaction.absoluteUrl()).to.startsWith("https://"); - }); - }); - - it("accepts options the same way composeUrl does", () => { - const options = { - secure: true, - replaceLocalhost: true, - rootUrl: "http://127.0.0.1" - }; - - const reactionVersion = Reaction.absoluteUrl(path, options); - const meteorVersion = composeUrl(path, options); - - expect(reactionVersion).to.equal(meteorVersion); - }); - }); -}); diff --git a/imports/meteor-app-tests/accounts-validation.app-test.js b/imports/meteor-app-tests/accounts-validation.app-test.js deleted file mode 100644 index 7e10595adfb..00000000000 --- a/imports/meteor-app-tests/accounts-validation.app-test.js +++ /dev/null @@ -1,120 +0,0 @@ -/* eslint prefer-arrow-callback:0 */ -import { Meteor } from "meteor/meteor"; -import { expect } from "meteor/practicalmeteor:chai"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; - -// These are client-side only function (???) so they cannot be test from here -describe("Account Registration Validation ", function () { - before(function (done) { - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - describe("username validation ", function () { - it("should not allow a invalid username of length 3", function (done) { - const username = "tn"; - Meteor.call("accounts/validation/username", username, function (error, result) { - expect(error).to.be.undefined; - expect(result).to.be.an("object"); - return done(); - }); - }); - - it("should allow a username of valid length", function (done) { - const username = "tenten"; - Meteor.call("accounts/validation/username", username, function (error, result) { - expect(error).to.be.undefined; - expect(result).to.be.true; - return done(); - }); - }); - }); - - describe("email address validation ", function () { - it("should not allow an invalid email address", function (done) { - this.timeout(4000); - const email = "emailwebsite.com"; - Meteor.call("accounts/validation/email", email, false, function (error, result) { - expect(result).to.be.an("object"); - return done(); - }); - }); - - it("should allow a valid email address", function (done) { - const email = "email@website.com"; - Meteor.call("accounts/validation/email", email, false, function (error, result) { - expect(result).to.be.true; - return done(); - }); - }); - - it("should allow a valid, supplied, optional email address", function (done) { - const email = "email@website.com"; - Meteor.call("accounts/validation/email", email, true, function (error, result) { - expect(result).to.be.true; - return done(); - }); - }); - - it("should not allow an invalid, supplied, optional email address", function (done) { - const email = "emailwebsite.com"; - Meteor.call("accounts/validation/email", email, true, function (error, result) { - expect(result).to.be.an("object"); - return done(); - }); - }); - }); - - describe("password validation", function () { - it("should not allow a password under 6 characters in length", function (done) { - const password = "abc12"; - Meteor.call("accounts/validation/password", password, undefined, function (error, result) { - expect(result).to.be.an("array"); - const errMessage = result[0]; - expect(errMessage).to.be.an("object"); - expect(errMessage.reason).to.contain("at least 6 characters"); - return done(); - }); - }); - - it("should allow a password of exactly 6 characters in length", function (done) { - const password = "abc123"; - Meteor.call("accounts/validation/password", password, undefined, function (error, result) { - expect(result).to.be.true; - return done(); - }); - }); - - it("should allow a password of 6 characters or more in length", function (done) { - const password = "abc1234"; - Meteor.call("accounts/validation/password", password, undefined, function (error, result) { - expect(result).to.be.true; - return done(); - }); - }); - - it("should allow a password of 6 characters or more in length with only uppercase characters", function (done) { - const password = "ABC1234"; - Meteor.call("accounts/validation/password", password, undefined, function (error, result) { - expect(result).to.be.true; - return done(); - }); - }); - - it("should allow a password of 6 characters or more in length uppercase and lower characters", function (done) { - const password = "abcABC1234"; - Meteor.call("accounts/validation/password", password, undefined, function (error, result) { - expect(result).to.be.true; - return done(); - }); - }); - it("should allow a password of 6 characters or more in length uppercase, lower, and symbol characters", function (done) { - const password = "abcABC1234@#$%^"; - Meteor.call("accounts/validation/password", password, undefined, function (error, result) { - expect(result).to.be.true; - return done(); - }); - }); - }); -}); diff --git a/imports/meteor-app-tests/accounts.app-test.js b/imports/meteor-app-tests/accounts.app-test.js deleted file mode 100644 index 5725339a95d..00000000000 --- a/imports/meteor-app-tests/accounts.app-test.js +++ /dev/null @@ -1,65 +0,0 @@ -/* eslint-disable require-jsdoc */ -/* eslint dot-notation: 0 */ -/* eslint prefer-arrow-callback:0 */ -import { Meteor } from "meteor/meteor"; -import { Factory } from "meteor/dburles:factory"; -import { check, Match } from "meteor/check"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import { Accounts, Packages, Orders, Products, Shops, Cart } from "/lib/collections"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import { getShop } from "/imports/plugins/core/core/server/fixtures/shops"; -import Fixtures from "/imports/plugins/core/core/server/fixtures"; - -describe("Account Meteor method ", function () { - let shopId; - let fakeUser; - const originals = {}; - let sandbox; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - Fixtures(); - done(); - }); - }); - - after(() => { - Packages.remove({}); - Cart.remove({}); - Accounts.remove({}); - Orders.remove({}); - Products.remove({}); - Shops.remove({}); - if (sandbox) { - sandbox.restore(); - } - }); - - beforeEach(function () { - shopId = getShop()._id; - sandbox = sinon.sandbox.create(); - - fakeUser = Factory.create("user"); - const userId = fakeUser._id; - // set the _id... some code requires that Account#_id === Account#userId - sandbox.stub(Meteor, "user", () => fakeUser); - sandbox.stub(Meteor.users, "findOne", () => fakeUser); - sandbox.stub(Reaction, "getUserId", () => userId); - sandbox.stub(Reaction, "getShopId", () => shopId); - - Object.keys(originals).forEach((method) => spyOnMethod(method, userId)); - }); - - afterEach(function () { - sandbox.restore(); - }); - - function spyOnMethod(method, id) { - return sandbox.stub(Meteor.server.method_handlers, `cart/${method}`, function (...args) { - check(args, [Match.Any]); // to prevent audit_arguments from complaining - this.userId = id; // having to do this makes me think that we should be using Meteor.userId() instead of this.userId in our Meteor methods - return originals[method].apply(this, args); - }); - } -}); diff --git a/imports/meteor-app-tests/core.app-test.js b/imports/meteor-app-tests/core.app-test.js deleted file mode 100644 index 920aa784198..00000000000 --- a/imports/meteor-app-tests/core.app-test.js +++ /dev/null @@ -1,161 +0,0 @@ -import { Meteor } from "meteor/meteor"; - -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import { Shops } from "/lib/collections"; - -import Logger from "@reactioncommerce/logger"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import ConnectionDataStore from "/imports/plugins/core/core/server/util/connectionDataStore"; - -/** - * @returns {String} A random string - */ -function randomString() { - return Math.random().toString(36); -} - -describe("Server/API/Core", () => { - let sandbox; - let shop; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - beforeEach(() => { - sandbox = sinon.sandbox.create(); - shop = { _id: randomString() }; - }); - - afterEach(() => { - sandbox.restore(); - shop = undefined; - }); - - describe("#getPrimaryShop", () => { - it("returns the shop tagged as primary", () => { - sandbox.stub(Shops, "findOne") - .withArgs({ shopType: "primary" }) - .returns(shop); - - expect(Reaction.getPrimaryShop()).to.be.equal(shop); - }); - }); - - describe("#getShopId", () => { - afterEach(() => { - Reaction.resetShopId(); - }); - - it("returns the cached value if applicable", () => { - sandbox.stub(ConnectionDataStore, "get") - .withArgs("shopId") - .returns(shop._id); - - expect(Reaction.getShopId()).to.equal(shop._id); - }); - - it("fetches a user's preferred shop", () => { - const userId = randomString(); - - sandbox.stub(Meteor, "userId").returns(userId); - - const fnGetUserShopId = - sandbox.stub(Reaction, "getUserShopId").withArgs(userId).returns(shop._id); - - expect(Reaction.getShopId()).to.equal(shop._id); - expect(fnGetUserShopId.called).to.be.true; - }); - - it("gets the shop by domain", () => { - const fnGetShopIdByDomain = - sandbox.stub(Reaction, "getShopIdByDomain").returns(shop._id); - - sandbox.stub(Meteor, "userId").returns(null); - - expect(Reaction.getShopId()).to.equal(shop._id); - expect(fnGetShopIdByDomain.called).to.be.true; - }); - - it("defaults to the Primary Shop", () => { - const primaryShopId = randomString(); - const fnGetPrimaryShopId = - sandbox.stub(Reaction, "getPrimaryShopId").returns(primaryShopId); - const fnLogger = - sandbox.stub(Logger, "warn").withArgs(sinon.match(/No shop matching/)); - sandbox.stub(Meteor, "userId").returns(null); - sandbox.stub(Reaction, "getShopIdByDomain").returns(null); - - expect(Reaction.getShopId()).to.equal(primaryShopId); - expect(fnGetPrimaryShopId.called).to.be.true; - expect(fnLogger.called).to.be.true; - }); - - it("caches the shopId for subsequent calls", () => { - const fnSetCachedData = sandbox.stub(ConnectionDataStore, "set").withArgs("shopId", shop._id); - - sandbox.stub(Meteor, "userId").returns(null); - sandbox.stub(Reaction, "getShopIdByDomain").returns(shop._id); - - Reaction.getShopId(); - - expect(fnSetCachedData.called).to.be.true; - }); - }); - - describe("#resetShopId", () => { - it("clears shopId from cache", () => { - const fnCacheClear = - sandbox.spy(ConnectionDataStore, "clear").withArgs("shopId"); - - Reaction.resetShopId(); - - expect(fnCacheClear.called).to.be.true; - }); - }); - - describe("#getShopIdByDomain", () => { - it("gets the shop with the domain attribute which includes the current domain", () => { - const domain = `${randomString()}.reactioncommerce.com`; - const shopsCursor = { - fetch: () => [shop] - }; - - sandbox.stub(Reaction, "getDomain").returns(domain); - - sandbox.stub(Shops, "find") - .withArgs({ domains: domain }, sinon.match.any) - .returns(shopsCursor); - - expect(Reaction.getShopIdByDomain()).to.equal(shop._id); - }); - }); - - describe("#isShopPrimary", () => { - let primaryShopId; - - beforeEach(() => { - primaryShopId = randomString(); - }); - - it("is true when the current shop is the Primary Shop", () => { - sandbox.stub(Reaction, "getShopId", () => primaryShopId); - sandbox.stub(Reaction, "getPrimaryShopId", () => primaryShopId); - - expect(Reaction.isShopPrimary()).to.be.true; - }); - - it("is false when the current shop is a Merchant Shop", () => { - const shopId = `xxx${primaryShopId}xxx`; - - sandbox.stub(Reaction, "getShopId", () => shopId); - sandbox.stub(Reaction, "getPrimaryShopId", () => primaryShopId); - - expect(Reaction.isShopPrimary()).to.be.false; - }); - }); -}); diff --git a/imports/meteor-app-tests/generate-sitemaps.app-test.js b/imports/meteor-app-tests/generate-sitemaps.app-test.js deleted file mode 100644 index 21aabe6314c..00000000000 --- a/imports/meteor-app-tests/generate-sitemaps.app-test.js +++ /dev/null @@ -1,132 +0,0 @@ -import { Meteor } from "meteor/meteor"; -import { expect } from "meteor/practicalmeteor:chai"; -import { Factory } from "meteor/dburles:factory"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import { Products, Shops, Tags } from "/lib/collections"; -import { Sitemaps } from "/imports/plugins/included/sitemap-generator/lib/collections/sitemaps"; -import generateSitemaps from "/imports/plugins/included/sitemap-generator/server/lib/generate-sitemaps"; - -describe("generateSitemaps", () => { - let sandbox; - let primaryShop; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - beforeEach(function () { - this.timeout(30000); - sandbox = sinon.sandbox.create(); - primaryShop = Factory.create("shop"); - sandbox.stub(Reaction, "getPrimaryShopId", () => primaryShop._id); - }); - - afterEach(() => { - const { _id: shopId } = primaryShop; - Shops.remove({ _id: shopId }); - Sitemaps.remove({ shopId }); - Products.remove({ shopId }); - Tags.remove({ shopId }); - sandbox.restore(); - }); - - it("should throw not-found error if invalid shopId is passed", () => { - expect(() => generateSitemaps({ shopIds: ["FAKE_SHOP_ID"] })).to.throw(Meteor.Error, /not-found/); - }); - - it("should generate the correct number of sitemap documents", () => { - const { _id: shopId } = primaryShop; - - // Create a visible tag and product for our primary shop - Factory.create("tag", { shopId, slug: "slug1" }); - Factory.create("product", { shopId }); - - generateSitemaps({ urlsPerSitemap: 1 }); // 1 URL per sitemap - - /** - * At this point, we should have the following sitemaps: - * sitemap.xml - * sitemap-pages-1.xml - * sitemap-products-1.xml - * sitemaps-tags-1.xml - */ - - const sitemapsCount = Sitemaps.find({ shopId }).count(); - expect(sitemapsCount).to.equal(4); - }); - - it("should create sitemaps for primary shop if no shop _id is given", () => { - const { _id: shopId } = primaryShop; - - Sitemaps.remove({}); - - Factory.create("product", { shopId }); - - generateSitemaps({ urlsPerSitemap: 1 }); // 1 URL per sitemap - - const sitemap = Sitemaps.findOne({}); - expect(sitemap).to.be.an("object"); - expect(sitemap.shopId).to.equal(shopId); - }); - - it("should not include deleted/non-visible products in sitemaps", () => { - const { _id: shopId } = primaryShop; - - const tag1 = Factory.create("tag", { shopId, slug: "slug2" }); - Factory.create("product", { shopId, hashtags: [tag1._id] }); - - // Create a deleted/non-visible tag and product - const tag2 = Factory.create("tag", { shopId, isVisible: false, isDeleted: true, slug: "slug3" }); - Factory.create("product", { shopId, hashtags: [tag2._id], isVisible: false, isDeleted: true }); - - generateSitemaps({ urlsPerSitemap: 1 }); // 1 URL per sitemap - - const sitemapsCount = Sitemaps.find({ shopId }).count(); - expect(sitemapsCount).to.equal(4); - }); - - it("should create sitemaps with the correct number of URLs per each", () => { - const { _id: shopId } = primaryShop; - const shopFields = { shopId }; - - // Create 4 visible products - for (let inc = 0; inc < 4; inc += 1) { - Factory.create("product", shopFields); - } - - // Create 4 visible tags - for (let inc = 0; inc < 4; inc += 1) { - Factory.create("tag", { ...shopFields, slug: `tag${inc}` }); - } - - generateSitemaps({ urlsPerSitemap: 2 }); // 2 URLs per sitemap - - /** - * @name expectLocTagCount - * @summary Loads a sitemap's XML by handle for current primary shop, and confirms # of tags is as expected - * @private - * @param {String} handle - Sitemaps handle - * @param {Number} count - Expected count of tags in sitemap's XML - * @returns {undefined} - */ - const expectLocTagCount = (handle, count) => { - const sitemapProducts1 = Sitemaps.findOne({ shopId, handle: "sitemap-products-1.xml" }); - expect(sitemapProducts1).to.be.an("object"); - const { xml } = sitemapProducts1; - expect(xml).to.be.a("string"); - const locTagCount = (xml.match(//g) || []).length; - expect(locTagCount).to.equal(count); - }; - - // Should be 2 product sitemaps - sitemap-products-1.xml, sitemap-products-2.xml - // Each should have 2 entries (sitemap location XML tags) - expectLocTagCount("sitemap-products-1.xml", 2); - expectLocTagCount("sitemap-products-2.xml", 2); - expectLocTagCount("sitemap-tags-1.xml", 2); - expectLocTagCount("sitemap-tags-2.xml", 2); - }); -}); diff --git a/imports/meteor-app-tests/get-sitemap-xml.app-test.js b/imports/meteor-app-tests/get-sitemap-xml.app-test.js deleted file mode 100644 index acce34aae4c..00000000000 --- a/imports/meteor-app-tests/get-sitemap-xml.app-test.js +++ /dev/null @@ -1,37 +0,0 @@ -import Random from "@reactioncommerce/random"; -import { expect } from "meteor/practicalmeteor:chai"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import { Sitemaps } from "/imports/plugins/included/sitemap-generator/lib/collections/sitemaps"; -import getSitemapXML from "/imports/plugins/included/sitemap-generator/server/lib/get-sitemap-xml"; - -describe("getSitemapXML", () => { - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - it("should return an empty string if no sitemap by handle for given shop is found", () => { - Sitemaps.remove({}); - const xml = getSitemapXML("FAKE_SHOP_ID", "FAKE_HANDLE"); - expect(xml).to.equal(""); - }); - - it("should return the correct XML for a sitemap", () => { - const shopId = Random.id(); - const handle = "sitemap.xml"; - const mockSitemap = { - shopId, - handle, - _id: Random.id(), - xml: "", // Fake XML - createdAt: new Date() - }; - - Sitemaps.insert(mockSitemap); - - const xml = getSitemapXML(shopId, handle); - expect(xml).to.equal(mockSitemap.xml); - }); -}); diff --git a/imports/meteor-app-tests/members-publications.app-test.js b/imports/meteor-app-tests/members-publications.app-test.js deleted file mode 100644 index ba230daae13..00000000000 --- a/imports/meteor-app-tests/members-publications.app-test.js +++ /dev/null @@ -1,84 +0,0 @@ -/* eslint dot-notation: 0 */ -/* eslint prefer-arrow-callback:0 */ -import _ from "lodash"; -import { Meteor } from "meteor/meteor"; -import { Factory } from "meteor/dburles:factory"; -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import { Roles } from "meteor/alanning:roles"; -import { getShop } from "/imports/plugins/core/core/server/fixtures/shops"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import Fixtures from "/imports/plugins/core/core/server/fixtures"; - -const shopId = getShop()._id; - -describe("Account Publications", function () { - let sandbox; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - Fixtures(); - done(); - }); - }); - - beforeEach(function () { - // reset - Meteor.users.remove({}); - sandbox = sinon.sandbox.create(); - }); - - afterEach(function () { - sandbox.restore(); - }); - - describe("ShopMembers", function () { - it("should let an admin fetch userIds", function () { - sandbox.stub(Reaction, "getShopId", () => shopId); - sandbox.stub(Roles, "userIsInRole", () => true); - const publication = Meteor.server.publish_handlers["ShopMembers"]; - const user = Factory.create("user"); - const thisContext = { - userId: user._id - }; - const cursor = publication.apply(thisContext); - // verify - const data = cursor.fetch()[0]; - expect(data._id).to.equal(user._id); - }); - - it("should not let a regular user fetch userIds", function () { - sandbox.stub(Reaction, "getShopId", () => shopId); - sandbox.stub(Roles, "userIsInRole", () => false); - const thisContext = { - userId: "notAdminUser", - ready() { return "ready"; } - }; - const publication = Meteor.server.publish_handlers["ShopMembers"]; - const cursor = publication.apply(thisContext); - expect(cursor).to.equal("ready"); - }); - - it("should not overpublish user data to admins", function () { - sandbox.stub(Reaction, "getShopId", () => shopId); - sandbox.stub(Roles, "userIsInRole", () => true); - const user = Factory.create("user"); - Factory.create("registeredUser"); - const thisContext = { - userId: user._id, - ready() { return "ready"; } - }; - const publication = Meteor.server.publish_handlers["ShopMembers"]; - const cursor = publication.apply(thisContext); - // verify - const data = cursor.fetch(); - // we expect services will be clean object - expect(data.some((_user) => - // we expect two users. First will be without services, second with - // clean services object - typeof _user.services === "object" && - _.isEqual(_user.services, {}))).to.be.true; - }); - }); -}); diff --git a/imports/meteor-app-tests/methods.app-test.js b/imports/meteor-app-tests/methods.app-test.js deleted file mode 100644 index 26450966983..00000000000 --- a/imports/meteor-app-tests/methods.app-test.js +++ /dev/null @@ -1,98 +0,0 @@ -/* eslint-disable require-jsdoc */ -/* eslint prefer-arrow-callback:0 */ -import { Meteor } from "meteor/meteor"; -import { Roles } from "meteor/alanning:roles"; -import { Factory } from "meteor/dburles:factory"; -import { Shops, Tags } from "/lib/collections"; -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import ReactionError from "@reactioncommerce/reaction-error"; - -describe("Server/Core", function () { - let sandbox; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - beforeEach(function () { - sandbox = sinon.sandbox.create(); - }); - - afterEach(function () { - sandbox.restore(); - }); - - describe("shop/createTag", () => { - beforeEach(() => { - Tags.remove({}); - }); - - it("should throw 403 error by non admin", () => { - sandbox.stub(Roles, "userIsInRole", () => false); - sandbox.spy(Tags, "insert"); - expect(function () { - return Meteor.call("shop/createTag", "testTag", true); - }).to.throw(ReactionError, /Access Denied/); - expect(Tags.insert).not.to.have.been.called; - }); - - it("should create new tag", (done) => { - sandbox.stub(Roles, "userIsInRole", () => true); - sandbox.spy(Tags, "insert"); - expect(Meteor.call("shop/createTag", "testTag", true)).to.be.a("string"); - expect(Tags.insert).to.have.been.called; - return done(); - }); - }); - - describe("shop/updateHeaderTags", function () { - beforeEach(function () { - Shops.remove({}); - return Tags.remove({}); - }); - - it("should throw 403 error by non admin", function (done) { - sandbox.spy(Tags, "update"); - const tag = Factory.create("tag"); - function updateTagFunc() { - return Meteor.call("shop/updateHeaderTags", tag._id); - } - expect(updateTagFunc).to.throw(ReactionError, /Access Denied/); - expect(Tags.update).not.to.have.been.called; - return done(); - }); - - it("should insert new header tag with 1 argument by admin", function (done) { - sandbox.stub(Reaction, "hasPermission", function () { - return true; - }); - const tagCount = Tags.find().count(); - Factory.create("shop"); // Create shop so that ReactionCore.getShopId() doesn't fail - Meteor.call("shop/updateHeaderTags", "new tag"); - expect(Tags.find().count()).to.equal(tagCount + 1); - const tag = Tags.find().fetch()[0]; - expect(tag.name).to.equal("new tag"); - expect(tag.slug).to.equal("new-tag"); - return done(); - }); - - it("should update existing header tag with 2 arguments by admin", function (done) { - let tag; - sandbox.stub(Reaction, "hasPermission", function () { - return true; - }); - tag = Factory.create("tag"); - Meteor.call("shop/updateHeaderTags", "updated tag", tag._id); - expect(Tags.find().count()).to.equal(1); - tag = Tags.findOne(); - expect(tag.name).to.equal("updated tag"); - expect(tag.slug).to.equal("updated-tag"); - return done(); - }); - }); -}); diff --git a/imports/meteor-app-tests/packages-update.app-test.js b/imports/meteor-app-tests/packages-update.app-test.js deleted file mode 100644 index 89db1385332..00000000000 --- a/imports/meteor-app-tests/packages-update.app-test.js +++ /dev/null @@ -1,78 +0,0 @@ -/* eslint-disable require-jsdoc */ -/* eslint prefer-arrow-callback:0 */ -import { Meteor } from "meteor/meteor"; -import { Match } from "meteor/check"; -import { Factory } from "meteor/dburles:factory"; -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import { Packages } from "/lib/collections"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import ReactionError from "@reactioncommerce/reaction-error"; - -describe("Update Package", function () { - let sandbox; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - beforeEach(function () { - sandbox = sinon.sandbox.create(); - }); - - afterEach(function () { - sandbox.restore(); - }); - - describe("package/update", function () { - it("should throw an 'Access Denied' error for non-admins", function () { - this.timeout(20000); - const pkgUpdateSpy = sandbox.spy(Packages, "update"); - const examplePackage = Factory.create("examplePackage"); - - function updatePackage() { - return Meteor.call("package/update", examplePackage.name, "settings", {}); - } - expect(updatePackage).to.throw(ReactionError, /Access Denied/); - expect(pkgUpdateSpy).to.not.have.been.called; - }); - - it("should throw an error when supplied with an argument of the wrong type", function () { - this.timeout(20000); - const pkgUpdateSpy = sandbox.spy(Packages, "update"); - sandbox.stub(Reaction, "getShopId", () => "randomId"); - sandbox.stub(Reaction, "hasPermission", () => true); - - function updatePackage(packageName, field, value) { - return Meteor.call("package/update", packageName, field, value); - } - expect(() => updatePackage([], "someField", { foo: "bar" })).to.throw(Match.Error, /Match error: Expected string, got object/); - expect(() => updatePackage("somePackage", [], { foo: "bar" })).to.throw(Match.Error, /Match error: Expected string, got object/); - expect(() => updatePackage("somePackage", "someField", "")) - .to.throw(Match.Error, /Match error: Failed Match.OneOf, Match.Maybe or Match.Optional validation/); - expect(pkgUpdateSpy).to.not.have.been.called; - }); - - it("should be able to update any Package", function () { - this.timeout(20000); - const packageUpdateSpy = sandbox.spy(Packages, "update"); - const oldPackage = Factory.create("examplePackage"); - - sandbox.stub(Reaction, "getShopId", () => oldPackage.shopId); - sandbox.stub(Reaction, "hasPermission", () => true); - const packageName = oldPackage.name; - const newValues = { - enabled: true, - apiUrl: "http://foo-bar.com/api/v1" - }; - Meteor.call("package/update", packageName, "settings", newValues); - expect(packageUpdateSpy).to.have.been.called; - const updatedPackage = Packages.findOne({ name: packageName }); - expect(oldPackage.settings.enabled).to.not.equal(updatedPackage.settings.enabled); - expect(oldPackage.settings.apiUrl).to.not.equal(updatedPackage.settings.apiUrl); - }); - }); -}); diff --git a/imports/meteor-app-tests/shops.app-test.js b/imports/meteor-app-tests/shops.app-test.js deleted file mode 100644 index a65e37b4fd8..00000000000 --- a/imports/meteor-app-tests/shops.app-test.js +++ /dev/null @@ -1,139 +0,0 @@ -/* eslint dot-notation: 0 */ -/* eslint prefer-arrow-callback:0 */ -import Logger from "@reactioncommerce/logger"; -import Random from "@reactioncommerce/random"; -import { Meteor } from "meteor/meteor"; -import { expect } from "meteor/practicalmeteor:chai"; -import { Factory } from "meteor/dburles:factory"; -import { sinon, stubs, spies } from "meteor/practicalmeteor:sinon"; -import Fixtures from "/imports/plugins/core/core/server/fixtures"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import ReactionError from "@reactioncommerce/reaction-error"; -import { Shops } from "/lib/collections"; - -describe("Shop Methods", function () { - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - Fixtures(); - done(); - }); - }); - - beforeEach(function () { - return Shops.remove({}); - }); - - after(function () { - spies.restoreAll(); - stubs.restoreAll(); - }); - - it("shop factory should create a new shop", function () { - stubs.create("hasPermissionStub", Reaction, "hasPermission"); - stubs.hasPermissionStub.returns(true); - spies.create("shopInsertSpy", Shops, "insert"); - Factory.create("shop"); - expect(spies.shopInsertSpy).to.have.been.called; - }); -}); - -describe("core shop methods", function () { - let sandbox; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - Fixtures(); - done(); - }); - }); - - beforeEach(function () { - sandbox = sinon.sandbox.create(); - }); - - afterEach(function () { - sandbox.restore(); - }); - - describe("shop/createShop", function () { - let primaryShop; - let insertShopSpy; - - beforeEach(function () { - this.timeout(20000); - Shops.remove({}); - - primaryShop = Factory.create("shop"); - sandbox.stub(Reaction, "getPrimaryShop", () => primaryShop); - - insertShopSpy = sandbox.spy(Shops, "insert"); - }); - - describe("failure conditions", function () { - it("throws a 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - - expect(() => Meteor.call("shop/createShop")) - .to.throw(ReactionError, /Access Denied/); - expect(insertShopSpy).to.not.have.been.called; - }); - }); - - describe("success conditions", function () { - let userId; - let shopId; - let name; - - beforeEach(function () { - userId = Random.id(); - shopId = Random.id(); - name = Random.id(); - - Factory.create("user", { - _id: userId, - emails: [{ - address: `${userId}@example.com`, - provides: "default", - verified: true - }] - }); - Factory.create("account", { userId, shopId }); - - sandbox.stub(Reaction, "getUserId", () => userId); - sandbox.stub(Reaction, "hasPermission", () => true); - sandbox.stub(Reaction, "getPrimaryShopId", () => shopId); - - // a logging statement exists, stub it to keep the output clean - sandbox.stub(Logger, "info") - .withArgs(sinon.match(/Created shop/), sinon.match.string); - }); - - afterEach(function () { - const newShopCount = Shops.find({ name }).count(); - expect(newShopCount).to.equal(1); - }); - - it("creates a new shop for admin for userId and a partial shopObject", function () { - this.timeout(15000); - const partialShop = { name }; - - Meteor.call("shop/createShop", userId, partialShop); - }); - - it("creates a new shop for admin for userId and a partial shopObject ignoring extraneous data", function () { - this.timeout(15000); - const extraneousData = Random.id(); - const partialShop = { name, extraneousData }; - - Meteor.call("shop/createShop", userId, partialShop); - - expect(insertShopSpy) - .to.have.been.calledWith(sinon.match({ name })); - expect(insertShopSpy) - .to.not.have.been.calledWith(sinon.match({ extraneousData })); - }); - }); - }); -}); diff --git a/imports/meteor-app-tests/tags.app-test.js b/imports/meteor-app-tests/tags.app-test.js deleted file mode 100644 index 5f08825299f..00000000000 --- a/imports/meteor-app-tests/tags.app-test.js +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable require-jsdoc */ -import { Random } from "meteor/random"; -import { expect } from "meteor/practicalmeteor:chai"; -import { Factory } from "meteor/dburles:factory"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import { PublicationCollector } from "meteor/johanbrook:publication-collector"; -import * as Collections from "/lib/collections"; -import Fixtures from "/imports/plugins/core/core/server/fixtures"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import { createActiveShop } from "/imports/plugins/core/core/server/fixtures/shops"; - -describe("Tags Publication", () => { - let sandbox; - let collector; - let primaryShop; - let shop; - let tags; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - Fixtures(); - done(); - }); - }); - - beforeEach(() => { - sandbox = sinon.sandbox.create(); - - collector = new PublicationCollector({ userId: Random.id() }); - - primaryShop = createActiveShop(); - shop = Factory.create("shop"); - - sandbox.stub(Reaction, "getPrimaryShopId", () => primaryShop._id); - sandbox.stub(Reaction, "hasPermission", () => true); - - Collections.Tags.remove({}); - - tags = [1, 2, 3].map(() => { - const tag = createTag({ shopId: primaryShop._id }); - Collections.Tags.insert(tag); - return tag; - }); - }); - - afterEach(() => { - sandbox.restore(); - }); - - it("ensures our test is set up properly", () => { - expect(primaryShop._id).to.not.equal(shop._id); - }); - - it("returns all Tags when the current shop is the Primary Shop", (done) => { - // create a tag for a Merchant Shop - const tag = createTag({ shopId: shop._id }); - Collections.Tags.insert(tag); - - const expectedTags = [...tags, tag]; - const tagIds = expectedTags.map((expectedTag) => expectedTag._id); - tagIds.sort(); - - sandbox.stub(Reaction, "getShopId", () => primaryShop._id); - - collector.collect("Tags", tagIds, (collections) => { - const collectionTags = collections.Tags; - - expect(collectionTags.map((collectionTag) => collectionTag._id).sort()) - .to.eql(tagIds); - // eslint-disable-next-line promise/no-callback-in-promise - }).then(() => done()).catch(done); - }); - - function randomString() { - return Math.random().toString(36); - } - - function createTag(tagData = {}) { - return Object.assign({ - name: randomString(), - slug: randomString(), - isTopLevel: true - }, tagData); - } -}); From c68dbbc96b00bbb665dcac9f91ad227ede210af3 Mon Sep 17 00:00:00 2001 From: Erik Kieckhafer Date: Mon, 16 Sep 2019 09:27:18 -0700 Subject: [PATCH 3/8] chore: remove testing related packages Signed-off-by: Erik Kieckhafer --- .meteor/packages | 7 ------- .meteor/versions | 10 ---------- 2 files changed, 17 deletions(-) diff --git a/.meteor/packages b/.meteor/packages index bfc78964d57..c143863c9bc 100644 --- a/.meteor/packages +++ b/.meteor/packages @@ -58,11 +58,4 @@ percolate:migrations gadicc:blaze-react-component orionsoft:graphql-compiler -# Testing packages -dburles:factory -meteortesting:mocha -practicalmeteor:chai -practicalmeteor:sinon -johanbrook:publication-collector - # Custom Packages diff --git a/.meteor/versions b/.meteor/versions index 80791f31ddc..8471f35cae1 100644 --- a/.meteor/versions +++ b/.meteor/versions @@ -28,8 +28,6 @@ caching-compiler@1.2.1 caching-html-compiler@1.1.3 callback-hook@1.1.0 check@1.3.1 -coffeescript@1.0.17 -dburles:factory@1.1.0 ddp@1.4.0 ddp-client@2.3.3 ddp-common@1.4.0 @@ -58,22 +56,17 @@ htmljs@1.0.11 http@1.4.1 id-map@1.1.0 inter-process-messaging@0.1.0 -johanbrook:publication-collector@1.1.0 jquery@1.11.11 juliancwirko:postcss@1.3.0 launch-screen@1.1.1 less@2.8.0 livedata@1.0.18 -lmieulet:meteor-coverage@1.1.4 localstorage@1.2.0 logging@1.1.20 mdg:validated-method@1.2.0 meteor@1.9.2 meteor-base@1.4.0 -meteorhacks:picker@1.0.3 meteorhacks:subs-manager@1.6.4 -meteortesting:browser-tests@0.2.0 -meteortesting:mocha@0.6.0 minifier-css@1.4.1 minifier-js@2.4.0 minimongo@1.4.5 @@ -98,9 +91,6 @@ ongoworks:security@2.1.0 ordered-dict@1.1.0 orionsoft:graphql-compiler@0.0.4 percolate:migrations@0.9.8 -practicalmeteor:chai@2.1.0_1 -practicalmeteor:mocha-core@1.0.1 -practicalmeteor:sinon@1.14.1_2 promise@0.11.2 raix:eventemitter@0.1.3 random@1.1.0 From 28e2f20eee69480f8e0f9f4290502898efc4cddd Mon Sep 17 00:00:00 2001 From: Erik Kieckhafer Date: Mon, 16 Sep 2019 09:27:34 -0700 Subject: [PATCH 4/8] chore: remove test-app from CI config Signed-off-by: Erik Kieckhafer --- .circleci/config.yml | 27 --------------------------- 1 file changed, 27 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index a1670216ece..b0307f51c3c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -197,29 +197,6 @@ jobs: command: | npm run lint:gql - test-app: - <<: *defaults - steps: - - checkout - - restore_cache: - name: Restoring Meteor cache - key: reaction-v2-meteor - - run: - name: Link Restored Meteor - command: sudo ln -s ~/.meteor/meteor /usr/local/bin/meteor - - restore_cache: - # Fall back to less specific caches - keys: - - reaction-v2-node-modules-{{ checksum "package.json" }}-{{ checksum "package-lock.json" }} - - reaction-v2-node-modules-{{ .Branch }} - - reaction-v2-node-modules-master - - run: - name: Load App Plugins - command: node --experimental-modules ./.reaction/scripts/build.mjs - - run: - name: Run Meteor Integration Tests - command: .circleci/tests.sh - test-unit: <<: *defaults steps: @@ -298,9 +275,6 @@ workflows: jobs: - build - dockerfile-lint - - test-app: - requires: - - build - test-unit: requires: - build @@ -322,7 +296,6 @@ workflows: - deploy-docs: requires: - test-unit - - test-app - docker-build filters: branches: From e3d18ac23ed25be1bd2a321541e1324ce5503acc Mon Sep 17 00:00:00 2001 From: Erik Kieckhafer Date: Mon, 16 Sep 2019 09:27:45 -0700 Subject: [PATCH 5/8] chore: update package-lock.json Signed-off-by: Erik Kieckhafer --- package-lock.json | 75 +++++++++++++++++------------------------------ 1 file changed, 27 insertions(+), 48 deletions(-) diff --git a/package-lock.json b/package-lock.json index 94a99b37cb6..a7bbb9fea0e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3016,14 +3016,14 @@ "resolved": "https://registry.npmjs.org/@reactioncommerce/file-collections/-/file-collections-0.7.0.tgz", "integrity": "sha512-Tqhfz3nFC8ivjKseogu3qnU7HauklD89eJjPJNZJrf61ayjEfNfoCHLnijHRQ/B8pT0qy8/jLp9RUukQuS7lrg==", "requires": { - "babel-runtime": "6.26.0", - "content-disposition": "0.5.2", - "debug": "3.2.6", - "extend": "3.0.2", - "path-parser": "4.2.0", - "query-string": "5.1.1", - "tus-js-client": "1.7.1", - "tus-node-server": "0.3.2" + "babel-runtime": "^6.26.0", + "content-disposition": "^0.5.2", + "debug": "^3.1.0", + "extend": "~3.0.2", + "path-parser": "^4.0.4", + "query-string": "^5.1.0", + "tus-js-client": "^1.5.1", + "tus-node-server": "~0.3.2" }, "dependencies": { "debug": { @@ -3031,7 +3031,7 @@ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", "requires": { - "ms": "2.1.2" + "ms": "^2.1.1" } }, "ms": { @@ -3046,8 +3046,8 @@ "resolved": "https://registry.npmjs.org/@reactioncommerce/file-collections-sa-base/-/file-collections-sa-base-0.1.0.tgz", "integrity": "sha512-T4isLFSb5CKHyYgJkvPnMY/GCwit8j3SFvCFXvRUNrqUWnqHMPLIMgsWLPmCfGC5EIFiqf1cBNF9JeBs/gHvfw==", "requires": { - "babel-runtime": "6.26.0", - "debug": "3.1.0" + "babel-runtime": "^6.26.0", + "debug": "^3.1.0" }, "dependencies": { "debug": { @@ -4300,12 +4300,12 @@ "dependencies": { "buffer": { "version": "4.9.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", + "resolved": "http://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", "requires": { - "base64-js": "1.3.0", - "ieee754": "1.1.8", - "isarray": "1.0.0" + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" } }, "ieee754": { @@ -8625,8 +8625,7 @@ "version": "0.0.8", "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", - "dev": true, - "optional": true + "dev": true }, "minipass": { "version": "2.2.4", @@ -8650,7 +8649,6 @@ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "dev": true, - "optional": true, "requires": { "minimist": "0.0.8" } @@ -8942,7 +8940,6 @@ "resolved": "https://registry.npmjs.org/minipass/-/minipass-2.3.5.tgz", "integrity": "sha512-Gi1W4k059gyRbyVUZQ4mEqLm0YIUiGYfvxhF6SIlk3ui1WVxMTGfGdQ2SInh3PDrRTVvPKgULkpJtT4RH10+VA==", "dev": true, - "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -8962,15 +8959,13 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true, - "optional": true + "dev": true }, "yallist": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.0.3.tgz", "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==", - "dev": true, - "optional": true + "dev": true } } }, @@ -11361,8 +11356,7 @@ "ansi-regex": { "version": "2.1.1", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "aproba": { "version": "1.2.0", @@ -11405,8 +11399,7 @@ "code-point-at": { "version": "1.1.0", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "concat-map": { "version": "0.0.1", @@ -11417,8 +11410,7 @@ "console-control-strings": { "version": "1.1.0", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "core-util-is": { "version": "1.0.2", @@ -11535,8 +11527,7 @@ "inherits": { "version": "2.0.3", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "ini": { "version": "1.3.5", @@ -11548,7 +11539,6 @@ "version": "1.0.0", "bundled": true, "dev": true, - "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -11563,7 +11553,6 @@ "version": "3.0.4", "bundled": true, "dev": true, - "optional": true, "requires": { "brace-expansion": "^1.1.7" } @@ -11571,14 +11560,12 @@ "minimist": { "version": "0.0.8", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "minipass": { "version": "2.3.5", "bundled": true, "dev": true, - "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -11597,7 +11584,6 @@ "version": "0.5.1", "bundled": true, "dev": true, - "optional": true, "requires": { "minimist": "0.0.8" } @@ -11678,8 +11664,7 @@ "number-is-nan": { "version": "1.0.1", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "object-assign": { "version": "4.1.1", @@ -11691,7 +11676,6 @@ "version": "1.4.0", "bundled": true, "dev": true, - "optional": true, "requires": { "wrappy": "1" } @@ -11777,8 +11761,7 @@ "safe-buffer": { "version": "5.1.2", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "safer-buffer": { "version": "2.1.2", @@ -11814,7 +11797,6 @@ "version": "1.0.2", "bundled": true, "dev": true, - "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -11834,7 +11816,6 @@ "version": "3.0.1", "bundled": true, "dev": true, - "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -11878,14 +11859,12 @@ "wrappy": { "version": "1.0.2", "bundled": true, - "dev": true, - "optional": true + "dev": true }, "yallist": { "version": "3.0.3", "bundled": true, - "dev": true, - "optional": true + "dev": true } } }, From e85a2cb337957b337c736ac933a55b4e927c83c3 Mon Sep 17 00:00:00 2001 From: Erik Kieckhafer Date: Mon, 16 Sep 2019 09:39:04 -0700 Subject: [PATCH 6/8] chore: remove `test:app` from scripts Signed-off-by: Erik Kieckhafer --- package.json | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/package.json b/package.json index 9c164c2ffe0..e6de45c1370 100644 --- a/package.json +++ b/package.json @@ -219,9 +219,7 @@ "lint:errors": "eslint . --quiet", "lint:gql": "graphql-schema-linter **/schemas/*.graphql", "lint:warnings": "eslint --max-warnings=0", - "test": "npm run test:unit && npm run test:integration && npm run test:app", - "test:app": "MONGO_URL='' SKIP_FIXTURES=true TEST_CLIENT=0 meteor test --no-release-check --once --full-app --driver-package meteortesting:mocha", - "test:app:watch": "MONGO_URL='' SKIP_FIXTURES=true TEST_CLIENT=0 TEST_WATCH=1 meteor test --no-release-check --full-app --driver-package meteortesting:mocha", + "test": "npm run test:unit && npm run test:integration", "test:unit": "NODE_ENV=jesttest BABEL_DISABLE_CACHE=1 REACTION_LOG_LEVEL=ERROR jest --no-cache --maxWorkers=4 --testPathIgnorePatterns /tests/integration/", "test:unit:watch": "NODE_ENV=jesttest BABEL_DISABLE_CACHE=1 REACTION_LOG_LEVEL=ERROR jest --no-cache --maxWorkers=4 --testPathIgnorePatterns /tests/integration/ --watch", "test:integration": "NODE_ENV=jesttest BABEL_DISABLE_CACHE=1 REACTION_LOG_LEVEL=ERROR jest --maxWorkers=4 --no-cache /tests/integration/", From 89ba992df794c8e7d9b31f86da5cd57af3c4e450 Mon Sep 17 00:00:00 2001 From: Erik Kieckhafer Date: Mon, 16 Sep 2019 09:39:20 -0700 Subject: [PATCH 7/8] chore: remove test:app shell script Signed-off-by: Erik Kieckhafer --- .circleci/tests.sh | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100755 .circleci/tests.sh diff --git a/.circleci/tests.sh b/.circleci/tests.sh deleted file mode 100755 index 1edd84ecb0a..00000000000 --- a/.circleci/tests.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash - -# Allow reaction tests to potentially fail the first time because -# tests sometimes fail due to a SIGKILL during Meteor package npm install. -# Since the install doesn't need to happen on second run, the error is -# often avoided and the false positive doesn't fail the CircleCI build. -# -# This will update npm deps which takes a while - -set +e - -npm run test:app - -if [ $? -eq 0 ]; then - echo "Reaction tests have passed!" -else - echo "Reaction tests failed. Trying one more time..." - set -e - npm run test:app -fi From 9190c9cfe42c25c1b9b9ab1d01f4ba32066791e9 Mon Sep 17 00:00:00 2001 From: Erik Kieckhafer Date: Mon, 16 Sep 2019 10:31:50 -0700 Subject: [PATCH 8/8] chore: remove excess app-test files Signed-off-by: Erik Kieckhafer --- .../server/methods/catalog.app-test.js | 531 ------------------ .../util/connectionDataStore.app-test.js | 102 ---- .../server/methods/methods.app-test.js | 70 --- lib/core/url-common.app-test.js | 171 ------ 4 files changed, 874 deletions(-) delete mode 100644 imports/plugins/core/catalog/server/methods/catalog.app-test.js delete mode 100644 imports/plugins/core/core/server/util/connectionDataStore.app-test.js delete mode 100644 imports/plugins/included/discount-codes/server/methods/methods.app-test.js delete mode 100644 lib/core/url-common.app-test.js diff --git a/imports/plugins/core/catalog/server/methods/catalog.app-test.js b/imports/plugins/core/catalog/server/methods/catalog.app-test.js deleted file mode 100644 index 657a5d927e8..00000000000 --- a/imports/plugins/core/catalog/server/methods/catalog.app-test.js +++ /dev/null @@ -1,531 +0,0 @@ -/* eslint dot-notation:0 */ -/* eslint no-loop-func:0 */ -/* eslint prefer-arrow-callback:0 */ -import _ from "lodash"; -import { Meteor } from "meteor/meteor"; -import { Factory } from "meteor/dburles:factory"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import { Products, Tags } from "/lib/collections"; -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import { Roles } from "meteor/alanning:roles"; -import ReactionError from "@reactioncommerce/reaction-error"; -import { addProduct, addProductSingleVariant } from "/imports/plugins/core/core/server/fixtures/products"; -import { getBaseContext } from "/imports/plugins/core/graphql/server/getGraphQLContextInMeteorMethod"; -import Fixtures from "/imports/plugins/core/core/server/fixtures"; - -describe("core product methods", function () { - // we can't clean Products collection after each test from now, because we - // have functions which called from async db operations callbacks. So, if we - // clean collections each time - we could have a situation when next test - // started, but previous not yet finished his async computations. - // So, if you need to clean the collection for your test, you could try to do - // it, but this is not recommended in droves - let sandbox; - let updateStub; - let removeStub; - let insertStub; - - before(function (done) { - this.timeout(20000); - - Reaction.onAppStartupComplete(() => { - Fixtures(); - Products.remove({}); - - // We sleep until `setBaseContext` has run. I wish there were a better way to - // do this but Meteor starts app tests whenever it decides to, without waiting - // for all the startup code to run. - const handle = Meteor.setInterval(() => { - if (getBaseContext().queries) { - Meteor.clearInterval(handle); - done(); - } - }, 500); - }); - }); - - after(function () { - if (updateStub) { - updateStub.restore(); - removeStub.restore(); - insertStub.restore(); - } - }); - - beforeEach(function () { - sandbox = sinon.sandbox.create(); - }); - - afterEach(function () { - sandbox.restore(); - }); - - describe("products/cloneVariant", function () { - it("should throw 403 error by non admin", function () { - this.timeout(20000); - sandbox.stub(Roles, "userIsInRole", () => false); - const product = addProduct(); - const variants = Products.find({ ancestors: [product._id] }).fetch(); - expect(variants.length).to.equal(1); - - const insertProductSpy = sandbox.spy(Products, "insert"); - expect(() => Meteor.call("products/cloneVariant", product._id, variants[0]._id)).to.throw(ReactionError, /Access Denied/); - expect(insertProductSpy).to.not.have.been.called; - }); - - it("should clone variant by admin", function () { - sandbox.stub(Roles, "userIsInRole", () => true); - const product = addProduct(); - let variants = Products.find({ ancestors: [product._id] }).fetch(); - expect(variants.length).to.equal(1); - Meteor.call("products/cloneVariant", product._id, variants[0]._id); - variants = Products.find({ ancestors: [product._id] }).count(); - expect(variants).to.equal(2); - }); - - it("number of `child variants` between source and cloned `variants` should be equal", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - const variant = Products.find({ ancestors: [product._id] }).fetch(); - let optionCount = Products.find({ - ancestors: { - $in: [variant[0]._id] - } - }).count(); - expect(optionCount).to.equal(2); - - Meteor.call("products/cloneVariant", product._id, variant[0]._id); - const variants = Products.find({ ancestors: [product._id] }).fetch(); - const clonedVariant = variants.filter((filteredVariant) => filteredVariant._id !== variant[0]._id); - expect(variant[0]._id).to.not.equal(clonedVariant[0]._id); - expect(_.isEqual(variant[0].ancestors, clonedVariant[0].ancestors)).to.be.true; - // expect(variant[0].ancestors).to.equal(clonedVariant[0].ancestors); - - optionCount = Products.find({ ancestors: { $in: [clonedVariant[0]._id] } }).count(); - expect(optionCount).to.equal(2); - }); - }); - - describe("products/createVariant", function () { - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const updateProductSpy = sandbox.spy(Products, "update"); - expect(() => Meteor.call("products/createVariant", product._id)).to.throw(ReactionError, /Access Denied/); - expect(updateProductSpy).to.not.have.been.called; - }); - - it("should create top level variant", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - let variants = Products.find({ ancestors: [product._id] }).fetch(); - expect(variants.length).to.equal(1); - Meteor.call("products/createVariant", product._id); - variants = Products.find({ ancestors: [product._id] }).fetch(); - expect(variants.length).to.equal(2); - }); - - it("should create option variant", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - let options; - const product = addProduct(); - const variant = Products.find({ ancestors: [product._id] }).fetch()[0]; - options = Products.find({ - ancestors: { $in: [variant._id] } - }).fetch(); - expect(options.length).to.equal(2); - - Meteor.call("products/createVariant", variant._id); - options = Products.find({ - ancestors: { $in: [variant._id] } - }).fetch(); - expect(options.length).to.equal(3); - }); - }); - - describe("products/deleteVariant", function () { - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const variant = Products.findOne({ ancestors: [product._id] }); - const removeProductSpy = sandbox.spy(Products, "remove"); - expect(() => Meteor.call("products/deleteVariant", variant._id)).to.throw(ReactionError, /Access Denied/); - expect(removeProductSpy).to.not.have.been.called; - }); - - it("should mark top-level variant as deleted", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - let variant = Products.findOne({ ancestors: [product._id] }); - expect(variant.isDeleted).to.equal(false); - Meteor.call("products/deleteVariant", variant._id); - variant = Products.findOne(variant._id); - expect(variant.isDeleted).to.equal(true); - }); - - it("should mark all child variants (options) as deleted if top-level variant deleted", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - const variant = Products.find({ ancestors: [product._id] }).fetch()[0]; - const variants = Products.find({ - ancestors: { - $in: [variant._id] - } - }).fetch(); - expect(variants.length).to.equal(2); - Meteor.call("products/deleteVariant", variant._id); - }); - }); - - describe("products/cloneProduct", function () { - // At the moment we do not have any mechanisms that track the product - // cloning hierarchy, so the only way to track that will be cleaning - // collection on before each test. - beforeEach(function () { - return Products.remove({}); - }); - - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const insertProductSpy = sandbox.spy(Products, "insert"); - expect(() => Meteor.call("products/cloneProduct", {})).to.throw(ReactionError, /Access Denied/); - expect(insertProductSpy).to.not.have.been.called; - }); - - it("should clone product", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - expect(Products.find({ type: "simple" }).count()).to.equal(1); - Meteor.call("products/cloneProduct", product); - expect(Products.find({ type: "simple" }).count()).to.equal(2); - const productCloned = Products.find({ - _id: { - $ne: product._id - }, - type: "simple" - }).fetch()[0]; - expect(productCloned.title).to.equal(`${product.title}-copy`); - expect(productCloned.handle).to.equal(`${product.handle}-copy`); - expect(productCloned.pageTitle).to.equal(product.pageTitle); - expect(productCloned.description).to.equal(product.description); - }); - - it("product should be cloned with all variants and child variants with equal data, but not the same `_id`s", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - const variants = Products.find({ ancestors: { $in: [product._id] } }).fetch(); - expect(variants.length).to.equal(3); - Meteor.call("products/cloneProduct", product); - const clone = Products.find({ - _id: { - $ne: product._id - }, - type: "simple" - }).fetch()[0]; - const cloneVariants = Products.find({ - ancestors: { $in: [clone._id] } - }).fetch(); - expect(cloneVariants.length).to.equal(3); - for (let inc = 0; inc < variants.length; inc += 1) { - expect(cloneVariants.some((clonedVariant) => clonedVariant.title === variants[inc].title)).to.be.ok; - } - }); - - it("product group cloning should create the same number of new products", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - const product2 = addProduct(); - Meteor.call("products/cloneProduct", [product, product2]); - const clones = Products.find({ - _id: { - $nin: [product._id, product2._id] - }, - type: "simple" - }).fetch(); - expect(clones.length).to.equal(2); - }); - - it("product group cloning should create the same number of cloned variants", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - const product2 = addProduct(); - const variants = Products.find({ - ancestors: { $in: [product._id, product2._id] } - }).count(); - Meteor.call("products/cloneProduct", [product, product2]); - const clones = Products.find({ - _id: { - $nin: [product._id, product2._id] - }, - type: "simple" - }).fetch(); - expect(clones.length).to.equal(2); - const clonedVariants = Products.find({ - ancestors: { $in: [clones[0]._id, clones[1]._id] } - }).count(); - expect(clonedVariants).to.equal(variants); - }); - }); - - describe("createProduct", function () { - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const insertProductSpy = sandbox.spy(Products, "insert"); - expect(() => Meteor.call("products/createProduct")).to.throw(ReactionError, /Access Denied/); - expect(insertProductSpy).to.not.have.been.called; - }); - - it("should create new product", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - Meteor.call("products/createProduct", (error, result) => { - if (result) { - expect(Products.find({ _id: result }).count()).to.equal(1); - } - }); - }); - - it("should create variant with new product", function (done) { - sandbox.stub(Reaction, "hasPermission", () => true); - Meteor.call("products/createProduct", (error, result) => { - if (error || !result) { - done(error || new Error("no result")); - return; - } - // this test successfully finds product variant only by such way - Meteor.defer(() => { - expect(Products.find({ ancestors: [result] }).count()).to.equal(1); - done(); - }); - }); - }); - }); - - describe("deleteProduct", function () { - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const removeProductSpy = sandbox.spy(Products, "remove"); - expect(() => Meteor.call("products/archiveProduct", product._id)).to.throw(ReactionError, /Access Denied/); - expect(removeProductSpy).to.not.have.been.called; - }); - - it("should mark product as deleted by admin", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - let product = addProduct(); - Meteor.call("products/archiveProduct", product._id); - product = Products.findOne(product._id); - expect(product.isDeleted).to.equal(true); - }); - }); - - describe("updateProductField", function () { - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const updateProductSpy = sandbox.spy(Products, "update"); - expect(() => Meteor.call( - "products/updateProductField", - product._id, "title", "Updated Title" - )).to.throw(ReactionError, /Access Denied/); - expect(updateProductSpy).to.not.have.been.called; - }); - - it("should update product field by admin", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - let product = addProduct(); - Meteor.call("products/updateProductField", product._id, "title", "Updated Title"); - product = Products.findOne(product._id); - expect(product.title).to.equal("Updated Title"); - }); - - it("should update variant fields", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const product = addProduct(); - let variant = Products.findOne({ ancestors: [product._id] }); - Meteor.call("products/updateProductField", variant._id, "title", "Updated Title"); - variant = Products.findOne(variant._id); - expect(variant.title).to.equal("Updated Title"); - }); - }); - - describe("updateProductTags", function () { - beforeEach(function () { - return Tags.remove({}); - }); - - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const updateProductSpy = sandbox.spy(Products, "update"); - const insertTagsSpy = sandbox.spy(Tags, "insert"); - expect(() => Meteor.call("products/updateProductTags", product._id, "productTag", null)).to.throw(ReactionError, /Access Denied/); - expect(updateProductSpy).to.not.have.been.called; - expect(insertTagsSpy).to.not.have.been.called; - }); - - it("should create new tag when passed tag name and null ID by admin", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - let product = addProduct(); - const tagName = "Product Tag"; - expect(Tags.findOne({ name: tagName })).to.be.undefined; - Meteor.call("products/updateProductTags", product._id, tagName, null); - const tag = Tags.findOne({ name: tagName }); - expect(tag.slug).to.equal(Reaction.getSlug(tagName)); - product = Products.findOne(product._id); - expect(product.hashtags).to.contain(tag._id); - }); - - it("should add existing tag when passed existing tag and tag._id by admin", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - let product = addProduct(); - const tag = Factory.create("tag"); - expect(Tags.find().count()).to.equal(1); - expect(product.hashtags).to.not.contain(tag._id); - Meteor.call("products/updateProductTags", product._id, tag.name, tag._id); - expect(Tags.find().count()).to.equal(1); - product = Products.findOne(product._id); - expect(product.hashtags).to.contain(tag._id); - }); - }); - - describe("removeProductTag", function () { - beforeEach(function () { - return Tags.remove({}); - }); - - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const tag = Factory.create("tag"); - const updateProductSpy = sandbox.spy(Products, "update"); - const removeTagsSpy = sandbox.spy(Tags, "remove"); - expect(() => Meteor.call("products/removeProductTag", product._id, tag._id)).to.throw(ReactionError, /Access Denied/); - expect(updateProductSpy).to.not.have.been.called; - expect(removeTagsSpy).to.not.have.been.called; - }); - - it("should remove product tag by admin", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - let product = addProduct(); - const tag = Factory.create("tag"); - - // Update product tags and publish so the original product will have the tags - Meteor.call("products/updateProductTags", product._id, tag.name, tag._id); - product = Products.findOne(product._id); - expect(product.hashtags).to.contain(tag._id); - expect(Tags.find().count()).to.equal(1); - - // Remove the tag from the published product and ensure it succeed. - Meteor.call("products/removeProductTag", product._id, tag._id); - product = Products.findOne(product._id); - expect(product.hashtags).to.not.contain(tag._id); - }); - }); - - describe("setHandle", () => { - beforeEach(() => Tags.remove({})); - - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const productUpdateSpy = sandbox.spy(Products, "update"); - expect(() => Meteor.call("products/setHandle", product._id)).to.throw(ReactionError, /Access Denied/); - expect(productUpdateSpy).to.not.have.been.called; - }); - - it("should set handle for product by admin", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - let product = addProduct(); - Meteor.call("products/updateProductField", product._id, "title", "new product name"); - Meteor.call("products/setHandle", product._id); - product = Products.findOne(product._id); - expect(product.handle).to.equal("new-product-name"); - }); - }); - - describe("setHandleTag", function () { - beforeEach(function () { - return Tags.remove({}); - }); - - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const tag = Factory.create("tag"); - const updateProductSpy = sandbox.spy(Products, "update"); - expect(function () { - return Meteor.call("products/setHandleTag", product._id, tag._id); - }).to.throw(ReactionError, /Access Denied/); - expect(updateProductSpy).to.not.have.been.called; - }); - - it("should set handle tag for product by admin", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - let product = addProduct(); - const tag = Factory.create("tag"); - Meteor.call("products/setHandleTag", product._id, tag._id); - product = Products.findOne(product._id); - expect(product.handle).to.equal(tag.slug); - }); - }); - - describe("updateMetaFields position", () => { - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const product2 = addProduct(); - const updateProductSpy = sandbox.spy(Products, "update"); - expect(() => Meteor.call("products/updateVariantsPosition", [ - product._id, product2._id], product.shopId)).to.throw(ReactionError, /Access Denied/); - expect(updateProductSpy).to.not.have.been.called; - }); - - it("should update variants' position", function () { - sandbox.stub(Reaction, "hasPermission", () => true); - const { variant: variant1 } = addProductSingleVariant(); - const { variant: variant2 } = addProductSingleVariant(); - const { variant: variant3 } = addProductSingleVariant(); - - expect(variant1.index).to.be.undefined; - expect(variant2.index).to.be.undefined; - expect(variant3.index).to.be.undefined; - - Meteor.call("products/updateVariantsPosition", [ - variant2._id, variant3._id, variant1._id - ], variant1.shopId); - const modifiedVariant1 = Products.findOne(variant1._id); - const modifiedVariant2 = Products.findOne(variant2._id); - const modifiedVariant3 = Products.findOne(variant3._id); - expect(modifiedVariant1.index).to.be.equal(2); - expect(modifiedVariant2.index).to.be.equal(0); - expect(modifiedVariant3.index).to.be.equal(1); - }); - }); - - describe("updateMetaFields", function () { - it("should throw 403 error by non admin", function () { - sandbox.stub(Reaction, "hasPermission", () => false); - const product = addProduct(); - const updateProductSpy = sandbox.spy(Products, "update"); - expect(() => Meteor.call("products/updateMetaFields", product._id, { - key: "Material", - value: "Spandex" - })).to.throw(ReactionError, /Access Denied/); - expect(updateProductSpy).to.not.have.been.called; - }); - - it("should add meta fields by admin", function (done) { - sandbox.stub(Reaction, "hasPermission", () => true); - let product = addProduct(); - Meteor.call("products/updateMetaFields", product._id, { - key: "Material", - value: "Spandex" - }); - product = Products.findOne(product._id); - expect(product.metafields.length).to.be.equal(1); - - return done(); - }); - }); -}); diff --git a/imports/plugins/core/core/server/util/connectionDataStore.app-test.js b/imports/plugins/core/core/server/util/connectionDataStore.app-test.js deleted file mode 100644 index c577e4ea0bd..00000000000 --- a/imports/plugins/core/core/server/util/connectionDataStore.app-test.js +++ /dev/null @@ -1,102 +0,0 @@ -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import { DDP } from "meteor/ddp-client"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import ConnectionDataStore from "./connectionDataStore"; - -describe("ConnectionDataStore", () => { - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - describe("used outside of a connection", () => { - it("sets/gets cached data", () => { - ConnectionDataStore.set("key", "val"); - - expect(ConnectionDataStore.get("key")).to.equal("val"); - }); - - it("clears cached data", () => { - ConnectionDataStore.set("key", "val"); - - expect(ConnectionDataStore.get("key")).to.equal("val"); - - ConnectionDataStore.clear("key"); - - expect(ConnectionDataStore.get("key")).to.be.undefined; - }); - }); - - describe("within the context of a connection", () => { - let mockConnection; - - beforeEach(() => { - mockConnection = {}; - - sinon.stub(DDP._CurrentMethodInvocation, "get") - .returns({ connection: mockConnection }); - - ConnectionDataStore.set("key", "val"); - }); - - afterEach(() => { - mockConnection = undefined; - - DDP._CurrentMethodInvocation.get.restore(); - }); - - it("sets/gets cached data", () => { - expect(ConnectionDataStore.get("key")).to.equal("val"); - }); - - it("stores data on the connection object", () => { - expect(mockConnection["connection-data"].key).to.equal("val"); - }); - }); - - describe("within the context of a multiple connections", () => { - let mockConnection; - let mockConnection2; - - beforeEach(() => { - mockConnection = {}; - mockConnection2 = {}; - - sinon.stub(DDP._CurrentMethodInvocation, "get") - .returns({ connection: mockConnection }); - - ConnectionDataStore.set("key", "val"); - - DDP._CurrentMethodInvocation.get.restore(); - - sinon.stub(DDP._CurrentMethodInvocation, "get") - .returns({ connection: mockConnection2 }); - - ConnectionDataStore.set("key2", "val2"); - }); - - afterEach(() => { - mockConnection = undefined; - mockConnection2 = undefined; - - DDP._CurrentMethodInvocation.get.restore(); - }); - - // we are now in the context of the second connection - it("does not access previous connection's data", () => { - expect(ConnectionDataStore.get("key")).to.be.undefined; - }); - - it("does not modify previous connection's data", () => { - expect(mockConnection["connection-data"]).not.to.have.property("key2"); - }); - - it("does modify _this_ connection's data", () => { - expect(ConnectionDataStore.get("key2")).to.equal("val2"); - expect(mockConnection2["connection-data"].key2).to.equal("val2"); - }); - }); -}); diff --git a/imports/plugins/included/discount-codes/server/methods/methods.app-test.js b/imports/plugins/included/discount-codes/server/methods/methods.app-test.js deleted file mode 100644 index c6e29527f33..00000000000 --- a/imports/plugins/included/discount-codes/server/methods/methods.app-test.js +++ /dev/null @@ -1,70 +0,0 @@ -/* eslint-disable node/no-unsupported-features/es-syntax */ -/* eslint prefer-arrow-callback:0 */ -import { Meteor } from "meteor/meteor"; -import { Roles } from "meteor/alanning:roles"; -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import { Discounts } from "/imports/plugins/core/discounts/lib/collections"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import ReactionError from "@reactioncommerce/reaction-error"; - -const code = { - discount: 12, - label: "Discount 5", - description: "Discount by 5%", - discountMethod: "code", - code: "promocode" -}; - -describe("discount code methods", function () { - let sandbox; - - before(function (done) { - this.timeout(20000); - - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - beforeEach(function () { - sandbox = sinon.sandbox.create(); - }); - - afterEach(function () { - sandbox.restore(); - }); - - describe("discounts/addCode", function () { - it("should throw 403 error with discounts permission", function () { - sandbox.stub(Roles, "userIsInRole", () => false); - // this should actually trigger a whole lot of things - expect(() => Meteor.call("discounts/addCode", code)).to.throw(ReactionError, /Access Denied/); - }); - - // admin user - it("should add code when user has role", function () { - sandbox.stub(Roles, "userIsInRole", () => true); - const discountInsertSpy = sandbox.spy(Discounts, "insert"); - const discountId = Meteor.call("discounts/addCode", code); - expect(discountInsertSpy).to.have.been.called; - - const discountCount = Discounts.find(discountId).count(); - expect(discountCount).to.equal(1); - }); - }); - - describe("discounts/deleteCode", function () { - it("should delete rate with discounts permission", function () { - this.timeout(15000); - sandbox.stub(Roles, "userIsInRole", () => true); - const discountInsertSpy = sandbox.spy(Discounts, "insert"); - const discountId = Meteor.call("discounts/addCode", code); - expect(discountInsertSpy).to.have.been.called; - - Meteor.call("discounts/deleteCode", discountId); - const discountCount = Discounts.find(discountId).count(); - expect(discountCount).to.equal(0); - }); - }); -}); diff --git a/lib/core/url-common.app-test.js b/lib/core/url-common.app-test.js deleted file mode 100644 index 0d32c957888..00000000000 --- a/lib/core/url-common.app-test.js +++ /dev/null @@ -1,171 +0,0 @@ -import { expect } from "meteor/practicalmeteor:chai"; -import { sinon } from "meteor/practicalmeteor:sinon"; -import Reaction from "/imports/plugins/core/core/server/Reaction"; -import { composeUrl } from "./url-common"; - -describe("urlCommon", () => { - let sandbox; - - before(function (done) { - this.timeout(20000); - Reaction.onAppStartupComplete(() => { - done(); - }); - }); - - beforeEach(() => { - sandbox = sinon.sandbox.create(); - }); - - afterEach(() => { - sandbox.restore(); - }); - - describe("composeUrl", () => { - let path; - let rootUrl; - let initialOptions; - - beforeEach(() => { - // commonly used test vars - path = randomString(); - rootUrl = `http://${randomString()}.reactioncommerce.com`; - - // mocking global options - initialOptions = Object.assign({}, composeUrl.defaultOptions); - // this is a round-about way of mocking $ROOT_URL - composeUrl.defaultOptions.rootUrl = rootUrl; - }); - - afterEach(() => { - // restore global options - composeUrl.defaultOptions = initialOptions; - }); - - it("allows for no parameters", () => { - const expected = `${rootUrl}/`; - expect(composeUrl()).to.equal(expected); - }); - - it("allows for an optional path", () => { - const expected = `${rootUrl}/${path}`; - expect(composeUrl(path)).to.equal(expected); - }); - - it("allows for optional options", () => { - const options = {}; - - const expected = `${rootUrl}/`; - expect(composeUrl(options)).to.equal(expected); - }); - - it("requires a root url", () => { - const options = { - rootUrl: null - }; - - expect(() => composeUrl(options)) - .to.throw(/Must pass options\.rootUrl or set ROOT_URL/); - }); - - it("prepends http: when not provided", () => { - const host = `${randomString()}.reactioncommerce.com`; - const options = { - rootUrl: host - }; - - const expected = `http://${host}/`; - expect(composeUrl(options)).to.equal(expected); - }); - - it("does not prepend http: if rootUrl begins with https", () => { - const host = `https://${randomString()}.reactioncommerce.com`; - const options = { - rootUrl: host - }; - - const expected = `${host}/`; - expect(composeUrl(options)).to.equal(expected); - }); - - it("uses https with the `secure` option", () => { - const host = `${randomString()}.reactioncommerce.com`; - const options = { - rootUrl: host, - secure: true - }; - - const expected = `https://${host}/`; - expect(composeUrl(options)).to.equal(expected); - }); - - it("uses https with the `secure` option, unless localhost", () => { - const host = "localhost"; - const options = { - rootUrl: host, - secure: true - }; - - const expected = `http://${host}/`; - expect(composeUrl(options)).to.equal(expected); - }); - - it("uses https with the `secure` option, unless 127.0.0.1", () => { - const host = "127.0.0.1"; - const options = { - rootUrl: host, - secure: true - }; - - const expected = `http://${host}/`; - expect(composeUrl(options)).to.equal(expected); - }); - - it("replaces localhost with IP with `replaceLocalhost` option", () => { - const host = "localhost"; - const options = { - replaceLocalhost: true, - rootUrl: host, - secure: true - }; - - const expected = "http://127.0.0.1/"; - expect(composeUrl(options)).to.equal(expected); - }); - - describe("with global settings", () => { - it("honors the global setting `rootUrl`", () => { - composeUrl.defaultOptions.rootUrl = rootUrl; - - const expected = `${rootUrl}/${path}`; - expect(composeUrl(path)).to.equal(expected); - }); - - it("honors the global setting `secure`", () => { - composeUrl.defaultOptions.secure = true; - - const expected = - `${rootUrl}/${path}`.replace(/^http:\/\//, "https://"); - - expect(composeUrl(path)).to.equal(expected); - }); - - it("honors the global setting `replaceLocalhost`", () => { - composeUrl.defaultOptions.replaceLocalhost = true; - const options = { - rootUrl: "localhost" - }; - - const expected = `http://127.0.0.1/${path}`; - expect(composeUrl(path, options)).to.equal(expected); - }); - }); - }); - - /** - * @returns {String} random string - */ - function randomString() { - return Math.random().toString(36); - } -});