text
stringlengths
92
5.09M
import { color, serializeOKLCH } from '@csstools/css-color-parser'; import { isCommentNode, isFunctionNode, isTokenNode, isWhitespaceNode, parseComponentValue } from '@csstools/css-parser-algorithms'; import { tokenize } from '@csstools/css-tokenizer'; function renderResult() { document.querySelectorAll('.color-input...
(() => { const calculateScrollBarWidth = () => { const root = document.documentElement; const scrollBarWidth = `${window.innerWidth - document.body.clientWidth}px`; root.style.setProperty('--scroll-bar', scrollBarWidth); }; if (window.CSS && window.CSS.supports('color', 'var(--foo)')) { calculateScrollBarWi...
import { color, serializeP3, serializeRGB } from '@csstools/css-color-parser'; import { parseComponentValue } from '@csstools/css-parser-algorithms'; import { tokenize } from '@csstools/css-tokenizer'; const cylindrical = new Set(['hsl', 'hwb', 'lch', 'oklch']); const supportsP3AndP3Gamut = CSS.supports('(color: color...
import { color, serializeP3, serializeRGB } from '@csstools/css-color-parser'; import { parseComponentValue } from '@csstools/css-parser-algorithms'; import { tokenize } from '@csstools/css-tokenizer'; function renderResult() { const mainHueEl = document.getElementById('relative-color-syntax-main-hue'); if (!mainHue...
(() => { const wordList = document.querySelector('.ppe-word-rotate'); if (!wordList) { return; } const mq = '(prefers-reduced-motion: no-preference)'; const canRun = window.matchMedia(mq) === true || window.matchMedia(mq).matches === true; const words = wordList.children; const ROTATION_DURATION = 3000; le...
import { calc } from '@csstools/css-calc'; function renderResult() { const inputEl = document.getElementById('calc-input'); if (!inputEl) { return; } const outputEl = document.getElementById('calc-output'); if (!outputEl) { return; } const value = inputEl.value; if (!value) { return; } const wrapped...
import { color, serializeOKLCH, serializeP3, serializeRGB } from '@csstools/css-color-parser'; import { parseComponentValue } from '@csstools/css-parser-algorithms'; import { tokenize } from '@csstools/css-tokenizer'; function renderResult() { document.querySelectorAll('.color-input').forEach((inputEl) => { const o...
import { EditorState } from '@codemirror/state'; import { EditorView } from '@codemirror/view'; import { basicSetup } from 'codemirror'; import { css } from '@codemirror/lang-css'; import { javascript } from '@codemirror/lang-javascript'; import { oneDark } from '@codemirror/theme-one-dark'; import postcss from 'postcs...
const postcssBundler = require('@csstools/postcss-bundler'); const postcssMinify = require('@csstools/postcss-minify'); const postcssPresetEnv = require('postcss-preset-env'); module.exports = { plugins: [ postcssBundler(), postcssPresetEnv(), postcssMinify(), ], };
const openProps = require('open-props'); const postcssBundler = require('@csstools/postcss-bundler'); const postcssCustomMedia = require('postcss-custom-media'); const postcssGlobalData = require('@csstools/postcss-global-data'); const postcssJitProps = require('postcss-jit-props'); const postcssMinify = require('@csst...
import isValidReplacement from './is-valid-replacement.mjs'; function generateHandler(replaceWith) { let selector; let remove; let add; const lastElements = []; if (replaceWith[0] === '.') { selector = replaceWith.slice(1); remove = (el) => el.classList.remove(selector); add = (el) => el.classList.add(selec...
import isValidReplacement from './is-valid-replacement.mjs'; const CSS_CLASS_LOADED = 'js-blank-pseudo'; // form control elements selector function isFormControlElement(element) { if (element.nodeName === 'INPUT' || element.nodeName === 'SELECT' || element.nodeName === 'TEXTAREA') { return true; } return false;...
const PREFERS_COLOR_SCHEME_REGEX = /prefers-color-scheme:/i; const prefersColorSchemeInit = (initialColorScheme, options) => { // OPTIONS { if (!options) { options = {}; } options = { debug: (!!options.debug) || false, }; } const mediaQueryString = '(prefers-color-scheme: dark)'; const mediaQueryL...
import '@mrhenry/core-web/modules/~element-qsa-has.js'; import extractEncodedSelectors from './encode/extract.mjs'; import encodeCSS from './encode/encode.mjs'; function hasNativeSupport() { try { if (!('CSS' in self) || !('supports' in self.CSS) || !self.CSS.supports('selector(:has(div))')) { return false; } ...
import valuesParser from 'postcss-value-parser'; import isEnvFunc from './is-env-func'; /** * @param {string} originalValue * @param variables * @returns {string} returns a value replaced with environment variables */ export default (originalValue, variables) => { // get the ast of the original value const ast =...
import fs from 'node:fs'; import path from 'node:path'; import url from 'node:url'; /** * Import Custom Properties from Object * @param {{environmentVariables: Record<string, string>, 'environment-variables': Record<string, string>}} object * @returns {Object} */ function importEnvironmentVariablesFromObject(objec...
import getReplacedValue from './lib/get-replaced-value'; import importEnvironmentVariablesFromSources from './lib/import-from'; /** * @param {{importFrom?: string[]}} opts * @returns {import('postcss').Plugin} */ const creator = (opts) => { // sources to import environment variables from const importFrom = [].con...
set -e # Zero out result file echo '' > ./test/cli/basic.result.css; csstools-cli css-has-pseudo ./test/cli/basic.css --output ./test/cli/basic.result.css # Check result git --no-pager diff --no-index --word-diff ./test/cli/basic.expect.css ./test/cli/basic.result.css echo "pass csstools-cli"
# Run tests as if local. unset GITHUB_ACTIONS # if node version begins with "v16" then exit 0; if [[ "$(node --version)" =~ ^v16 ]]; then echo "Skip tests on node v16" exit 0 fi # region:Basic set +e echo "" > ./test-self/basic.result.log node --test-reporter ./test/_dot-reporter.cjs ./test/basic.mjs > ./test-sel...
#!/usr/bin/env bash set -e if [ "$(uname)" == "Darwin" ]; then # Darwin cmd find . -type f -perm +0111 | node .github/bin/detect-executable-files/to-github-annotations.mjs else # Linux cmd find . -type f -perm /u=x,g=x,o=x | node .github/bin/detect-executable-files/to-github-annotations.mjs fi
const CACHE_NAME = 'cache'; self.addEventListener("fetch", function(e) { e.respondWith(caches.open(CACHE_NAME).then(function(s) { return s.match(e.request).then(function(t) { // console.log("cache request: " + e.request.url); var n = fetch(e.request).then(function(t) { ...
module.exports = { siteMetadata: { title: `e-shop`, description: `Simple e-commerce website in react.`, author: `@james-muriithi`, siteUrl: "https://my-online-shop.netlify.app/", siteLanguage: `en`, ogLanguage: `en`, headline: `E-Shop`, twitter: `@jam_es_muriithi`, facebook: `james...
import React from "react" import { Link } from "gatsby" import Layout from "../components/layout" import SEO from "../components/seo" const SecondPage = () => ( <Layout> <SEO title="Page two" /> <h1>Hi from the second page</h1> <p>Welcome to page 2</p> <Link to="/">Go back to the homepage</Link> <...
import React from "react" import Layout from "../components/layout" import SEO from "../components/seo" const NotFoundPage = () => ( <Layout> <SEO title="404: Not found" /> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </Layout> ) export default NotFoundPage
import React from "react" import { Provider } from "react-redux" import store from "../store" import App from "../App" const IndexPage = () => ( <Provider store={store}> <App /> </Provider> ) export default IndexPage
import React from "react" import { Provider } from "react-redux" import store from "../store" import BreadCrumb from "../components/shoppingCart/BreadCrumb" import Recommended from "../components/recommendationSector/Recommended" import Layout from "../components/layout/Layout" import SEO from "../components/seo/Seo"...
import React from "react" import { Provider } from "react-redux" import store from "../store" import BreadCrumb from "../components/shoppingCart/BreadCrumb" import Recommended from "../components/recommendationSector/Recommended" import Layout from "../components/layout/Layout" import SEO from "../components/seo/Seo"...
import React, { useState } from "react" import { Link } from "gatsby" import { Collapse, Navbar, NavbarToggler, Nav, NavItem, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem, } from "reactstrap" import { connect } from "react-redux" import emptyCartSvg from "../../images/empty_cart.s...
import React from "react" import { Row, Col } from "reactstrap" import "./Benefits.css" export default function Benefits() { return ( <div className="benefit-items mx-3"> <Row> <Col md="4"> <div className="single-benefit"> <div className="sb-icon"> <img src={req...
import React from "react" import { Container, Row } from "reactstrap" import ProductCard from "../productCard/ProductCard" import styled from "styled-components" import { items } from "../../data"; export default function Products() { const Heading = styled.h3` font-size: 20px; color: #171717; margin-ri...
import React, {useEffect, useState } from "react" import { connect } from "react-redux" import { toggleWishlist } from "../../actions/wishListActions"; import "./Like.css" function Like(props) { const [checked, setChecked] = useState(false) const animate = () => { setChecked(prevState => !prevState); pr...
import React from "react" import { Container, Row } from "reactstrap" import ProductCard from "../productCard/ProductCard" import styled from "styled-components" import { recommendedItems as items } from "../../data"; export default function Products({ title }) { const Heading = styled.h3` font-size: 20px; ...
import React from "react" import SwipeableBottomSheet from "../react-swipeable-bottom-sheet/SwipeableBottomSheet" export default function ProductSheet(props) { return ( <SwipeableBottomSheet overflowHeight={0} {...props} style={{ zIndex: "100" }} bodyStyle={{ borderTopLeftRadius: ...
/** * Layout component that queries for data * with Gatsby's useStaticQuery component * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import PropTypes from "prop-types" import { useStaticQuery, graphql } from "gatsby" import Header from "./header" import "./layout.css" cons...
import React from "react" import PropTypes from "prop-types" import Navbar from "../navbar/Navbar" import "./layout.css" import Footer from "../footer/Footer" const Layout = ({ children }) => { return ( <> <div style={{ overflowX: "hidden" }}> <Navbar /> <main>{children}</main> <...
import React from "react" import { useStaticQuery, graphql } from "gatsby" import Img from "gatsby-image" /* * This component is built using `gatsby-image` to automatically serve optimized * images with lazy loading and reduced file sizes. The image is loaded using a * `useStaticQuery`, which allows us to load the ...
import PropTypes from "prop-types" import React from "react" import Helmet from "react-helmet" const Facebook = ({ url, name, type, title, desc, image, locale }) => ( <Helmet> {name && <meta property="og:site_name" content={name} />} <meta property="og:locale" content={locale} /> <meta property="og:url" ...
/** * SEO component that queries for data with * Gatsby's useStaticQuery React hook * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import PropTypes from "prop-types" import Helmet from "react-helmet" import { useStaticQuery, graphql } from "gatsby" import Facebook from "./...
import PropTypes from "prop-types" import React from "react" import Helmet from "react-helmet" const Twitter = ({ type, username, title, desc, image }) => ( <Helmet> {username && <meta name="twitter:creator" content={username} />} <meta name="twitter:card" content={type} /> <meta name="twitter:title" con...
import React from "react" import { Container, Row, Col } from "reactstrap" import { connect } from "react-redux" import emptyCartSvg from "../../images/empty_cart.svg" import mpesa from "../../images/mpesa.png" import "./Checkout.css" function Checkout(props) { return ( <section className="checkout-section pad"...
import React, { Component } from "react" import PropTypes from "prop-types" class HeightUpdater extends Component { constructor(props) { super(props) this.globalWindow = typeof window !== "undefined" && window this.onWindowResize = this.onWindowResize.bind(this) } onWindowResize() { const heigh...
import React, { Component } from "react" import PropTypes from "prop-types" class ScrollToTop extends Component { componentDidMount() { this.props.element().scrollTop = 0 } render() { return null } } ScrollToTop.propTypes = { element: PropTypes.func.isRequired, } export default ScrollToTop
import React, { Component } from "react" import PropTypes from "prop-types" import SwipeableViews from "react-swipeable-views" import HeightUpdater from "./HeightUpdater" import ScrollToTop from "./ScrollToTop" class SwipeableBottomSheet extends Component { constructor(props) { super(props) this.onHeightCh...
/** * SEO component that queries for data with * Gatsby's useStaticQuery React hook * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import PropTypes from "prop-types" import { Helmet } from "react-helmet" import { useStaticQuery, graphql } from "gatsby" function SEO({ descr...
import React from "react" import { Link } from "gatsby" import { Container, Row, Col } from "reactstrap" import { connect } from "react-redux" import { removeFromCart, addToCart, decreaseQuantity, } from "../../actions/cartActions" import emptyCartSvg from "../../images/empty_cart.svg" import "./cart.css" funct...
import React from "react" import { Link } from "gatsby" import { Container, Row, Col } from "reactstrap" import "./BreadCrumb.css" export default function BreadCrumb({ current, children }) { return ( <div className="breacrumb-section"> <Container> <Row> <Col lg="12"> <div cla...
import React from "react" import { Container, Row, Col } from "reactstrap" import { Link } from "gatsby" import "./Footer.css" export default function Footer() { return ( <footer className="footer-section"> <Container> <Row> <Col lg="4"> <div className="footer-left"> ...
import { Link } from "gatsby" import PropTypes from "prop-types" import React from "react" const Header = ({ siteTitle }) => ( <header style={{ background: `rebeccapurple`, marginBottom: `1.45rem`, }} > <div style={{ margin: `0 auto`, maxWidth: 960, padding: `1...
import React from "react" import "./Stars.css" import { Link } from "gatsby" export default function Stars({ rating }) { // total number of stars const starTotal = 5 rating = rating ? rating : (Math.random() * (5 - 1)).toPrecision(2) const starPercentage = (rating / starTotal) * 100 return ( <div classNa...
import React, { useState } from "react" import { Carousel, CarouselItem, CarouselControl, CarouselIndicators, CarouselCaption, Row, Col, } from "reactstrap" import Image from "./SliderImage" const items = [ { src: "slider01.jpg", altText: "Slide 1", }, { src: "slider02.jpg", altText...
import React from "react" import { useStaticQuery, graphql } from "gatsby" import styled from "styled-components" import Img from "gatsby-image" const SliderImage = ({ src, alt }) => { const data = useStaticQuery(graphql` query { images: allFile { edges { node { relativePath ...
import React, { useState } from "react" import { Col } from "reactstrap" import { Link } from "gatsby" import "lazysizes" import "lazysizes/plugins/attrchange/ls.attrchange" import "lazysizes/plugins/parent-fit/ls.parent-fit" import { connect } from "react-redux" import "./ProductCard.css" import Like from "../favouri...
import React from "react" import { Container, Row, Col } from "reactstrap" import "./Categories.css" export default function Categories() { return ( <div className="banner-section"> <Container fluid> <Row> <Col lg="4"> <div className="single-banner"> <img src={re...
import { ADD_TO_CART, REMOVE_FROM_CART, DECREASE_QUANTITY, } from "../actions/types" const initialState = { cartItems: [], total: 0, } const cartReducer = (state = initialState, action) => { switch (action.type) { case ADD_TO_CART: let newTotal = state.total + action.item.price let existe...
import { TOGGLE_TO_WISHLIST, } from "../actions/types" const initialState = { wishlistItems: [] } const wishlistReducer = (state = initialState, action) => { switch (action.type) { case TOGGLE_TO_WISHLIST: let existed_item = state.wishlistItems.find( item => action.ite...
import React from "react" import Layout from "../components/layout/Layout" import SEO from "../components/seo/Seo" import "bootstrap/dist/css/bootstrap.min.css" import "font-awesome/css/font-awesome.min.css" import HomeCarousel from "../components/carousel/HomeCarousel" import Products from "../components/productsSec...
import { ADD_TO_CART, REMOVE_FROM_CART, DECREASE_QUANTITY } from "./types" export const addToCart = item => dispatch => { dispatch({ type: ADD_TO_CART, item, }) } export const removeFromCart = item => dispatch => { dispatch({ type: REMOVE_FROM_CART, item, }) } export const decreaseQuantity = ...
import { applyMiddleware, compose, createStore } from "redux" import thunk from "redux-thunk" import rootReducer from "./reducers" let initialState = {} const middleware = [thunk] const globalWindow = typeof window !== "undefined" && window if (globalWindow) { initialState = localStorage.getItem("myCart") ? JS...
export const items = [ { src: require("../images/products/product-1.jpg"), name: "Sweater", id: 1, price: 200, description: "A sweater that keeps you warm.", color: "yellow", label: "New", rating: "4.5", sizes: [ "xxl", "xxl", "xl" ], }, ...
#!/bin/bash export TLS_CERT="jory-dev-tls" export TLS_NAMESPACE="network" CERT_DIR="/tmp/cert" CERT_TMP="$CERT_DIR/tmp" CERT_JSON="$CERT_DIR/certificate/certificate-tls.json" CLUSTER="${1:-utility}" DESTINATION="${2:-caddy}" # Set default values based on DESTINATION if [[ "$DESTINATION" == "caddy" ]]; then SERVER="...
#!/usr/bin/env bash NAMESPACE=$1 CLUSTER=${2:-main} function delete_namespace () { echo "Deleting namespace $NAMESPACE" kubectl --context $CLUSTER get namespace $NAMESPACE -o json > tmp.json sed -i 's/"kubernetes"//g' tmp.json kubectl --context $CLUSTER replace --raw "/api/v1/namespaces/$NAMESPACE/fin...
#!/bin/bash # Issue local Talos shutdown command talosctl shutdown --context main # Wait a few seconds to allow local shutdown to initiate (optional but recommended) sleep 5 # Remotely shutdown the Linux server ssh root@voyager "sudo shutdown -h now" exit 0
#!/bin/bash # Extract essential fields EVENT_TYPE=${1:-} ACTION_TYPE=${2:-} REPOSITORY_NAME=${3:-} REPOSITORY_OWNER=${4:-} PR_NUMBER=${5:-} PR_TITLE=${6:-} PR_USER=${7:-} PR_URL=${8:-} PR_BODY=${9:-} echo "$(date): Received GitHub event: $EVENT_TYPE action: $ACTION_TYPE for $REPOSITORY_NAME issue/PR: $PR_NUMBER" >&2 ...
#!/usr/bin/env bash set -euo pipefail # Incoming arguments JOB=${1:-} NAMESPACE=${2:-} PROJECT=${3:-} RENOVATE_OPERATOR_WEBHOOK_URL=${4:-} # URL encode the project name PROJECT=$(echo "${PROJECT}" | jq -Rr @uri) curl -v -X POST \ "${RENOVATE_OPERATOR_WEBHOOK_URL}/webhook/v1/schedule?job=${JOB}&namespace=${NAMESPAC...
#!/usr/bin/env bash set -Eeuo pipefail # Environment variables set by the user CROSS_SEED_HOST="${CROSS_SEED_HOST:?}" CROSS_SEED_API_KEY="${CROSS_SEED_API_KEY:?}" CROSS_SEED_SLEEP_INTERVAL="${CROSS_SEED_SLEEP_INTERVAL:-30}" # Environment variables set by sabnzbd SAB_COMPLETE_DIR="${SAB_COMPLETE_DIR:?}" SAB_PP_STATUS=...
#!/usr/bin/env bash set -euo pipefail # Incoming environment variables EVENT_TYPE="${sonarr_eventtype:-}" SERIES_ID="${sonarr_series_id:-}" # Only proceed for "Grab" events with valid series ID [[ "${EVENT_TYPE}" == "Grab" && -n "${SERIES_ID}" ]] || exit 0 # Required environment variables : "${SONARR__AUTH__APIKEY:?...
import Foundation import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let window = UIWindow(frame...
import UIKit import Toaster import Photos final class RootViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let button = UIButton(type: .system) button.setTitle("Show", for: .normal) button.sizeToFit() button.addTarget(self, action: #selector(self.showButt...
// // ToasterTests.swift // ToasterTests // // Created by Lois Di Qual on 10/16/17. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import XCTest @testable import Toaster class ToasterTests: XCTestCase { override func tearDown() { super.tearDown() ToastCenter.default.cancelAll()...
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "Toaster", platforms: [ .iOS(.v9) ], products: [ .library( name: "Toaster", targets: ["Toaster"]), ], targets: [ .target( name: "Toaster", d...
// // KeyboardObserver.swift // Toaster // // Created by SeongHo Hong on 28/08/2019. // Copyright © 2019 Suyeol Jeon. All rights reserved. // import UIKit final class KeyboardObserver { static let shared = KeyboardObserver() private(set) var didKeyboardShow: Bool = false init() { #if swift(>=4....
import UIKit open class ToastWindow: UIWindow { // MARK: - Public Property public static let shared = ToastWindow(frame: UIScreen.main.bounds, mainWindow: UIApplication.shared.keyWindow) override open var rootViewController: UIViewController? { get { guard !self.isShowing else { isShowing ...
import UIKit open class ToastCenter: NSObject { // MARK: Properties private let queue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 return queue }() open var currentToast: Toast? { return self.queue.operations.first { !$0.isCancelled && !$0.isFinished...
// // UIApplication+Load.swift // Toaster // // Created by SeongHo Hong on 28/08/2019. // Copyright © 2019 Suyeol Jeon. All rights reserved. // import UIKit extension UIApplication { open override var next: UIResponder? { UIApplication.runOnce return super.next } private static let runOnce: Vo...
import UIKit public class Delay: NSObject { @available(*, unavailable) private override init() {} // `short` and `long` (lowercase) are reserved words in Objective-C // so we capitalize them instead of the default `short_` and `long_` @objc(Short) public static let short: TimeInterval = 2.0 @objc(Long) publi...
import UIKit open class ToastView: UIView { // MARK: Properties open var text: String? { get { return self.textLabel.text } set { self.textLabel.text = newValue } } open var attributedText: NSAttributedString? { get { return self.textLabel.attributedText } set { self.textLabel.attributedText...
import pytest import set_filter_policy SUBSCRIPTION_ARN = 'theSubscription' FILTER_POLICY = '{"pet": ["dog", "cat"]}' def test_create(mocker): mocker.patch.object(set_filter_policy, 'SNS') response = set_filter_policy.create(_mock_event(), None) assert response == { 'Status': 'SUCCESS', ...
"""Setup unit test environment.""" import sys import os import test_constants # make sure tests can import the app code my_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, my_path + '/../../src/') # set expected config environment variables to test constants os.environ['AWS_DEFAULT_REGION'] = 'u...
"""Special initializations for Lambda functions. This file must be imported as the first import in any file containing a Lambda function handler method. """ import sys # add packaged dependencies to search path sys.path.append('lib') # imports of library dependencies must come after setting up the dependency search...
"""Lambda handler for custom resource for setting SNS subscription filter policy.""" # must be the first import in files with lambda function handlers import lambdainit # noqa: F401 import boto3 import cfn_resource import lambdalogging LOG = lambdalogging.getLogger(__name__) SNS = boto3.client('sns') handler = cfn...
"""Lambda logging helper. Returns a Logger with log level set based on env variables. """ import logging import config # translate log level from string to numeric value LOG_LEVEL = getattr(logging, config.LOG_LEVEL) if hasattr(logging, config.LOG_LEVEL) else logging.INFO def getLogger(name): """Return a logg...
"""Setup unit test environment.""" import sys import os import test_constants # make sure tests can import the app code my_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, my_path + '/../../src/') # set expected config environment variables to test constants os.environ['AWS_DEFAULT_REGION'] = 'u...
import pytest import json import process_records def test_handler(mocker): mocker.patch.object(process_records, 'TABLE') checkout_events = [ { 'id': 1, 'date': '2018-12-15T23:41:11-08:00', 'status': 'confirmed', 'customer': { 'id': 100 ...
"""Special initializations for Lambda functions. This file must be imported as the first import in any file containing a Lambda function handler method. """ import sys # add packaged dependencies to search path sys.path.append('lib') # imports of library dependencies must come after setting up the dependency search...
"""Lambda logging helper. Returns a Logger with log level set based on env variables. """ import logging import config # translate log level from string to numeric value LOG_LEVEL = getattr(logging, config.LOG_LEVEL) if hasattr(logging, config.LOG_LEVEL) else logging.INFO def getLogger(name): """Return a logg...
"""Lambda function handler.""" # must be the first import in files with lambda function handlers import lambdainit # noqa: F401 import boto3 from decimal import Decimal import json import config import lambdalogging LOG = lambdalogging.getLogger(__name__) TABLE = boto3.resource('dynamodb').Table(config.TABLE_NAME...
import pytest import json import base64 import remove_sensitive_data def test_handler(): records = [ { 'id': 123, 'date': '2018-12-15T23:41:11-08:00', 'status': 'confirmed', 'customer': { 'id': 65144, 'name': 'John Doe', ...
"""Setup unit test environment.""" import sys import os import test_constants # make sure tests can import the app code my_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, my_path + '/../../src/') # set expected config environment variables to test constants os.environ['AWS_DEFAULT_REGION'] = 'u...
import json import pytest import api def test_checkout(mocker): mocker.patch.object(api, 'TOPIC') api.TOPIC.publish.return_value = {'MessageId': 'foo'} message = json.dumps({ 'payment': { 'amount': 99.99 } }) api_event = { 'body': message } response =...
"""Special initializations for Lambda functions. This file must be imported as the first import in any file containing a Lambda function handler method. """ import sys # add packaged dependencies to search path sys.path.append('lib') # imports of library dependencies must come after setting up the dependency search...
"""Lambda function handler.""" # must be the first import in files with lambda function handlers import lambdainit # noqa: F401 import boto3 import json import config import lambdalogging LOG = lambdalogging.getLogger(__name__) TOPIC = boto3.resource('sns').Topic(config.TOPIC_ARN) def checkout(event, context): ...
"""Lambda logging helper. Returns a Logger with log level set based on env variables. """ import logging import config # translate log level from string to numeric value LOG_LEVEL = getattr(logging, config.LOG_LEVEL) if hasattr(logging, config.LOG_LEVEL) else logging.INFO def getLogger(name): """Return a logg...
"""Lambda function handler.""" # must be the first import in files with lambda function handlers import lambdainit # noqa: F401 import base64 import json import lambdalogging LOG = lambdalogging.getLogger(__name__) def handler(event, context): """Remove sensitive data from checkout events.""" LOG.debug('...
"""Setup unit test environment.""" import sys import os import test_constants # make sure tests can import the app code my_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, my_path + '/../../src/') # set expected config environment variables to test constants os.environ['AWS_DEFAULT_REGION'] = 'u...
import pytest import test_constants import process_records def test_handler(mocker): mocker.patch.object(process_records, 'FIREHOSE') process_records.FIREHOSE.put_record.return_value = {} event = { 'Records': [ {'body': 'foo'}, {'body': 'bar'} ] } process_...
"""Special initializations for Lambda functions. This file must be imported as the first import in any file containing a Lambda function handler method. """ import sys # add packaged dependencies to search path sys.path.append('lib') # imports of library dependencies must come after setting up the dependency search...
"""Lambda logging helper. Returns a Logger with log level set based on env variables. """ import logging import config # translate log level from string to numeric value LOG_LEVEL = getattr(logging, config.LOG_LEVEL) if hasattr(logging, config.LOG_LEVEL) else logging.INFO def getLogger(name): """Return a logg...
"""Lambda handler for forwarding messages from SQS to Kinesis Firehose.""" import lambdainit # noqa: F401 import boto3 import config import lambdalogging LOG = lambdalogging.getLogger(__name__) FIREHOSE = boto3.client('firehose') def handler(event, context): """Forward SQS messages to Kinesis Firehose Delive...
"""Setup unit test environment.""" import sys import os import test_constants # make sure tests can import the app code my_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, my_path + '/../../src/') # set expected config environment variables to test constants os.environ['AWS_DEFAULT_REGION'] = 'u...
import pytest from unittest.mock import MagicMock import boto3 QUEUE_URL = 'https://queue.com' @pytest.fixture def replay_messages(mocker): mock_sqs_client = MagicMock() mock_sqs_client.get_queue_url.return_value = {'QueueUrl': QUEUE_URL} mocker.patch.object(boto3, 'client') mocker.patch.object(bot...