id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
400
<NME> shaclsquare.shacl.ttl <BEF> ADDFILE <MSG> Clean up, added SHACLSquare example <DFF> @@ -0,0 +1,176 @@ +# baseURI: http://topbraid.org/examples/shaclsquare +# imports: http://www.w3.org/ns/shacl + +# An example SHACL model about rectangles and squares, demonstrating all major +# features of SHACL with simple examples. + +# Contact: Holger Knublauch (holger@topquadrant.com) + +@prefix arg: <http://www.w3.org/ns/shacl/arg#> . +@prefix ex: <http://topbraid.org/examples/shaclsquare#> . +@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . +@prefix schema: <http://schema.org/> +@prefix sh: <http://www.w3.org/ns/shacl#> . +@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . + + +# The sh:Graph ---------------------------------------------------------------- + +<http://topbraid.org/examples/shaclsquare> + a sh:Graph ; + sh:shapesGraph <http://www.w3.org/ns/shacl> ; + rdfs:label "SHACL Square Example" ; + rdfs:comment "A simple example model demonstrating some key features of SHACL. Have a look at the ex:computeArea function, the rule attached to ex:Rectangle and the constraint attached to ex:Square." ; +. + + +# Classes --------------------------------------------------------------------- + +ex:Rectangle + a sh:ShapeClass ; + rdfs:subClassOf rdfs:Resource ; + rdfs:label "Rectangle" ; + sh:property [ + sh:predicate ex:height ; + sh:datatype xsd:integer ; + sh:minCount 1 ; + sh:maxCount 1 ; + rdfs:label "height" ; + rdfs:comment "The height of the Rectangle." ; + ] ; + sh:property [ + sh:predicate ex:width ; + sh:datatype xsd:integer ; + sh:minCount 1 ; + sh:maxCount 1 ; + rdfs:label "width" ; + rdfs:comment "The width of the Rectangle." ; + ] ; + sh:property [ + sh:predicate ex:creator ; + sh:maxCount 1 ; + sh:valueShape [ + sh:property [ + sh:predicate schema:email ; + sh:minCount 1 ; + ] ; + ] ; + sh:valueClass schema:Person ; + rdfs:label "creator" ; + rdfs:comment "The creator of the Rectangle." ; + ] ; + sh:constraint [ + a ex:PositivePropertyValueConstraint ; + arg:property ex:height ; + ] ; + sh:constraint [ + a ex:PositivePropertyValueConstraint ; + arg:property ex:width ; + ] ; +. + +ex:Square + a sh:ShapeClass ; + rdfs:label "Square" ; + rdfs:subClassOf ex:Rectangle ; + sh:constraint [ + sh:message "Width and height of a Square must be equal" ; + sh:predicate ex:width ; + sh:sparql """ + SELECT ?this (?this AS ?subject) (?width AS ?object) + WHERE { + ?this ex:width ?width . + ?this ex:height ?height . + FILTER (?width != ?height) . + } + """ ; + ] ; +. + +schema:Person + a sh:ShapeClass ; + rdfs:label "Person" ; + rdfs:subClassOf rdfs:Resource ; + sh:property [ + sh:predicate schema:email ; + sh:datatype xsd:string ; + rdfs:label "email" ; + rdfs:comment "Zero or more email addresses of the person." ; + ] ; +. + + +# Example Instances ----------------------------------------------------------- + +ex:InvalidSquare + a ex:Square ; + ex:creator ex:PersonWithoutEmail ; + ex:height 8 ; + ex:width 9 ; + rdfs:label "Invalid square" ; +. + +ex:TestRectangle + a ex:Rectangle ; + ex:creator ex:PersonWithEmail ; + ex:height 6 ; + ex:width 7 ; + rdfs:label "Test rectangle" ; +. + +ex:PersonWithoutEmail + a schema:Person ; +. + +ex:PersonWithEmail + a schema:Person ; + schema:email "john@example.com" ; +. + + +# Templates ------------------------------------------------------------------- + +ex:PositivePropertyValueConstraint + a sh:ConstraintTemplate ; + rdfs:subClassOf sh:TemplateConstraint ; + rdfs:label "Positive property value constraint" ; + rdfs:comment "A template that can be used to define a SHACL constraint on a given property (arg:property) to make sure that the values of that property are > 0." ; + sh:labelTemplate "Values of property {?property} must be > 0" ; + sh:argument [ + sh:predicate arg:property ; + sh:valueClass rdf:Property ; + rdfs:label "property" ; + rdfs:comment "The property to constrain (e.g. ex:width or ex:height)." ; + ] ; + sh:message "Property {?property} must only have positive values, but found {?object}" ; + sh:sparql """ + SELECT ?this (?this AS ?subject) (?property AS ?predicate) ?object ?property + WHERE { + ?this ?property ?object . + FILTER (?object <= 0) . + } + """ ; +. + +# Functions ------------------------------------------------------------------- + +ex:computeArea + a sh:Function ; + rdfs:subClassOf sh:Functions ; + rdfs:label "compute area" ; + rdfs:comment "Computes the area of a given rectangle (?arg1) as the product of its width and height." ; + sh:argument [ + sh:predicate sh:arg1 ; + sh:valueClass ex:Rectangle ; + rdfs:comment "The rectangle whose area to compute." ; + ] ; + sh:sparql """ + SELECT ((?width * ?height) AS ?result) + WHERE { + ?arg1 ex:width ?width . + ?arg1 ex:height ?height . + } + """ ; + sh:returnType xsd:integer ; +.
176
Clean up, added SHACLSquare example
0
.ttl
shacl
apache-2.0
TopQuadrant/shacl
401
<NME> shaclsquare.shacl.ttl <BEF> ADDFILE <MSG> Clean up, added SHACLSquare example <DFF> @@ -0,0 +1,176 @@ +# baseURI: http://topbraid.org/examples/shaclsquare +# imports: http://www.w3.org/ns/shacl + +# An example SHACL model about rectangles and squares, demonstrating all major +# features of SHACL with simple examples. + +# Contact: Holger Knublauch (holger@topquadrant.com) + +@prefix arg: <http://www.w3.org/ns/shacl/arg#> . +@prefix ex: <http://topbraid.org/examples/shaclsquare#> . +@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . +@prefix schema: <http://schema.org/> +@prefix sh: <http://www.w3.org/ns/shacl#> . +@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . + + +# The sh:Graph ---------------------------------------------------------------- + +<http://topbraid.org/examples/shaclsquare> + a sh:Graph ; + sh:shapesGraph <http://www.w3.org/ns/shacl> ; + rdfs:label "SHACL Square Example" ; + rdfs:comment "A simple example model demonstrating some key features of SHACL. Have a look at the ex:computeArea function, the rule attached to ex:Rectangle and the constraint attached to ex:Square." ; +. + + +# Classes --------------------------------------------------------------------- + +ex:Rectangle + a sh:ShapeClass ; + rdfs:subClassOf rdfs:Resource ; + rdfs:label "Rectangle" ; + sh:property [ + sh:predicate ex:height ; + sh:datatype xsd:integer ; + sh:minCount 1 ; + sh:maxCount 1 ; + rdfs:label "height" ; + rdfs:comment "The height of the Rectangle." ; + ] ; + sh:property [ + sh:predicate ex:width ; + sh:datatype xsd:integer ; + sh:minCount 1 ; + sh:maxCount 1 ; + rdfs:label "width" ; + rdfs:comment "The width of the Rectangle." ; + ] ; + sh:property [ + sh:predicate ex:creator ; + sh:maxCount 1 ; + sh:valueShape [ + sh:property [ + sh:predicate schema:email ; + sh:minCount 1 ; + ] ; + ] ; + sh:valueClass schema:Person ; + rdfs:label "creator" ; + rdfs:comment "The creator of the Rectangle." ; + ] ; + sh:constraint [ + a ex:PositivePropertyValueConstraint ; + arg:property ex:height ; + ] ; + sh:constraint [ + a ex:PositivePropertyValueConstraint ; + arg:property ex:width ; + ] ; +. + +ex:Square + a sh:ShapeClass ; + rdfs:label "Square" ; + rdfs:subClassOf ex:Rectangle ; + sh:constraint [ + sh:message "Width and height of a Square must be equal" ; + sh:predicate ex:width ; + sh:sparql """ + SELECT ?this (?this AS ?subject) (?width AS ?object) + WHERE { + ?this ex:width ?width . + ?this ex:height ?height . + FILTER (?width != ?height) . + } + """ ; + ] ; +. + +schema:Person + a sh:ShapeClass ; + rdfs:label "Person" ; + rdfs:subClassOf rdfs:Resource ; + sh:property [ + sh:predicate schema:email ; + sh:datatype xsd:string ; + rdfs:label "email" ; + rdfs:comment "Zero or more email addresses of the person." ; + ] ; +. + + +# Example Instances ----------------------------------------------------------- + +ex:InvalidSquare + a ex:Square ; + ex:creator ex:PersonWithoutEmail ; + ex:height 8 ; + ex:width 9 ; + rdfs:label "Invalid square" ; +. + +ex:TestRectangle + a ex:Rectangle ; + ex:creator ex:PersonWithEmail ; + ex:height 6 ; + ex:width 7 ; + rdfs:label "Test rectangle" ; +. + +ex:PersonWithoutEmail + a schema:Person ; +. + +ex:PersonWithEmail + a schema:Person ; + schema:email "john@example.com" ; +. + + +# Templates ------------------------------------------------------------------- + +ex:PositivePropertyValueConstraint + a sh:ConstraintTemplate ; + rdfs:subClassOf sh:TemplateConstraint ; + rdfs:label "Positive property value constraint" ; + rdfs:comment "A template that can be used to define a SHACL constraint on a given property (arg:property) to make sure that the values of that property are > 0." ; + sh:labelTemplate "Values of property {?property} must be > 0" ; + sh:argument [ + sh:predicate arg:property ; + sh:valueClass rdf:Property ; + rdfs:label "property" ; + rdfs:comment "The property to constrain (e.g. ex:width or ex:height)." ; + ] ; + sh:message "Property {?property} must only have positive values, but found {?object}" ; + sh:sparql """ + SELECT ?this (?this AS ?subject) (?property AS ?predicate) ?object ?property + WHERE { + ?this ?property ?object . + FILTER (?object <= 0) . + } + """ ; +. + +# Functions ------------------------------------------------------------------- + +ex:computeArea + a sh:Function ; + rdfs:subClassOf sh:Functions ; + rdfs:label "compute area" ; + rdfs:comment "Computes the area of a given rectangle (?arg1) as the product of its width and height." ; + sh:argument [ + sh:predicate sh:arg1 ; + sh:valueClass ex:Rectangle ; + rdfs:comment "The rectangle whose area to compute." ; + ] ; + sh:sparql """ + SELECT ((?width * ?height) AS ?result) + WHERE { + ?arg1 ex:width ?width . + ?arg1 ex:height ?height . + } + """ ; + sh:returnType xsd:integer ; +.
176
Clean up, added SHACLSquare example
0
.ttl
shacl
apache-2.0
TopQuadrant/shacl
402
<NME> manifest.ttl <BEF> ADDFILE <MSG> Tests converted to new format, all green <DFF> @@ -0,0 +1,47 @@ +@prefix dc: <http://purl.org/dc/elements/1.1/> . +@prefix ex: <http://example.org/> . +@prefix foaf: <http://xmlns.com/foaf/0.1/> . +@prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> . +@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . +@prefix sh: <http://www.w3.org/ns/shacl#> . +@prefix sht: <http://www.w3.org/ns/shacl/test-suite#> . +@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . + +<> + a mf:Manifest ; + rdfs:comment "Tests of SPARQL features" ; + rdfs:label "SPARQL Features tests" ; + mf:entries ( + <entailment-001> + <global-001> + ) +. + +<entailment-001> + a sht:Validate ; + mf:name "Test for a SPARQL constraint with RDFS entailment" ; + mf:action [ + sht:schema <entailment-001.ttl> ; + sht:data <entailment-001.ttl> ; + ] ; + mf:result [ + a sh:Error ; + sh:root ex:InvalidInstance1 ; + ] ; + mf:status sht:proposed ; +. + +<global-001> + a sht:Validate ; + mf:name "Test for a SPARQL constraint attached to the graph resource" ; + mf:action [ + sht:schema <global-001.ttl> ; + sht:data <global-001.ttl> ; + ] ; + mf:result [ + a sh:Error ; + sh:root rdfs:Resource ; + ] ; + mf:status sht:proposed ; +.
47
Tests converted to new format, all green
0
.ttl
ttl
apache-2.0
TopQuadrant/shacl
403
<NME> manifest.ttl <BEF> ADDFILE <MSG> Tests converted to new format, all green <DFF> @@ -0,0 +1,47 @@ +@prefix dc: <http://purl.org/dc/elements/1.1/> . +@prefix ex: <http://example.org/> . +@prefix foaf: <http://xmlns.com/foaf/0.1/> . +@prefix mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#> . +@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . +@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . +@prefix sh: <http://www.w3.org/ns/shacl#> . +@prefix sht: <http://www.w3.org/ns/shacl/test-suite#> . +@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . + +<> + a mf:Manifest ; + rdfs:comment "Tests of SPARQL features" ; + rdfs:label "SPARQL Features tests" ; + mf:entries ( + <entailment-001> + <global-001> + ) +. + +<entailment-001> + a sht:Validate ; + mf:name "Test for a SPARQL constraint with RDFS entailment" ; + mf:action [ + sht:schema <entailment-001.ttl> ; + sht:data <entailment-001.ttl> ; + ] ; + mf:result [ + a sh:Error ; + sh:root ex:InvalidInstance1 ; + ] ; + mf:status sht:proposed ; +. + +<global-001> + a sht:Validate ; + mf:name "Test for a SPARQL constraint attached to the graph resource" ; + mf:action [ + sht:schema <global-001.ttl> ; + sht:data <global-001.ttl> ; + ] ; + mf:result [ + a sh:Error ; + sh:root rdfs:Resource ; + ] ; + mf:status sht:proposed ; +.
47
Tests converted to new format, all green
0
.ttl
ttl
apache-2.0
TopQuadrant/shacl
404
<NME> ValidationEngine.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl.validation; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import org.apache.jena.graph.Graph; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.graph.compose.MultiUnion; import org.apache.jena.query.Dataset; import org.apache.jena.query.QuerySolution; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import org.apache.jena.sparql.path.P_Inverse; import org.apache.jena.sparql.path.P_Link; import org.apache.jena.sparql.path.Path; import org.apache.jena.sparql.path.eval.PathEval; import org.apache.jena.sparql.util.Context; import org.apache.jena.vocabulary.RDF; import org.topbraid.jenax.util.ExceptionUtil; import org.topbraid.jenax.util.JenaDatatypes; import org.topbraid.jenax.util.JenaUtil; import org.topbraid.jenax.util.RDFLabels; import org.topbraid.shacl.arq.SHACLPaths; import org.topbraid.shacl.engine.AbstractEngine; import org.topbraid.shacl.engine.Constraint; import org.topbraid.shacl.engine.SHACLScriptEngineManager; import org.topbraid.shacl.engine.Shape; import org.topbraid.shacl.engine.ShapesGraph; import org.topbraid.shacl.engine.filters.ExcludeMetaShapesFilter; import org.topbraid.shacl.expr.NodeExpression; import org.topbraid.shacl.expr.NodeExpressionFactory; import org.topbraid.shacl.model.SHNodeShape; import org.topbraid.shacl.model.SHPropertyShape; import org.topbraid.shacl.targets.InstancesTarget; import org.topbraid.shacl.targets.Target; import org.topbraid.shacl.util.FailureLog; import org.topbraid.shacl.util.SHACLPreferences; import org.topbraid.shacl.util.SHACLUtil; import org.topbraid.shacl.validation.sparql.SPARQLSubstitutions; import org.topbraid.shacl.vocabulary.DASH; import org.topbraid.shacl.vocabulary.SH; /** * A ValidationEngine uses a given shapes graph (represented via an instance of ShapesGraph) * and performs SHACL validation on a given Dataset. * * Instances of this class should be created via the ValidatorFactory. * * @author Holger Knublauch */ public class ValidationEngine extends AbstractEngine { // The currently active ValidationEngine for cases where no direct pointer can be acquired, e.g. from HasShapeFunction private static ThreadLocal<ValidationEngine> current = new ThreadLocal<>(); public static ValidationEngine getCurrent() { return current.get(); } public static void setCurrent(ValidationEngine value) { current.set(value); } // Avoids repeatedly walking up/down the class hierarchy for sh:class constraints private ClassesCache classesCache; private ValidationEngineConfiguration configuration; // Can be used to drop certain focus nodes from validation private Predicate<RDFNode> focusNodeFilter; // The inferred triples if the shapes graph declares an entailment regime private Model inferencesModel; // The label function for rendering nodes in validation results (message templates etc) private Function<RDFNode,String> labelFunction = (node -> RDFLabels.get().getNodeLabel(node)); // Avoids repeatedly fetching labels private Map<RDFNode,String> labelsCache = new ConcurrentHashMap<>(); // Can be used to collect statistical data about execution time of constraint components and shapes private ValidationProfile profile; // The resulting validation report instance private Resource report; // Number of created results, e.g. for progress monitor private int resultsCount = 0; // Avoids repeatedly fetching the value nodes of a focus node / path combination private Map<ValueNodesCacheKey,Collection<RDFNode>> valueNodes = new WeakHashMap<>(); // Number of created violations, e.g. for progress monitor private int violationsCount = 0; /** * Constructs a new ValidationEngine. * @param dataset the Dataset to operate on * @param shapesGraphURI the URI of the shapes graph (must be in the dataset) * @param shapesGraph the ShapesGraph with the shapes to validate against * @param report the sh:ValidationReport object in the results Model, or null to create a new one */ protected ValidationEngine(Dataset dataset, URI shapesGraphURI, ShapesGraph shapesGraph, Resource report) { super(dataset, shapesGraph, shapesGraphURI); setConfiguration(new ValidationEngineConfiguration()); if(report == null) { Model reportModel = JenaUtil.createMemoryModel(); reportModel.setNsPrefixes(dataset.getDefaultModel()); // This can be very expensive in some databases reportModel.withDefaultMappings(shapesGraph.getShapesModel()); this.report = reportModel.createResource(SH.ValidationReport); } else { this.report = report; } } /** * Checks if entailments are active for the current shapes graph and applies them for a given focus node. * This will only work for the sh:Rules entailment, e.g. to compute sh:values and sh:defaultValue. * If any inferred triples exist, the focus node will be returned attached to the model that includes those inferences. * The dataset used internally will also be switched to use that new model as its default model, so that if * a node gets validated it will "see" the inferred triples too. * @param focusNode the focus node * @return the focus node, possibly in a different Model than originally */ public RDFNode applyEntailments(Resource focusNode) { Model shapesModel = dataset.getNamedModel(shapesGraphURI.toString()); if(shapesModel.contains(null, SH.entailment, SH.Rules)) { // Create union of data model and inferences if called for the first time if(inferencesModel == null) { inferencesModel = JenaUtil.createDefaultModel(); Model dataModel = dataset.getDefaultModel(); MultiUnion multiUnion = new MultiUnion(new Graph[]{ dataModel.getGraph(), inferencesModel.getGraph() }); multiUnion.setBaseGraph(dataModel.getGraph()); dataset.setDefaultModel(ModelFactory.createModelForGraph(multiUnion)); } // Apply sh:values rules Map<Property,RDFNode> defaultValueMap = new HashMap<>(); for(SHNodeShape nodeShape : SHACLUtil.getAllShapesAtNode(focusNode)) { if(!nodeShape.hasProperty(SH.deactivated, JenaDatatypes.TRUE)) { for(SHPropertyShape ps : nodeShape.getPropertyShapes()) { if(!ps.hasProperty(SH.deactivated, JenaDatatypes.TRUE)) { Resource path = ps.getPath(); if(path instanceof Resource) { Statement values = ps.getProperty(SH.values); if(values != null) { NodeExpression ne = NodeExpressionFactory.get().create(values.getObject()); ne.eval(focusNode, this).forEachRemaining(v -> inferencesModel.getGraph().add(Triple.create(focusNode.asNode(), path.asNode(), v.asNode()))); } Statement defaultValue = ps.getProperty(SH.defaultValue); if(defaultValue != null) { defaultValueMap.put(JenaUtil.asProperty(path), defaultValue.getObject()); } } } } } } // Add sh:defaultValue where needed Model dataModel = dataset.getDefaultModel(); // This is now the union model Resource newFocusNode = focusNode.inModel(dataModel); for(Property predicate : defaultValueMap.keySet()) { if(!newFocusNode.hasProperty(predicate)) { NodeExpression ne = NodeExpressionFactory.get().create(defaultValueMap.get(predicate)); ne.eval(focusNode, this).forEachRemaining(v -> inferencesModel.add(focusNode, predicate, v)); } } return newFocusNode; } return focusNode; } public void addResultMessage(Resource result, Literal message, QuerySolution bindings) { result.addProperty(SH.resultMessage, SPARQLSubstitutions.withSubstitutions(message, bindings, getLabelFunction())); } // Note: does not set sh:path public Resource createResult(Resource type, Constraint constraint, RDFNode focusNode) { Resource result = report.getModel().createResource(type); report.addProperty(SH.result, result); result.addProperty(SH.resultSeverity, constraint.getSeverity()); result.addProperty(SH.sourceConstraintComponent, constraint.getComponent()); result.addProperty(SH.sourceShape, constraint.getShapeResource()); if(focusNode != null) { result.addProperty(SH.focusNode, focusNode); } checkMaximumNumberFailures(constraint); resultsCount++; return result; } public Resource createValidationResult(Constraint constraint, RDFNode focusNode, RDFNode value, Supplier<String> defaultMessage) { Resource result = createResult(SH.ValidationResult, constraint, focusNode); if(value != null) { result.addProperty(SH.value, value); } if(!constraint.getShape().isNodeShape()) { result.addProperty(SH.resultPath, SHACLPaths.clonePath(constraint.getShapeResource().getPath(), result.getModel())); } Collection<RDFNode> messages = constraint.getMessages(); if(messages.size() > 0) { messages.stream().forEach(message -> result.addProperty(SH.resultMessage, message)); } else if(defaultMessage != null) { String m = defaultMessage.get(); if(m != null) { result.addProperty(SH.resultMessage, m); } } return result; } private void checkMaximumNumberFailures(Constraint constraint) { if (SH.Violation.equals(constraint.getShape().getSeverity())) { this.violationsCount++; if (configuration.getValidationErrorBatch() != -1 && violationsCount >= configuration.getValidationErrorBatch()) { throw new MaximumNumberViolations(violationsCount); } } } public ClassesCache getClassesCache() { return classesCache; } public ValidationEngineConfiguration getConfiguration() { return configuration; } public String getLabel(RDFNode node) { return labelsCache.computeIfAbsent(node, n -> getLabelFunction().apply(n)); } public Function<RDFNode,String> getLabelFunction() { return labelFunction; } public ValidationProfile getProfile() { return profile; } /** * Gets the validation report as a Resource in the report Model. * @return the report Resource */ public Resource getReport() { return report; } /** * Gets a Set of all shapes that should be evaluated for a given resource. * @param focusNode the focus node to get the shapes for * @param dataset the Dataset containing the resource * @param shapesModel the shapes Model * @return a Set of shape resources */ private Set<Resource> getShapesForNode(RDFNode focusNode, Dataset dataset, Model shapesModel) { Set<Resource> shapes = new HashSet<>(); for(Shape rootShape : shapesGraph.getRootShapes()) { for(Target target : rootShape.getTargets()) { if(!(target instanceof InstancesTarget)) { if(target.contains(dataset, focusNode)) { shapes.add(rootShape.getShapeResource()); } } } } // rdf:type / sh:targetClass if(focusNode instanceof Resource) { for(Resource type : JenaUtil.getAllTypes((Resource)focusNode)) { if(JenaUtil.hasIndirectType(type.inModel(shapesModel), SH.Shape)) { shapes.add(type); } for(Statement s : shapesModel.listStatements(null, SH.targetClass, type).toList()) { shapes.add(s.getSubject()); } } } return shapes; } public ValidationReport getValidationReport() { return new ResourceValidationReport(report); } public Collection<RDFNode> getValueNodes(Constraint constraint, RDFNode focusNode) { if(constraint.getShape().isNodeShape()) { return Collections.singletonList(focusNode); } else { // We use a cache here because many shapes contains for example both sh:datatype and sh:minCount, and fetching // the value nodes each time may be expensive, esp for sh:minCount/maxCount constraints. ValueNodesCacheKey key = new ValueNodesCacheKey(focusNode, constraint.getShape().getPath()); return valueNodes.computeIfAbsent(key, k -> getValueNodesHelper(focusNode, constraint)); } } private Collection<RDFNode> getValueNodesHelper(RDFNode focusNode, Constraint constraint) { Property predicate = constraint.getShape().getPredicate(); if(predicate != null) { List<RDFNode> results = new LinkedList<>(); if(focusNode instanceof Resource) { Iterator<Statement> it = ((Resource)focusNode).listProperties(predicate); while(it.hasNext()) { results.add(it.next().getObject()); } } return results; } else { Path jenaPath = constraint.getShape().getJenaPath(); if(jenaPath instanceof P_Inverse && ((P_Inverse)jenaPath).getSubPath() instanceof P_Link) { List<RDFNode> results = new LinkedList<>(); Property inversePredicate = ResourceFactory.createProperty(((P_Link)((P_Inverse)jenaPath).getSubPath()).getNode().getURI()); Iterator<Statement> it = focusNode.getModel().listStatements(null, inversePredicate, focusNode); while(it.hasNext()) { results.add(it.next().getSubject()); } return results; } Set<RDFNode> results = new HashSet<>(); Iterator<Node> it = PathEval.eval(focusNode.getModel().getGraph(), focusNode.asNode(), jenaPath, Context.emptyContext); while(it.hasNext()) { Node node = it.next(); results.add(focusNode.getModel().asRDFNode(node)); } return results; } } /** * Validates a given list of focus nodes against a given Shape, and stops as soon * as one validation result is reported. No results are recorded. * @param focusNodes the nodes to validate * @param shape the sh:Shape to validate against * @return true if there were no validation results, false for violations */ public boolean nodesConformToShape(List<RDFNode> focusNodes, Node shape) { if(!shapesGraph.isIgnored(shape)) { Resource oldReport = report; report = JenaUtil.createMemoryModel().createResource(); try { Shape vs = shapesGraph.getShape(shape); if(!vs.isDeactivated()) { boolean nested = SHACLScriptEngineManager.get().begin(); try { for(Constraint constraint : vs.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); if(report.hasProperty(SH.result)) { return false; } } } finally { SHACLScriptEngineManager.get().end(nested); } } } finally { this.report = oldReport; } } return true; } public void setClassesCache(ClassesCache value) { this.classesCache = value; } /** * Sets a filter that can be used to skip certain focus node from validation. * The filter must return true if the given candidate focus node shall be validated, * and false to skip it. * @param value the new filter */ public void setFocusNodeFilter(Predicate<RDFNode> value) { this.focusNodeFilter = value; } public void setLabelFunction(Function<RDFNode,String> value) { this.labelFunction = value; } public void updateConforms() { boolean conforms = true; StmtIterator it = report.listProperties(SH.result); while(it.hasNext()) { Statement s = it.next(); if(s.getResource().hasProperty(RDF.type, SH.ValidationResult)) { conforms = false; it.close(); break; } } if(report.hasProperty(SH.conforms)) { report.removeAll(SH.conforms); } report.addProperty(SH.conforms, conforms ? JenaDatatypes.TRUE : JenaDatatypes.FALSE); } /** * Validates all target nodes against all of their shapes. * To further narrow down which nodes to validate, use {@link #setFocusNodeFilter(Predicate)}. * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateAll() throws InterruptedException { List<Shape> rootShapes = shapesGraph.getRootShapes(); return validateShapes(rootShapes); } /** * Validates a given focus node against all of the shapes that have matching targets. * @param focusNode the node to validate * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateNode(Node focusNode) throws InterruptedException { Model shapesModel = dataset.getNamedModel(shapesGraphURI.toString()); RDFNode focusRDFNode = dataset.getDefaultModel().asRDFNode(focusNode); Set<Resource> shapes = getShapesForNode(focusRDFNode, dataset, shapesModel); boolean nested = SHACLScriptEngineManager.get().begin(); try { for(Resource shape : shapes) { if(monitor != null && monitor.isCanceled()) { throw new InterruptedException(); } validateNodesAgainstShape(Collections.singletonList(focusRDFNode), shape.asNode()); } } finally { SHACLScriptEngineManager.get().end(nested); } return report; } /** * Validates a given list of focus node against a given Shape. * @param focusNodes the nodes to validate * @param shape the sh:Shape to validate against * @return an instance of sh:ValidationReport in the results Model */ public Resource validateNodesAgainstShape(List<RDFNode> focusNodes, Node shape) { if(!shapesGraph.isIgnored(shape)) { Shape vs = shapesGraph.getShape(shape); if(!vs.isDeactivated()) { boolean nested = SHACLScriptEngineManager.get().begin(); ValidationEngine oldEngine = current.get(); current.set(this); try { for(Constraint constraint : vs.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); } } finally { current.set(oldEngine); SHACLScriptEngineManager.get().end(nested); } } } return report; } /** * Validates all target nodes of a given collection of shapes against these shapes. * To further narrow down which nodes to validate, use {@link #setFocusNodeFilter(Predicate)}. * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateShapes(Collection<Shape> shapes) throws InterruptedException { boolean nested = SHACLScriptEngineManager.get().begin(); try { if(monitor != null) { monitor.beginTask("Validating " + shapes.size() + " shapes", shapes.size()); } if(classesCache == null) { // If we are doing everything then the cache should be used, but not for validation of individual focus nodes classesCache = new ClassesCache(); } int i = 0; for(Shape shape : shapes) { if(monitor != null) { String label = "Shape " + (++i) + ": " + getLabelFunction().apply(shape.getShapeResource()); if(resultsCount > 0) { label = "" + resultsCount + " results. " + label; } monitor.subTask(label); } Collection<RDFNode> focusNodes = shape.getTargetNodes(dataset); if(focusNodeFilter != null) { List<RDFNode> filteredFocusNodes = new LinkedList<>(); for(RDFNode focusNode : focusNodes) { if(focusNodeFilter.test(focusNode)) { filteredFocusNodes.add(focusNode); } } focusNodes = filteredFocusNodes; } if(!focusNodes.isEmpty()) { for(Constraint constraint : shape.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); } } if(monitor != null) { monitor.worked(1); if(monitor.isCanceled()) { throw new InterruptedException(); } } } } catch(MaximumNumberViolations ex) { // Ignore as this is just our way to stop validation when max number of violations is reached } finally { SHACLScriptEngineManager.get().end(nested); } updateConforms(); return report; } protected void validateNodesAgainstConstraint(Collection<RDFNode> focusNodes, Constraint constraint) { if(configuration != null && configuration.isSkippedConstraintComponent(constraint.getComponent())) { return; } ConstraintExecutor executor; try { executor = constraint.getExecutor(); } catch(Exception ex) { Resource result = createResult(DASH.FailureResult, constraint, constraint.getShapeResource()); result.addProperty(SH.resultMessage, "Failed to create validator: " + ExceptionUtil.getStackTrace(ex)); return; } if(executor != null) { if(SHACLPreferences.isProduceFailuresMode()) { try { executor.executeConstraint(constraint, this, focusNodes); } catch(Exception ex) { Resource result = createResult(DASH.FailureResult, constraint, constraint.getShapeResource()); result.addProperty(SH.resultMessage, "Exception during validation: " + ExceptionUtil.getStackTrace(ex)); } } else { executor.executeConstraint(constraint, this, focusNodes); } } else { FailureLog.get().logWarning("No suitable validator found for constraint " + constraint); } } public void setConfiguration(ValidationEngineConfiguration configuration) { this.configuration = configuration; if(!configuration.getValidateShapes()) { shapesGraph.setShapeFilter(new ExcludeMetaShapesFilter()); } } public void setProfile(ValidationProfile profile) { this.profile = profile; } // Used to avoid repeated computation of value nodes for a focus node / path combination private static class ValueNodesCacheKey { Resource path; RDFNode focusNode; ValueNodesCacheKey(RDFNode focusNode, Resource path) { this.path = path; this.focusNode = focusNode; } public boolean equals(Object o) { if(o instanceof ValueNodesCacheKey) { return path.equals(((ValueNodesCacheKey)o).path) && focusNode.equals(((ValueNodesCacheKey)o).focusNode); } else { return false; } } @Override public int hashCode() { return path.hashCode() + focusNode.hashCode(); } @Override public String toString() { return focusNode.toString() + " . " + path; } } } <MSG> Updated topbraid SHACL library to remove deprecated Apache Jena calls and updated version of Jena to 4.3.1 <DFF> @@ -386,7 +386,7 @@ public class ValidationEngine extends AbstractEngine { return results; } Set<RDFNode> results = new HashSet<>(); - Iterator<Node> it = PathEval.eval(focusNode.getModel().getGraph(), focusNode.asNode(), jenaPath, Context.emptyContext); + Iterator<Node> it = PathEval.eval(focusNode.getModel().getGraph(), focusNode.asNode(), jenaPath, Context.emptyContext()); while(it.hasNext()) { Node node = it.next(); results.add(focusNode.getModel().asRDFNode(node));
1
Updated topbraid SHACL library to remove deprecated Apache Jena calls and updated version of Jena to 4.3.1
1
.java
java
apache-2.0
TopQuadrant/shacl
405
<NME> ValidationEngine.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl.validation; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import org.apache.jena.graph.Graph; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.graph.compose.MultiUnion; import org.apache.jena.query.Dataset; import org.apache.jena.query.QuerySolution; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import org.apache.jena.sparql.path.P_Inverse; import org.apache.jena.sparql.path.P_Link; import org.apache.jena.sparql.path.Path; import org.apache.jena.sparql.path.eval.PathEval; import org.apache.jena.sparql.util.Context; import org.apache.jena.vocabulary.RDF; import org.topbraid.jenax.util.ExceptionUtil; import org.topbraid.jenax.util.JenaDatatypes; import org.topbraid.jenax.util.JenaUtil; import org.topbraid.jenax.util.RDFLabels; import org.topbraid.shacl.arq.SHACLPaths; import org.topbraid.shacl.engine.AbstractEngine; import org.topbraid.shacl.engine.Constraint; import org.topbraid.shacl.engine.SHACLScriptEngineManager; import org.topbraid.shacl.engine.Shape; import org.topbraid.shacl.engine.ShapesGraph; import org.topbraid.shacl.engine.filters.ExcludeMetaShapesFilter; import org.topbraid.shacl.expr.NodeExpression; import org.topbraid.shacl.expr.NodeExpressionFactory; import org.topbraid.shacl.model.SHNodeShape; import org.topbraid.shacl.model.SHPropertyShape; import org.topbraid.shacl.targets.InstancesTarget; import org.topbraid.shacl.targets.Target; import org.topbraid.shacl.util.FailureLog; import org.topbraid.shacl.util.SHACLPreferences; import org.topbraid.shacl.util.SHACLUtil; import org.topbraid.shacl.validation.sparql.SPARQLSubstitutions; import org.topbraid.shacl.vocabulary.DASH; import org.topbraid.shacl.vocabulary.SH; /** * A ValidationEngine uses a given shapes graph (represented via an instance of ShapesGraph) * and performs SHACL validation on a given Dataset. * * Instances of this class should be created via the ValidatorFactory. * * @author Holger Knublauch */ public class ValidationEngine extends AbstractEngine { // The currently active ValidationEngine for cases where no direct pointer can be acquired, e.g. from HasShapeFunction private static ThreadLocal<ValidationEngine> current = new ThreadLocal<>(); public static ValidationEngine getCurrent() { return current.get(); } public static void setCurrent(ValidationEngine value) { current.set(value); } // Avoids repeatedly walking up/down the class hierarchy for sh:class constraints private ClassesCache classesCache; private ValidationEngineConfiguration configuration; // Can be used to drop certain focus nodes from validation private Predicate<RDFNode> focusNodeFilter; // The inferred triples if the shapes graph declares an entailment regime private Model inferencesModel; // The label function for rendering nodes in validation results (message templates etc) private Function<RDFNode,String> labelFunction = (node -> RDFLabels.get().getNodeLabel(node)); // Avoids repeatedly fetching labels private Map<RDFNode,String> labelsCache = new ConcurrentHashMap<>(); // Can be used to collect statistical data about execution time of constraint components and shapes private ValidationProfile profile; // The resulting validation report instance private Resource report; // Number of created results, e.g. for progress monitor private int resultsCount = 0; // Avoids repeatedly fetching the value nodes of a focus node / path combination private Map<ValueNodesCacheKey,Collection<RDFNode>> valueNodes = new WeakHashMap<>(); // Number of created violations, e.g. for progress monitor private int violationsCount = 0; /** * Constructs a new ValidationEngine. * @param dataset the Dataset to operate on * @param shapesGraphURI the URI of the shapes graph (must be in the dataset) * @param shapesGraph the ShapesGraph with the shapes to validate against * @param report the sh:ValidationReport object in the results Model, or null to create a new one */ protected ValidationEngine(Dataset dataset, URI shapesGraphURI, ShapesGraph shapesGraph, Resource report) { super(dataset, shapesGraph, shapesGraphURI); setConfiguration(new ValidationEngineConfiguration()); if(report == null) { Model reportModel = JenaUtil.createMemoryModel(); reportModel.setNsPrefixes(dataset.getDefaultModel()); // This can be very expensive in some databases reportModel.withDefaultMappings(shapesGraph.getShapesModel()); this.report = reportModel.createResource(SH.ValidationReport); } else { this.report = report; } } /** * Checks if entailments are active for the current shapes graph and applies them for a given focus node. * This will only work for the sh:Rules entailment, e.g. to compute sh:values and sh:defaultValue. * If any inferred triples exist, the focus node will be returned attached to the model that includes those inferences. * The dataset used internally will also be switched to use that new model as its default model, so that if * a node gets validated it will "see" the inferred triples too. * @param focusNode the focus node * @return the focus node, possibly in a different Model than originally */ public RDFNode applyEntailments(Resource focusNode) { Model shapesModel = dataset.getNamedModel(shapesGraphURI.toString()); if(shapesModel.contains(null, SH.entailment, SH.Rules)) { // Create union of data model and inferences if called for the first time if(inferencesModel == null) { inferencesModel = JenaUtil.createDefaultModel(); Model dataModel = dataset.getDefaultModel(); MultiUnion multiUnion = new MultiUnion(new Graph[]{ dataModel.getGraph(), inferencesModel.getGraph() }); multiUnion.setBaseGraph(dataModel.getGraph()); dataset.setDefaultModel(ModelFactory.createModelForGraph(multiUnion)); } // Apply sh:values rules Map<Property,RDFNode> defaultValueMap = new HashMap<>(); for(SHNodeShape nodeShape : SHACLUtil.getAllShapesAtNode(focusNode)) { if(!nodeShape.hasProperty(SH.deactivated, JenaDatatypes.TRUE)) { for(SHPropertyShape ps : nodeShape.getPropertyShapes()) { if(!ps.hasProperty(SH.deactivated, JenaDatatypes.TRUE)) { Resource path = ps.getPath(); if(path instanceof Resource) { Statement values = ps.getProperty(SH.values); if(values != null) { NodeExpression ne = NodeExpressionFactory.get().create(values.getObject()); ne.eval(focusNode, this).forEachRemaining(v -> inferencesModel.getGraph().add(Triple.create(focusNode.asNode(), path.asNode(), v.asNode()))); } Statement defaultValue = ps.getProperty(SH.defaultValue); if(defaultValue != null) { defaultValueMap.put(JenaUtil.asProperty(path), defaultValue.getObject()); } } } } } } // Add sh:defaultValue where needed Model dataModel = dataset.getDefaultModel(); // This is now the union model Resource newFocusNode = focusNode.inModel(dataModel); for(Property predicate : defaultValueMap.keySet()) { if(!newFocusNode.hasProperty(predicate)) { NodeExpression ne = NodeExpressionFactory.get().create(defaultValueMap.get(predicate)); ne.eval(focusNode, this).forEachRemaining(v -> inferencesModel.add(focusNode, predicate, v)); } } return newFocusNode; } return focusNode; } public void addResultMessage(Resource result, Literal message, QuerySolution bindings) { result.addProperty(SH.resultMessage, SPARQLSubstitutions.withSubstitutions(message, bindings, getLabelFunction())); } // Note: does not set sh:path public Resource createResult(Resource type, Constraint constraint, RDFNode focusNode) { Resource result = report.getModel().createResource(type); report.addProperty(SH.result, result); result.addProperty(SH.resultSeverity, constraint.getSeverity()); result.addProperty(SH.sourceConstraintComponent, constraint.getComponent()); result.addProperty(SH.sourceShape, constraint.getShapeResource()); if(focusNode != null) { result.addProperty(SH.focusNode, focusNode); } checkMaximumNumberFailures(constraint); resultsCount++; return result; } public Resource createValidationResult(Constraint constraint, RDFNode focusNode, RDFNode value, Supplier<String> defaultMessage) { Resource result = createResult(SH.ValidationResult, constraint, focusNode); if(value != null) { result.addProperty(SH.value, value); } if(!constraint.getShape().isNodeShape()) { result.addProperty(SH.resultPath, SHACLPaths.clonePath(constraint.getShapeResource().getPath(), result.getModel())); } Collection<RDFNode> messages = constraint.getMessages(); if(messages.size() > 0) { messages.stream().forEach(message -> result.addProperty(SH.resultMessage, message)); } else if(defaultMessage != null) { String m = defaultMessage.get(); if(m != null) { result.addProperty(SH.resultMessage, m); } } return result; } private void checkMaximumNumberFailures(Constraint constraint) { if (SH.Violation.equals(constraint.getShape().getSeverity())) { this.violationsCount++; if (configuration.getValidationErrorBatch() != -1 && violationsCount >= configuration.getValidationErrorBatch()) { throw new MaximumNumberViolations(violationsCount); } } } public ClassesCache getClassesCache() { return classesCache; } public ValidationEngineConfiguration getConfiguration() { return configuration; } public String getLabel(RDFNode node) { return labelsCache.computeIfAbsent(node, n -> getLabelFunction().apply(n)); } public Function<RDFNode,String> getLabelFunction() { return labelFunction; } public ValidationProfile getProfile() { return profile; } /** * Gets the validation report as a Resource in the report Model. * @return the report Resource */ public Resource getReport() { return report; } /** * Gets a Set of all shapes that should be evaluated for a given resource. * @param focusNode the focus node to get the shapes for * @param dataset the Dataset containing the resource * @param shapesModel the shapes Model * @return a Set of shape resources */ private Set<Resource> getShapesForNode(RDFNode focusNode, Dataset dataset, Model shapesModel) { Set<Resource> shapes = new HashSet<>(); for(Shape rootShape : shapesGraph.getRootShapes()) { for(Target target : rootShape.getTargets()) { if(!(target instanceof InstancesTarget)) { if(target.contains(dataset, focusNode)) { shapes.add(rootShape.getShapeResource()); } } } } // rdf:type / sh:targetClass if(focusNode instanceof Resource) { for(Resource type : JenaUtil.getAllTypes((Resource)focusNode)) { if(JenaUtil.hasIndirectType(type.inModel(shapesModel), SH.Shape)) { shapes.add(type); } for(Statement s : shapesModel.listStatements(null, SH.targetClass, type).toList()) { shapes.add(s.getSubject()); } } } return shapes; } public ValidationReport getValidationReport() { return new ResourceValidationReport(report); } public Collection<RDFNode> getValueNodes(Constraint constraint, RDFNode focusNode) { if(constraint.getShape().isNodeShape()) { return Collections.singletonList(focusNode); } else { // We use a cache here because many shapes contains for example both sh:datatype and sh:minCount, and fetching // the value nodes each time may be expensive, esp for sh:minCount/maxCount constraints. ValueNodesCacheKey key = new ValueNodesCacheKey(focusNode, constraint.getShape().getPath()); return valueNodes.computeIfAbsent(key, k -> getValueNodesHelper(focusNode, constraint)); } } private Collection<RDFNode> getValueNodesHelper(RDFNode focusNode, Constraint constraint) { Property predicate = constraint.getShape().getPredicate(); if(predicate != null) { List<RDFNode> results = new LinkedList<>(); if(focusNode instanceof Resource) { Iterator<Statement> it = ((Resource)focusNode).listProperties(predicate); while(it.hasNext()) { results.add(it.next().getObject()); } } return results; } else { Path jenaPath = constraint.getShape().getJenaPath(); if(jenaPath instanceof P_Inverse && ((P_Inverse)jenaPath).getSubPath() instanceof P_Link) { List<RDFNode> results = new LinkedList<>(); Property inversePredicate = ResourceFactory.createProperty(((P_Link)((P_Inverse)jenaPath).getSubPath()).getNode().getURI()); Iterator<Statement> it = focusNode.getModel().listStatements(null, inversePredicate, focusNode); while(it.hasNext()) { results.add(it.next().getSubject()); } return results; } Set<RDFNode> results = new HashSet<>(); Iterator<Node> it = PathEval.eval(focusNode.getModel().getGraph(), focusNode.asNode(), jenaPath, Context.emptyContext); while(it.hasNext()) { Node node = it.next(); results.add(focusNode.getModel().asRDFNode(node)); } return results; } } /** * Validates a given list of focus nodes against a given Shape, and stops as soon * as one validation result is reported. No results are recorded. * @param focusNodes the nodes to validate * @param shape the sh:Shape to validate against * @return true if there were no validation results, false for violations */ public boolean nodesConformToShape(List<RDFNode> focusNodes, Node shape) { if(!shapesGraph.isIgnored(shape)) { Resource oldReport = report; report = JenaUtil.createMemoryModel().createResource(); try { Shape vs = shapesGraph.getShape(shape); if(!vs.isDeactivated()) { boolean nested = SHACLScriptEngineManager.get().begin(); try { for(Constraint constraint : vs.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); if(report.hasProperty(SH.result)) { return false; } } } finally { SHACLScriptEngineManager.get().end(nested); } } } finally { this.report = oldReport; } } return true; } public void setClassesCache(ClassesCache value) { this.classesCache = value; } /** * Sets a filter that can be used to skip certain focus node from validation. * The filter must return true if the given candidate focus node shall be validated, * and false to skip it. * @param value the new filter */ public void setFocusNodeFilter(Predicate<RDFNode> value) { this.focusNodeFilter = value; } public void setLabelFunction(Function<RDFNode,String> value) { this.labelFunction = value; } public void updateConforms() { boolean conforms = true; StmtIterator it = report.listProperties(SH.result); while(it.hasNext()) { Statement s = it.next(); if(s.getResource().hasProperty(RDF.type, SH.ValidationResult)) { conforms = false; it.close(); break; } } if(report.hasProperty(SH.conforms)) { report.removeAll(SH.conforms); } report.addProperty(SH.conforms, conforms ? JenaDatatypes.TRUE : JenaDatatypes.FALSE); } /** * Validates all target nodes against all of their shapes. * To further narrow down which nodes to validate, use {@link #setFocusNodeFilter(Predicate)}. * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateAll() throws InterruptedException { List<Shape> rootShapes = shapesGraph.getRootShapes(); return validateShapes(rootShapes); } /** * Validates a given focus node against all of the shapes that have matching targets. * @param focusNode the node to validate * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateNode(Node focusNode) throws InterruptedException { Model shapesModel = dataset.getNamedModel(shapesGraphURI.toString()); RDFNode focusRDFNode = dataset.getDefaultModel().asRDFNode(focusNode); Set<Resource> shapes = getShapesForNode(focusRDFNode, dataset, shapesModel); boolean nested = SHACLScriptEngineManager.get().begin(); try { for(Resource shape : shapes) { if(monitor != null && monitor.isCanceled()) { throw new InterruptedException(); } validateNodesAgainstShape(Collections.singletonList(focusRDFNode), shape.asNode()); } } finally { SHACLScriptEngineManager.get().end(nested); } return report; } /** * Validates a given list of focus node against a given Shape. * @param focusNodes the nodes to validate * @param shape the sh:Shape to validate against * @return an instance of sh:ValidationReport in the results Model */ public Resource validateNodesAgainstShape(List<RDFNode> focusNodes, Node shape) { if(!shapesGraph.isIgnored(shape)) { Shape vs = shapesGraph.getShape(shape); if(!vs.isDeactivated()) { boolean nested = SHACLScriptEngineManager.get().begin(); ValidationEngine oldEngine = current.get(); current.set(this); try { for(Constraint constraint : vs.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); } } finally { current.set(oldEngine); SHACLScriptEngineManager.get().end(nested); } } } return report; } /** * Validates all target nodes of a given collection of shapes against these shapes. * To further narrow down which nodes to validate, use {@link #setFocusNodeFilter(Predicate)}. * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateShapes(Collection<Shape> shapes) throws InterruptedException { boolean nested = SHACLScriptEngineManager.get().begin(); try { if(monitor != null) { monitor.beginTask("Validating " + shapes.size() + " shapes", shapes.size()); } if(classesCache == null) { // If we are doing everything then the cache should be used, but not for validation of individual focus nodes classesCache = new ClassesCache(); } int i = 0; for(Shape shape : shapes) { if(monitor != null) { String label = "Shape " + (++i) + ": " + getLabelFunction().apply(shape.getShapeResource()); if(resultsCount > 0) { label = "" + resultsCount + " results. " + label; } monitor.subTask(label); } Collection<RDFNode> focusNodes = shape.getTargetNodes(dataset); if(focusNodeFilter != null) { List<RDFNode> filteredFocusNodes = new LinkedList<>(); for(RDFNode focusNode : focusNodes) { if(focusNodeFilter.test(focusNode)) { filteredFocusNodes.add(focusNode); } } focusNodes = filteredFocusNodes; } if(!focusNodes.isEmpty()) { for(Constraint constraint : shape.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); } } if(monitor != null) { monitor.worked(1); if(monitor.isCanceled()) { throw new InterruptedException(); } } } } catch(MaximumNumberViolations ex) { // Ignore as this is just our way to stop validation when max number of violations is reached } finally { SHACLScriptEngineManager.get().end(nested); } updateConforms(); return report; } protected void validateNodesAgainstConstraint(Collection<RDFNode> focusNodes, Constraint constraint) { if(configuration != null && configuration.isSkippedConstraintComponent(constraint.getComponent())) { return; } ConstraintExecutor executor; try { executor = constraint.getExecutor(); } catch(Exception ex) { Resource result = createResult(DASH.FailureResult, constraint, constraint.getShapeResource()); result.addProperty(SH.resultMessage, "Failed to create validator: " + ExceptionUtil.getStackTrace(ex)); return; } if(executor != null) { if(SHACLPreferences.isProduceFailuresMode()) { try { executor.executeConstraint(constraint, this, focusNodes); } catch(Exception ex) { Resource result = createResult(DASH.FailureResult, constraint, constraint.getShapeResource()); result.addProperty(SH.resultMessage, "Exception during validation: " + ExceptionUtil.getStackTrace(ex)); } } else { executor.executeConstraint(constraint, this, focusNodes); } } else { FailureLog.get().logWarning("No suitable validator found for constraint " + constraint); } } public void setConfiguration(ValidationEngineConfiguration configuration) { this.configuration = configuration; if(!configuration.getValidateShapes()) { shapesGraph.setShapeFilter(new ExcludeMetaShapesFilter()); } } public void setProfile(ValidationProfile profile) { this.profile = profile; } // Used to avoid repeated computation of value nodes for a focus node / path combination private static class ValueNodesCacheKey { Resource path; RDFNode focusNode; ValueNodesCacheKey(RDFNode focusNode, Resource path) { this.path = path; this.focusNode = focusNode; } public boolean equals(Object o) { if(o instanceof ValueNodesCacheKey) { return path.equals(((ValueNodesCacheKey)o).path) && focusNode.equals(((ValueNodesCacheKey)o).focusNode); } else { return false; } } @Override public int hashCode() { return path.hashCode() + focusNode.hashCode(); } @Override public String toString() { return focusNode.toString() + " . " + path; } } } <MSG> Updated topbraid SHACL library to remove deprecated Apache Jena calls and updated version of Jena to 4.3.1 <DFF> @@ -386,7 +386,7 @@ public class ValidationEngine extends AbstractEngine { return results; } Set<RDFNode> results = new HashSet<>(); - Iterator<Node> it = PathEval.eval(focusNode.getModel().getGraph(), focusNode.asNode(), jenaPath, Context.emptyContext); + Iterator<Node> it = PathEval.eval(focusNode.getModel().getGraph(), focusNode.asNode(), jenaPath, Context.emptyContext()); while(it.hasNext()) { Node node = it.next(); results.add(focusNode.getModel().asRDFNode(node));
1
Updated topbraid SHACL library to remove deprecated Apache Jena calls and updated version of Jena to 4.3.1
1
.java
java
apache-2.0
TopQuadrant/shacl
406
<NME> tosh.ttl <BEF> # baseURI: http://topbraid.org/tosh # imports: http://datashapes.org/dash # prefix: tosh @prefix dash: <http://datashapes.org/dash#> . @prefix graphql: <http://datashapes.org/graphql#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix sh: <http://www.w3.org/ns/shacl#> . @prefix swa: <http://topbraid.org/swa#> . @prefix tosh: <http://topbraid.org/tosh#> . @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . dash: tosh:systemNamespace true ; . dash:Action sh:property tosh:Action-actionGroup ; sh:property tosh:Action-actionIconClass ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order "10"^^xsd:decimal ; . dash:HasValueWithClassConstraintComponent-hasValueWithClass sh:group tosh:OtherConstraintPropertyGroup ; . sh:property tosh:ActionTestCase-focusNode ; sh:property tosh:ActionTestCase-variables ; . dash:ChangeScript sh:group tosh:RelationshipPropertyGroup ; . dash:PrimaryKeyConstraintComponent-uriStart tosh:editWidget swa:PlainTextFieldEditor ; sh:group tosh:PrimaryKeyPropertyGroup ; . dash:RootClassConstraintComponent dash:CoExistsWithConstraintComponent-coExistsWith sh:group tosh:PropertyPairConstraintsPropertyGroup ; sh:order "0"^^xsd:decimal ; . dash:DetailsEditor dash:hidden true ; owl:versionInfo "This is not yet supported by TopBraid." ; . dash:FunctionTestCase sh:property tosh:FunctionTestCase-expectedResult ; sh:property tosh:FunctionTestCase-expression ; . dash:GraphStoreTestCase sh:property tosh:GraphStoreTestCase-expectedResult ; sh:property tosh:GraphStoreTestCase-uri ; . dash:IndexedConstraintComponent-indexed sh:group tosh:ReificationPropertyGroup ; sh:order "1"^^xsd:decimal ; . dash:InferencingTestCase sh:property tosh:InferencingTestCase-expectedResult ; . dash:JSTestCase sh:property tosh:JSTestCase-expectedResult ; . dash:MultiFunction sh:property tosh:Function-apiStatus ; sh:property tosh:MultiFunction-resultVariable ; . dash:NonRecursiveConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; . dash:NonRecursiveConstraintComponent-nonRecursive sh:group tosh:ValueConstraintsPropertyGroup ; sh:order "5"^^xsd:decimal ; . dash:PrimaryKeyConstraintComponent-uriStart sh:group tosh:StringConstraintsPropertyGroup ; sh:order "40"^^xsd:decimal ; . dash:PropertyRole sh:property tosh:Resource-comment ; sh:property tosh:Resource-label ; . dash:QueryTestCase sh:property tosh:QueryTestCase-expectedResult ; . dash:ReifiableByConstraintComponent-reifiableBy sh:group tosh:ReificationPropertyGroup ; sh:order "0"^^xsd:decimal ; . dash:ResourceAction sh:property tosh:ResourceAction-jsCondition ; . dash:RootClassConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; . dash:RootClassConstraintComponent-rootClass sh:group tosh:ValueConstraintsPropertyGroup ; sh:order "10"^^xsd:decimal ; . tosh:AboutPropertyGroup a sh:PropertyGroup ; rdfs:label "This Shape" ; sh:order 0 ; . tosh:CardinalityConstraintPropertyGroup a sh:PropertyGroup ; rdfs:label "Number of Values" ; sh:order 2 ; . tosh:ComplexConstraintPropertyGroup a sh:PropertyGroup ; tosh:editGroupDescription "Most edit fields in this section currently require Turtle source code, esp to enter blank node expressions. To reference existing shapes via their URI, enter them as <URI>." ; tosh:openable true ; rdfs:label "Complex Constraint Expressions" ; sh:order 9 ; . tosh:ConstraintMetadataPropertyGroup a sh:PropertyGroup ; sh:group tosh:AdvancedPropertyGroup ; sh:order "20"^^xsd:decimal ; . dash:ScriptFunction rdfs:comment "Produces a suggestion that would delete the offending value in the validation result from the focus node." ; rdfs:label "Delete triple suggestion generator" ; sh:message "Delete the invalid statement" ; sh:order 100 ; sh:update """DELETE { $focusNode $predicate $value . } sh:property tosh:Script-onAllValues ; $focusNode $predicate $value . }""" ; . tosh:DisplayPropertyGroup a sh:PropertyGroup ; rdfs:comment "A group for properties that are primarily for display purposes (names, ordering etc)." ; rdfs:label "Display Settings" ; sh:order 1 ; . tosh:InferencesPropertyGroup a sh:PropertyGroup ; a sh:PropertyShape ; rdfs:label "Inferences" ; sh:order "11"^^xsd:decimal ; . tosh:MemberShapeConstraintComponent a sh:ConstraintComponent ; rdfs:comment "Can be used to specify constraints on the members of a given list, assuming that the given sh:property has rdf:Lists as values. A violation is reported for each member of the list that does not comply with the constraints specified by the given shape." ; sh:description "The graph containing the test case." ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "test graph" ; sh:nodeKind sh:IRI ; ] ; . dash:UniqueValueForClassConstraintComponent-uniqueValueForClass sh:group tosh:ValueConstraintsPropertyGroup ; sh:order "20"^^xsd:decimal ; . dash:ValidationTestCase sh:property tosh:ValidationTestCase-expectedResult ; sh:property tosh:ValidationTestCase-includeSuggestions ; sh:property tosh:ValidationTestCase-validateShapes ; . dash:Widget sh:property tosh:Resource-comment ; sh:property tosh:Resource-label ; . dash:Widget-hidden sh:group tosh:DisplayPropertyGroup ; . <http://spinrdf.org/sp#> tosh:systemNamespace true ; . <http://spinrdf.org/spin#> a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Other Constraints" ; sh:order 10 ; . tosh:PrimaryKeyPropertyGroup a sh:PropertyGroup ; dash:generateClass dash:ConstraintReificationShape ; dash:generateClass rdf:Property ; dash:generateClass rdfs:Class ; dash:generateClass rdfs:Datatype ; dash:generateClass owl:Class ; a sh:NodeShape ; rdfs:label "Property group shape" ; sh:property [ sh:path sh:order ; sh:maxCount 1 ; ] ; dash:generatePrefixConstants "rdf" ; dash:generatePrefixConstants "rdfs" ; dash:generatePrefixConstants "sh" ; a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Relationship to Other Properties" ; sh:order 6 ; . tosh:PropertyShapeShape a sh:NodeShape ; Some of these may be of general use outside of TopBraid too.""" ; rdfs:label "TopBraid Data Shapes Library" ; owl:imports <http://datashapes.org/dash> ; sh:declare [ a sh:PrefixDeclaration ; sh:namespace "http://jena.hpl.hp.com/ARQ/function#"^^xsd:anyURI ; sh:prefix "afn" ; ] ; ] ; sh:property [ a sh:PropertyShape ; sh:path sh:values ; tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget <http://topbraid.org/tosh.ui#ValuesExpressionDiagramViewer> ; sh:group tosh:InferencesPropertyGroup ; sh:name "values" ; sh:order "1"^^xsd:decimal ; sh:sparql [ sh:message "sh:values must be accompanied by a sh:path that is an IRI." ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT $this ?value WHERE { $this $PATH ?value . FILTER NOT EXISTS { $this sh:path ?path . FILTER isIRI(?path) } }""" ; ] ; ] ; sh:property [ sh:path tosh:editWidget ; tosh:editWidget swa:WidgetDropDownEditor ; tosh:viewWidget swa:ResourceInUIGraphViewer ; sh:description "The swa:ObjectEditorClass that shall be used to edit values of this predicate." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "edit widget" ; sh:nodeKind sh:IRI ; sh:order 21 ; ] ; sh:property [ sh:path tosh:searchWidget ; tosh:editWidget swa:WidgetDropDownEditor ; tosh:viewWidget swa:ResourceInUIGraphViewer ; sh:description "The swa:ObjectFacetClass that shall be used to search for values of this predicate." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "search widget" ; sh:nodeKind sh:IRI ; sh:order 22 ; ] ; sh:property [ sh:path tosh:viewWidget ; tosh:editWidget swa:WidgetDropDownEditor ; tosh:viewWidget swa:ResourceInUIGraphViewer ; sh:description "The swa:ObjectViewerClass that shall be used to view values of this predicate." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "view widget" ; sh:nodeKind sh:IRI ; sh:order 20 ; ] ; sh:property [ sh:path sh:defaultValue ; tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; tosh:viewWidget <http://topbraid.org/tosh.ui#DefaultValueViewer> ; sh:description "The default value to be used for this property if no other value has been asserted. This may be a constant value or a SHACL node expression, in which case the values can be derived from other values. Default values are typically inferred and not stored as RDF statements." ; sh:group tosh:ValueTypeConstraintPropertyGroup ; ] ; sh:property [ sh:path sh:description ; tosh:editWidget swa:TextAreaEditor ; sh:description "A human-readable description of the role of the property in the constraint." ; sh:group tosh:DisplayPropertyGroup ; sh:name "description" ; sh:order 2 ; ] ; sh:property [ sh:path sh:disjoint ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order 1 ; ] ; sh:property [ sh:path sh:equals ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order 0 ; ] ; sh:property [ sh:path sh:group ; sh:description "The sh:PropertyGroup that the property belongs to." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "group" ; sh:order 10 ; ] ; sh:property [ sh:path sh:lessThan ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order 2 ; ] ; sh:property [ sh:path sh:lessThanOrEquals ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order 3 ; ] ; sh:property [ sh:path sh:name ; tosh:editWidget swa:TextFieldEditorWithLang ; sh:description "The display name of the property." ; sh:group tosh:DisplayPropertyGroup ; sh:name "name" ; sh:order 1 ; ] ; sh:property [ sh:path sh:order ; sh:description "The relative position of the property among its peers, e.g. a property with order 5 shows up before one with order 6." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "order" ; sh:order 11 ; ] ; sh:property [ sh:path sh:path ; tosh:editWidget <http://topbraid.org/tosh.ui#PathEditor> ; tosh:viewWidget <http://topbraid.org/tosh.ui#PathViewer> ; sh:group tosh:AboutPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "on property" ; sh:order 0 ; ] ; sh:sparql [ sh:message "Property shapes cannot have both class and datatype constraints." ; For parameters that declare dash:mimeTypes (i.e. file upload parameters), the value needs to be the path to a file relative to the workspace root. This file will be temporarily uploaded for the duration of the test case execution.""" ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "variables" ; sh:order "2"^^xsd:decimal ; . tosh:AdvancedPropertyGroup a sh:PropertyGroup ; rdfs:label "Advanced" ; sh:order "95"^^xsd:decimal ; . a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Relationship" ; sh:order 8 ; . tosh:RemoteValuesPropertyGroup a sh:PropertyGroup ; sh:name "deactivated" ; sh:order "10"^^xsd:decimal ; . tosh:ChangeScript-order a sh:PropertyShape ; sh:path sh:order ; sh:description "The relative order of this script compared to other change scripts. The default value is 0. Scripts with lower numbers are executed first." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "order" ; sh:or ( [ sh:datatype xsd:decimal ; ] [ sh:datatype xsd:integer ; ] ) ; sh:order "40"^^xsd:decimal ; . tosh:Class-ShapeScript a dash:ShapeScript ; dash:js """ /** * Returns this class as an instance of sh:NodeShape. * @returns {sh_NodeShape} */ asNodeShape() { return sh.asNodeShape(this); } /** * @callback rdfs_Class_callback * @param {rdfs_Class} class the visited class */ /** * Performs a depth-first traversal this class and its superclasses, visiting each (super) class * once until the callback function returns a non-null/undefined result. This becomes the result of this function. * The order in which sibling classes are traversed is undefined, so results may be inconsistent in * multiple-inheritance scenarios. * @param {rdfs_Class_callback} callback the callback for each class * @param {Set} [reached] the Set of reached URI strings, used internally * @returns the return value of the first callback that returned any value */ walkSuperclasses(callback, reached) { if(!reached) { reached = new Set(); tosh:ShapeInGraphConstraintComponent a sh:ConstraintComponent ; dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; rdfs:comment "A constraint component that can be used to verify that the value nodes have a given shape, where the shape validation is executed in a given graph. This can, for example, be used to verify that a given value is declared as an instance of a given class in some specified (not imported) graph." ; rdfs:label "Shape in graph constraint component" ; sh:labelTemplate "Values must have shape {$shapeInGraph} defined in graph {$graph}" ; sh:message "Value does not have shape {$shapeInGraph} defined in graph {$graph}" ; sh:path dash:abstract ; sh:datatype xsd:boolean ; sh:description "States whether this class is abstract, i.e. cannot have direct instances. Abstract classes are typically used to defined shared properties of its subclasses." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "abstract" ; sh:order "30"^^xsd:decimal ; . tosh:Class-classIcon a sh:PropertyShape ; sh:path tosh:classIcon ; dash:hidden true ; dash:propertyRole dash:IconRole ; sh:datatype xsd:string ; sh:defaultValue "http://datashapes.org/icons/class.svg" ; sh:description "Used to return the default icon for all classes." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "class icon" ; sh:order "1"^^xsd:decimal ; . tosh:Class-constructor a sh:PropertyShape ; sh:path dash:constructor ; graphql:name "constructorScript" ; sh:class dash:Constructor ; sh:description "The Constructor that shall be used to create new instances of this class or its subclasses." ; sh:group tosh:ScriptsPropertyGroup ; sh:maxCount 1 ; sh:name "constructor" ; sh:order "20"^^xsd:decimal ; . tosh:Class-disjointWith a sh:PropertyShape ; sh:path owl:disjointWith ; sh:class owl:Class ; sh:group tosh:OWLAxiomsPropertyGroup ; sh:name "disjoint with" ; sh:order "1"^^xsd:decimal ; . tosh:Class-domain-inverse a sh:PropertyShape ; sh:path [ sh:inversePath rdfs:domain ; ] ; dash:editor dash:PropertyAutoCompleteEditor ; sh:class rdf:Property ; sh:description "The properties that declare to have this class in their domain." ; sh:group tosh:RDFSPropertyAxiomsPropertyGroup ; tosh:ShapeShape-severity a sh:PropertyShape ; sh:path sh:severity ; tosh:editWidget swa:InstancesSelectEditor ; sh:class sh:Severity ; sh:description "The severity to be used for validation results produced by the associated constraint." ; sh:group tosh:AboutPropertyGroup ; sh:path owl:equivalentClass ; sh:class owl:Class ; sh:group tosh:OWLAxiomsPropertyGroup ; sh:name "equivalent classes" ; sh:order "0"^^xsd:decimal ; a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Constraints for Strings and Text" ; sh:order 7 ; . tosh:SystemNamespaceShape a sh:NodeShape ; sh:maxCount 1 ; sh:name "hidden" ; sh:order "0"^^xsd:decimal ; . tosh:Class-range-inverse a sh:PropertyShape ; sh:path [ sh:inversePath rdfs:range ; ] ; dash:editor dash:PropertyAutoCompleteEditor ; sh:class rdf:Property ; sh:description "The properties that have this class in their rdfs:range." ; sh:group tosh:RDFSPropertyAxiomsPropertyGroup ; sh:name "range of" ; sh:nodeKind sh:IRI ; sh:order "1"^^xsd:decimal ; . tosh:Class-resourceAction a sh:PropertyShape ; sh:path dash:resourceAction ; graphql:name "resourceActions" ; sh:class dash:ResourceAction ; sh:description "The Resource Actions that can be applied to instances of this class." ; sh:group tosh:ScriptsPropertyGroup ; rdfs:comment "The platform consisting of TopBraid." ; rdfs:label "TopBraid platform" ; . tosh:UseDeclaredDatatypeConstraintComponent a sh:ConstraintComponent ; dash:propertySuggestionGenerator [ sh:order "10"^^xsd:decimal ; . tosh:Class-subClassOf a sh:PropertyShape ; sh:path rdfs:subClassOf ; graphql:name "superclasses" ; sh:class rdfs:Class ; sh:description "The (direct) parent classes of this class." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "superclasses" ; sh:order "20"^^xsd:decimal ; . tosh:Class-subClassOf-inverse a sh:PropertyShape ; sh:path [ sh:inversePath rdfs:subClassOf ; ] ; dash:hidden true ; graphql:name "subclasses" ; sh:class rdfs:Class ; sh:description "The (direct) subclasses of this class." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "subclasses" ; sh:order "21"^^xsd:decimal ; . tosh:ConstraintComponent-localConstraint a sh:PropertyShape ; sh:path dash:localConstraint ; sh:datatype xsd:boolean ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "local constraint" ; sh:order "10"^^xsd:decimal ; . tosh:ConstraintComponent-message a sh:PropertyShape ; sh:path sh:message ; sh:description "The message to generate on violations." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "messages" ; a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Min/Max Values" ; sh:order 5 ; . tosh:ValueTypeConstraintPropertyGroup a sh:PropertyGroup ; tosh:editGroupDescription "Hint: Use \"or\" under Complex Constraints to represent choices between multiple value types." ; rdfs:comment "A property group for constraint parameters that restrict the value types of values." ; rdfs:label "Type of Values" ; sh:order 3 ; . tosh:closed a rdf:Property ; a owl:DeprecatedProperty ; rdfs:comment "If set to true, then the corresponding form section will be closed by default." ; rdfs:domain sh:PropertyGroup ; rdfs:label "closed" ; rdfs:range xsd:boolean ; . tosh:ConstraintComponent-propertyValidator a sh:PropertyShape ; sh:path sh:propertyValidator ; sh:class sh:Validator ; sh:description "The validator(s) used to evaluate a constraint in the context of a property shape." ; sh:path sh:expectedValue ; sh:datatype xsd:boolean ; sh:description "The expected value of tosh:hasShape to count." ; sh:order 3 ; ] ; sh:parameter [ sh:path sh:focusNode ; sh:class rdfs:Resource ; sh:description "The focus node." ; sh:order 0 ; ] ; sh:parameter [ sh:path sh:shapes ; sh:class rdf:List ; sh:description "The list of shapes to walk through." ; sh:order 1 ; ] ; sh:parameter [ sh:path sh:shapesGraph ; sh:class rdfs:Resource ; sh:description "The shapes graph." ; sh:order 2 ; ] ; sh:prefixes <http://topbraid.org/tosh> ; sh:returnType xsd:integer ; rdfs:label "Attribute view" ; sh:node tosh:PropertyShapeView ; sh:property dash:PrimaryKeyConstraintComponent-uriStart ; sh:property dash:SingleLineConstraintComponent-singleLine ; sh:property tosh:Shape-datatypes ; sh:property sh:LanguageInConstraintComponent-languageIn ; sh:property sh:LessThanConstraintComponent-lessThan ; sh:property sh:LessThanOrEqualsConstraintComponent-lessThanOrEquals ; sh:property sh:MaxExclusiveConstraintComponent-maxExclusive ; sh:property sh:MaxInclusiveConstraintComponent-maxInclusive ; sh:property sh:MaxLengthConstraintComponent-maxLength ; sh:property sh:MinExclusiveConstraintComponent-minExclusive ; sh:property sh:MinInclusiveConstraintComponent-minInclusive ; sh:property sh:MinLengthConstraintComponent-minLength ; sh:property sh:PatternConstraintComponent-flags ; sh:property sh:PatternConstraintComponent-pattern ; sh:property sh:UniqueLangConstraintComponent-uniqueLang ; rdfs:label "edit group description" ; rdfs:range xsd:string ; . tosh:editWidget a rdf:Property ; rdfs:label "edit widget" ; rdfs:range swa:ObjectEditorClass ; . tosh:graph a rdf:Property ; rdfs:comment "The graph that the shape is validated in." ; tosh:DefinitionPropertyGroup a sh:PropertyGroup ; rdfs:label "Definition" ; sh:order "0"^^xsd:decimal ; . tosh:DeleteTripleSuggestionGenerator a dash:SPARQLUpdateSuggestionGenerator ; rdfs:comment "Produces a suggestion that would delete the offending value in the validation result from the focus node." ; rdfs:label "Delete triple suggestion generator" ; sh:message "Delete the invalid statement" ; sh:order 100.0 ; sh:update """DELETE { $focusNode $predicate $value . } WHERE { $focusNode $predicate $value . }""" ; . tosh:DependentEnumSelectEditor a dash:SingleEditor ; rdfs:comment """A drop-down editor for enumerated values that are dynamically determined via a node shape that has sh:target dash:HasValueTarget. Example: states:USAddressShape rdf:type sh:NodeShape ; rdfs:label \"US Address shape\" ; sh:property [ rdf:type sh:PropertyShape ; sh:path states:state ; sh:in ( ] ; sh:returnType xsd:boolean ; . tosh:isInTargetOf a sh:Function ; rdfs:comment "Checks whether a given node is in the target of a given shape." ; sh:group tosh:DefinitionPropertyGroup ; sh:in ( dash:Experimental dash:Stable dash:Deprecated ) ; sh:maxCount 1 ; sh:name "API status" ; sh:order "15"^^xsd:decimal ; . tosh:Function-cachable ] ; sh:returnType xsd:boolean ; . tosh:isSystemResource a sh:SPARQLFunction ; rdfs:comment "Checks if a given resource is from a namespace that is marked with tosh:systemNamespace true." ; sh:path dash:expectedResult ; sh:datatype xsd:string ; sh:description "The expected RDF graph, as a Turtle string." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:order "10"^^xsd:decimal ; . tosh:GraphStoreTestCase-uri a sh:PropertyShape ; sh:path dash:uri ; sh:datatype xsd:anyURI ; sh:description "The URI of the graph to load." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "uri" ; sh:order "0"^^xsd:decimal ; . tosh:ImplementationPropertyGroup a sh:PropertyGroup ; rdfs:label "Implementation" ; sh:order "10"^^xsd:decimal ; . tosh:IncludedScript-exports a sh:PropertyShape ; sh:path dash:exports ; sh:datatype xsd:string ; sh:description "Declares the symbols that shall be exported from the surrounding module, e.g. for use in Node.js applications." ; sh:group tosh:ImplementationPropertyGroup ; sh:name "exports" ; sh:order "30"^^xsd:decimal ; rdfs:label "openable" ; rdfs:range xsd:boolean ; . tosh:searchWidget a rdf:Property ; rdfs:label "search widget" ; rdfs:range swa:ObjectFacetClass ; . tosh:shaclExists a sh:Function ; sh:name "member shape" ; . tosh:ModifyAction-skipPreview a sh:PropertyShape ; sh:path dash:skipPreview ; sh:datatype xsd:boolean ; sh:description "For actions that take no parameters, this can be set to true to skip any means for the user to preview the action. It will instead directly execute the modification." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "skip preview" ; sh:order "11"^^xsd:decimal ; . tosh:MultiFunction-resultVariable a sh:PropertyShape ; sh:path dash:resultVariable ; sh:class sh:Parameter ; sh:description "The result variables." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "result variables" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "30"^^xsd:decimal ; . tosh:NodeShape-ShapeScript a dash:ShapeScript ; dash:js """ /** * Returns this class as an instance of rdfs_Class, assuming this node shape is also a class. * @returns {rdfs_Class} */ asClass() { return rdfs.asClass(this); } /** * Gets the \"nearest\" constraint of a given type and a given path property. Deactivated shapes are skipped. * For example, call it with (ex.myProperty, sh.datatype) to find the closest sh:datatype constraint for ex:myProperty. * @param {NamedNode} path the property that is the sh:path of matching property shapes * @param {NamedNode} predicate the property to fetch the nearest value of */ nearestPropertyShapeValue(path, predicate) { return this.walkSupershapes(s => { if(!s.deactivated) { let ps = s.properties; for(let i = 0; i < ps.length; i++) { if(!ps[i].deactivated && graph.contains(ps[i], sh.path, path)) { let value = ps[i].value(predicate); if(value !== null && value !== undefined) { return value; } } } } }) } /** * @callback sh_NodeShape_callback * @param {sh_NodeShape} nodeShape the visited node shape */ /** * Performs a depth-first traversal of this and its superclasses (via rdfs:subClassOf) and supershapes (via sh:node), * visiting each (super) shape once until the callback function returns a non-null/undefined result. This becomes the result of this function. * The order in which sibling parents are traversed is undefined. * @param {sh_NodeShape_callback} callback the callback for each shape * @param {Set} [reached] the Set of reached URI strings, used internally but may also be used to terminate at certain supers * @returns the return value of the first callback that returned any value */ walkSupershapes(callback, reached) { if(!reached) { reached = new Set(); } if(!reached.has(this.uri)) { reached.add(this.uri); let result = callback(this); if(result !== undefined && result !== null) { return result; } let superClasses = this.asClass().superclasses; for(let i = 0; i < superClasses.length; i++) { result = superClasses[i].asNodeShape().walkSupershapes(callback, reached); if(result !== undefined && result !== null) { return result; } } let superShapes = this.supershapes; for(let i = 0; i < superShapes.length; i++) { result = superShapes[i].walkSupershapes(callback, reached); if(result !== undefined && result !== null) { return result; } } } } """ ; . tosh:NodeShape-applicableToClass a sh:PropertyShape ; sh:path dash:applicableToClass ; sh:class rdfs:Class ; sh:description "Links a node shape with the classes that it can be applied to." ; sh:group tosh:TargetsPropertyGroup ; sh:name "applicable to classes" ; sh:nodeKind sh:IRI ; sh:order "10"^^xsd:decimal ; . tosh:NodeShape-defaultViewForRole a sh:PropertyShape ; sh:path dash:defaultViewForRole ; dash:editor tosh:GovernanceRoleSelectEditor ; dash:viewer tosh:GovernanceRoleViewer ; sh:description "The user roles that this shape shall be used as default view for." ; sh:group tosh:TargetsPropertyGroup ; sh:name "default view for roles" ; sh:nodeKind sh:IRI ; owl: tosh:systemNamespace true ; . sh: tosh:systemNamespace true ; . sh:minus sh:this ; sh:nodes [ sh:distinct [ sh:path [ sh:oneOrMorePath [ sh:alternativePath ( rdfs:subClassOf sh:node ) ; ] ; ] ; ] ; ] ; ] ; ] ; . tosh:NodeShape-node a sh:PropertyShape ; sh:path sh:node ; graphql:name "supershapes" ; sh:description "The node shapes that this must also conform to, forming a kind of inheritance between shapes similar to a subclass-of relationship." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "node (super shapes)" ; sh:node sh:NodeShape ; sh:nodeKind sh:BlankNodeOrIRI ; ] ; . sh:AndConstraintComponent-and tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 11 ; . sh:ClassConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; sh:name "target classes" ; sh:nodeKind sh:IRI ; sh:order "0"^^xsd:decimal ; . tosh:NodeShape-targetObjectsOf a sh:PropertyShape ; sh:path sh:targetObjectsOf ; sh:group tosh:TargetsPropertyGroup ; sh:name "target objects of" ; sh:node rdf:Property ; sh:nodeKind sh:IRI ; sh:order "1"^^xsd:decimal ; . tosh:NodeShape-targetSubjectsOf a sh:PropertyShape ; sh:path sh:targetSubjectsOf ; sh:group tosh:TargetsPropertyGroup ; sh:name "target subjects of" ; sh:node rdf:Property ; sh:nodeKind sh:IRI ; sh:order "2"^^xsd:decimal ; . tosh:NodeShapeConstraintsShape a sh:NodeShape ; rdfs:comment "A shape that can be used to validate the syntax of node shapes, and to enter constraints for node shapes on forms." ; rdfs:label "Node shape constraints" ; . sh:ClassConstraintComponent-class sh:group tosh:ValueTypeConstraintPropertyGroup ; sh:order 2 ; . sh:ClosedConstraintComponent-closed sh:group tosh:OtherConstraintPropertyGroup ; sh:property sh:ClosedConstraintComponent-ignoredProperties ; sh:property sh:DatatypeConstraintComponent-datatype ; sh:property sh:HasValueConstraintComponent-hasValue ; sh:property sh:InConstraintComponent-in ; sh:property sh:LanguageInConstraintComponent-languageIn ; sh:property sh:MaxExclusiveConstraintComponent-maxExclusive ; sh:property sh:MaxInclusiveConstraintComponent-maxInclusive ; sh:property sh:MaxLengthConstraintComponent-maxLength ; sh:property sh:MinExclusiveConstraintComponent-minExclusive ; sh:property sh:MinInclusiveConstraintComponent-minInclusive ; sh:property sh:MinLengthConstraintComponent-minLength ; sh:property sh:NodeKindConstraintComponent-nodeKind ; sh:property sh:PatternConstraintComponent-flags ; sh:property sh:PatternConstraintComponent-pattern ; sh:property sh:SPARQLConstraintComponent-sparql ; sh:targetClass sh:NodeShape ; . tosh:NumberOfValuesPropertyGroup a sh:PropertyGroup ; rdfs:label "Number of Values" ; sh:order "40"^^xsd:decimal ; . tosh:OWLAxiomsPropertyGroup a sh:PropertyGroup ; rdfs:label "OWL Axioms" ; sh:order "17"^^xsd:decimal ; . tosh:ObjectPropertyShapeView a sh:NodeShape ; rdfs:comment "The default view shape for property shapes on object values." ; rdfs:label "Relationship view" ; sh:node tosh:PropertyShapeView ; sh:property dash:NonRecursiveConstraintComponent-nonRecursive ; sh:property dash:RootClassConstraintComponent-rootClass ; sh:property dash:StemConstraintComponent-stem ; sh:property dash:SymmetricConstraintComponent-symmetric ; sh:property tosh:ObjectPropertyShapeView-node ; sh:property sh:ClassConstraintComponent-class ; sh:property sh:NodeKindConstraintComponent-nodeKind ; . tosh:ObjectPropertyShapeView-node a sh:PropertyShape ; sh:path sh:node ; dash:reifiableBy dash:ConstraintReificationShape ; sh:validator tosh:hasDatatype ; . sh:DatatypeConstraintComponent-datatype tosh:editWidget <http://topbraid.org/tosh.ui#DatatypeEditor> ; sh:class rdfs:Datatype ; sh:group tosh:ValueTypeConstraintPropertyGroup ; sh:maxCount 1 ; sh:order 1 ; . sh:DisjointConstraintComponent-disjoint sh:deactivated true ; sh:name "imports" ; sh:nodeKind sh:IRI ; . tosh:Parameterizable-labelTemplate a sh:PropertyShape ; sh:path sh:labelTemplate ; sh:description "Outlines how human-readable labels of instances of the associated Parameterizable shall be produced. The values can contain {?paramName} as placeholders for the actual values of the given parameter." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "label template" ; sh:or dash:StringOrLangString ; sh:order "25"^^xsd:decimal ; . }""" ; ] ; sh:property [ sh:path sh:hasValue ; tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; ] ; . sh:order "20"^^xsd:decimal ; . tosh:PathStringViewer a dash:MultiViewer ; dash:hidden true ; rdfs:label "Path string viewer" ; dash:propertySuggestionGenerator [ a dash:SPARQLUpdateSuggestionGenerator ; sh:message "Replace invalid value with {$newObject}" ; sh:order 2 ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT ?newObject WHERE { tosh:Property-domain a sh:PropertyShape ; sh:path rdfs:domain ; graphql:name "domains" ; sh:description "The domain(s) of this property." ; sh:group tosh:PropertyAxiomsPropertyGroup ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "0"^^xsd:decimal ; . tosh:Property-range a sh:PropertyShape ; sh:path rdfs:range ; graphql:name "ranges" ; sh:description "The range(s) of this property." ; sh:group tosh:PropertyAxiomsPropertyGroup ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "1"^^xsd:decimal ; . tosh:Property-subPropertyOf a sh:PropertyShape ; sh:path rdfs:subPropertyOf ; graphql:name "superproperties" ; sh:class rdf:Property ; sh:group tosh:StringBasedConstraintPropertyGroup ; sh:order "9"^^xsd:decimal ; sh:property [ sh:path ( [ sh:zeroOrMorePath rdf:rest ; a sh:PropertyShape ; sh:path [ sh:inversePath rdfs:subPropertyOf ; ] ; graphql:name "subproperties" ; sh:class rdf:Property ; sh:description "The (direct) subproperties of this." ; sh:group tosh:PropertyAxiomsPropertyGroup ; sh:name "subproperties" ; sh:nodeKind sh:IRI ; sh:order "3"^^xsd:decimal ; . . sh:MaxCountConstraintComponent-maxCount sh:group tosh:CardinalityConstraintPropertyGroup ; sh:order 1 ; . sh:MaxExclusiveConstraintComponent-maxExclusive tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; sh:group tosh:ValueRangeConstraintPropertyGroup ; sh:order 3 ; . sh:MaxInclusiveConstraintComponent dash:propertySuggestionGenerator [ sh:or ( [ sh:datatype xsd:decimal ; ] [ sh:datatype xsd:integer ; ] ) ; sh:order "0"^^xsd:decimal ; . ] ; . sh:MaxInclusiveConstraintComponent-maxInclusive tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; sh:group tosh:ValueRangeConstraintPropertyGroup ; sh:order 2 ; . sh:MaxLengthConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; dash:viewer dash:NodeExpressionViewer ; dash:propertySuggestionGenerator [ a dash:SPARQLUpdateSuggestionGenerator ; sh:message "Prune string to only {$maxLength} characters" ; sh:order 1 ; sh:prefixes <http://topbraid.org/tosh> ; sh:update """DELETE { $focusNode $predicate $value . a sh:PropertyShape ; sh:path sh:description ; dash:singleLine false ; graphql:name "descriptions" ; sh:description "The description(s) of the property, possibly in multiple languages." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "descriptions" ; sh:nodeKind sh:Literal ; sh:or dash:StringOrLangStringOrHTML ; . sh:MaxLengthConstraintComponent-maxLength sh:group tosh:StringBasedConstraintPropertyGroup ; sh:order 4 ; . sh:MinCountConstraintComponent-minCount sh:group tosh:CardinalityConstraintPropertyGroup ; sh:order 0 ; . sh:MinExclusiveConstraintComponent-minExclusive tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; sh:group tosh:ValueRangeConstraintPropertyGroup ; sh:order 0 ; . sh:MinInclusiveConstraintComponent dash:propertySuggestionGenerator [ sh:datatype xsd:string ; sh:maxCount 1 ; sh:name "details endpoint" ; . tosh:PropertyShape-editor a sh:PropertyShape ; sh:path dash:editor ; dash:editor dash:InstancesSelectEditor ; sh:class dash:Editor ; sh:description "The editor component that should be used to edit values of this property." ; ] ; . sh:MinInclusiveConstraintComponent-minInclusive tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; sh:group tosh:ValueRangeConstraintPropertyGroup ; sh:order 1 ; . sh:MinLengthConstraintComponent-minLength sh:group tosh:StringBasedConstraintPropertyGroup ; sh:order 3 ; . sh:NodeConstraintComponent sh:nodeValidator [ sh:order "0"^^xsd:decimal ; . tosh:PropertyShape-hidden a sh:PropertyShape ; sh:path dash:hidden ; dash:editor dash:BooleanSelectEditor ; sh:datatype xsd:boolean ; sh:description "True to mark this property as hidden in user interface, yet still used in data tasks." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:order "30"^^xsd:decimal ; . tosh:PropertyShape-indexed a sh:PropertyShape ; sh:path dash:indexed ; sh:datatype xsd:boolean ; sh:description "True to indicate that the values of this shall be indexed, forming ordered arrays." ; sh:maxCount 1 ; sh:name "indexed" ; . tosh:PropertyShape-name a sh:PropertyShape ; sh:path sh:name ; ] ; . sh:NodeConstraintComponent-node tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 0 ; . sh:NodeKindConstraintComponent-nodeKind tosh:editWidget <http://topbraid.org/tosh.ui#NodeKindEditor> ; sh:group tosh:ValueTypeConstraintPropertyGroup ; sh:name "value kinds" ; sh:order 0 ; . sh:NotConstraintComponent sh:nodeValidator [ sh:maxCount 1 ; sh:name "never materialize" ; sh:order "11"^^xsd:decimal ; . tosh:PropertyShape-order a sh:PropertyShape ; sh:path sh:order ; sh:description "The relative order of this property shape compared to others." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "order" ; sh:or ( [ sh:datatype xsd:decimal ; ] [ sh:datatype xsd:integer ; ] ) ; sh:order "1"^^xsd:decimal ; . tosh:PropertyShape-path a sh:PropertyShape ; ] ; . sh:NotConstraintComponent-not tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 10 ; . sh:OrConstraintComponent sh:nodeValidator [ a sh:PropertyShape ; sh:path dash:propertyRole ; sh:class dash:PropertyRole ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "role" ; sh:order "40"^^xsd:decimal ; . tosh:PropertyShape-readOnly a sh:PropertyShape ; sh:path dash:readOnly ; dash:editor dash:BooleanSelectEditor ; dash:viewer dash:NodeExpressionViewer ; sh:datatype xsd:boolean ; sh:description """If set to true then the values of this property should not be editable in the user interface. Note that low-level access such as source code editors may still allow editing, but form-based editors would not. More generally, the values of this property are SHACL node expressions, e.g. function calls, in which case the property counts as read-only if the expression evaluates to true.""" ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:order "20"^^xsd:decimal ; . tosh:PropertyShape-values a sh:PropertyShape ; sh:path sh:values ; dash:viewer dash:NodeExpressionViewer ; ] ; . sh:OrConstraintComponent-or tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 12 ; . sh:PatternConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; dash:propertySuggestionGenerator tosh:ReplaceWithDefaultValueSuggestionGenerator ; . sh:PatternConstraintComponent-flags tosh:editWidget <http://topbraid.org/tosh.ui#FlagsEditor> ; sh:group tosh:StringBasedConstraintPropertyGroup ; sh:maxCount 1 ; sh:name "regex flags" ; . sh:PatternConstraintComponent-pattern tosh:editWidget swa:PlainTextFieldEditor ; sh:group tosh:StringBasedConstraintPropertyGroup ; sh:maxCount 1 ; sh:name "regex pattern" ; sh:class dash:Viewer ; sh:description "The viewer component that should be used to render values of this property." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:nodeKind sh:IRI ; sh:order "10"^^xsd:decimal ; . tosh:PropertyShapeView a sh:NodeShape ; rdfs:comment "Base view shape for either datatype or object property shapes." ; rdfs:label "Property shape view" ; sh:QualifiedMaxCountConstraintComponent-qualifiedMaxCount sh:group tosh:ComplexConstraintPropertyGroup ; sh:maxCount 1 ; sh:order 3 ; . sh:QualifiedMinCountConstraintComponent-qualifiedMinCount sh:group tosh:ComplexConstraintPropertyGroup ; sh:maxCount 1 ; sh:order 2 ; . sh:QualifiedMinCountConstraintComponent-qualifiedValueShape tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:maxCount 1 ; sh:order 1 ; . sh:UniqueLangConstraintComponent-uniqueLang sh:group tosh:StringBasedConstraintPropertyGroup ; sh:order 8 ; . sh:XoneConstraintComponent sh:nodeValidator [ sh:property tosh:PropertyShapeView-qualifiedValueShapesDisjoint ; sh:property tosh:Shape-deactivated ; sh:property tosh:Shape-severity ; sh:property sh:DisjointConstraintComponent-disjoint ; sh:property sh:EqualsConstraintComponent-equals ; sh:property sh:MaxCountConstraintComponent-maxCount ; sh:property sh:MinCountConstraintComponent-minCount ; sh:property sh:SPARQLConstraintComponent-sparql ; . tosh:PropertyShapeView-indexed a sh:PropertyShape ; sh:path dash:indexed ; sh:datatype xsd:boolean ; sh:description "Indicates whether the values are sorted by an index. The user interface will display them in-order." ; sh:group tosh:ReificationPropertyGroup ; sh:maxCount 1 ; sh:name "indexed" ; sh:order "1"^^xsd:decimal ; . tosh:PropertyShapeView-message a sh:PropertyShape ; sh:path sh:message ; sh:description "The message that shall be generated for all constraint violations produced by this property shape." ; sh:group tosh:ValidationPropertyGroup ; sh:name "messages" ; ] ; . sh:XoneConstraintComponent-xone tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 13 ; . sh:count a rdf:Property ; sh:description "A display label of the sh:path based on qnames." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "property path" ; sh:order "2"^^xsd:decimal ; sh:values [ sh:else [ <http://uispin.org/ui#label> ( [ sh:path sh:path ; ] ) ; ] ; sh:if [ <http://datashapes.org/sparql#isIRI> ( [ sh:path sh:path ; ] ) ; ] ; sh:then [ <http://topbraid.org/sparqlmotionfunctions#qname> ( [ sh:path sh:path ; ] ) ; ] ; ] ; . tosh:PropertyShapeView-qualifiedMaxCount a sh:PropertyShape ; sh:path sh:qualifiedMaxCount ; sh:datatype xsd:integer ; sh:description "The maximum number of values that may conform to the qualified value shape." ; sh:group tosh:QualifiedCardinalityConstraintsPropertyGroup ; sh:maxCount 1 ; sh:name "qualified max count" ; sh:order "1"^^xsd:decimal ; . tosh:PropertyShapeView-qualifiedMinCount a sh:PropertyShape ; sh:path sh:qualifiedMinCount ; sh:datatype xsd:integer ; sh:description "The minimum number of values that must conform to the qualified value shape." ; sh:group tosh:QualifiedCardinalityConstraintsPropertyGroup ; sh:maxCount 1 ; sh:name "qualified min count" ; sh:order "0"^^xsd:decimal ; . tosh:PropertyShapeView-qualifiedValueShape a sh:PropertyShape ; sh:path sh:qualifiedValueShape ; sh:class sh:NodeShape ; sh:description "The shape that the specified number of values must conform to." ; sh:group tosh:QualifiedCardinalityConstraintsPropertyGroup ; sh:name "qualified value shape" ; sh:order "2"^^xsd:decimal ; . tosh:PropertyShapeView-qualifiedValueShapesDisjoint a sh:PropertyShape ; sh:path sh:qualifiedValueShapesDisjoint ; sh:datatype xsd:boolean ; sh:description "True to treat all qualified values as disjoint." ; sh:group tosh:QualifiedCardinalityConstraintsPropertyGroup ; sh:maxCount 1 ; sh:name "qualified value shapes disjoint" ; sh:order "3"^^xsd:decimal ; . tosh:PropertyTableViewer a dash:MultiViewer ; dash:hidden true ; rdfs:label "Property table viewer" ; . tosh:QualifiedCardinalityConstraintsPropertyGroup a sh:PropertyGroup ; rdfs:comment "The properties in this group are used together to express that a certain number of values must conform to a given shape." ; rdfs:label "Qualified Cardinality Constraints" ; sh:order "77"^^xsd:decimal ; . tosh:QueryTestCase-expectedResult a sh:PropertyShape ; sh:path dash:expectedResult ; dash:singleLine false ; sh:description "The expected result set, as a JSON string." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "expected result" ; sh:or ( [ sh:datatype rdf:JSON ; ] [ sh:datatype xsd:string ; ] ) ; . tosh:RDFSOWLClassView a sh:NodeShape ; dash:applicableToClass rdfs:Class ; rdfs:comment "A node shape collecting RDFS and OWL axioms for classes." ; rdfs:label "RDFS/OWL class view" ; sh:property tosh:Class-disjointWith ; sh:property tosh:Class-domain-inverse ; sh:property tosh:Class-equivalentClass ; sh:property tosh:Class-range-inverse ; sh:property tosh:Class-subClassOf ; sh:property tosh:Class-subClassOf-inverse ; sh:property tosh:Resource-comment ; sh:property tosh:Resource-label ; sh:property tosh:Resource-type ; . tosh:RDFSPropertyAxiomsPropertyGroup a sh:PropertyGroup ; rdfs:label "RDFS Property Axioms" ; sh:order "15"^^xsd:decimal ; . tosh:ReferencesPropertyGroup a sh:PropertyGroup ; rdfs:comment "A property group typically used for incoming references or usages."^^rdf:HTML ; rdfs:label "References" ; sh:order "100"^^xsd:decimal ; . tosh:ReificationPropertyGroup a sh:PropertyGroup ; rdfs:label "Reification (Statements about Statements)" ; sh:order "90"^^xsd:decimal ; . tosh:ReplaceWithDefaultValueSuggestionGenerator a dash:SPARQLUpdateSuggestionGenerator ; rdfs:comment "Produces a suggestion to replace all values of the given predicate (which must exist) at the focus node to the default value declared at the shape that has caused the violation. Does nothing if the shape does not declare a sh:defaultValue. Deletes any old value of the property." ; rdfs:label "Replace with default value suggestion generator" ; sh:message "Replace with default value" ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT ?defaultValue WHERE { GRAPH $shapesGraph { $sourceShape sh:defaultValue ?defaultValue . } }""" ; sh:update """DELETE { $focusNode $predicate ?oldValue . } INSERT { $focusNode $predicate ?defaultValue . } WHERE { $focusNode $predicate ?oldValue . }""" ; . tosh:Resource-comment a sh:PropertyShape ; sh:path rdfs:comment ; dash:propertyRole dash:DescriptionRole ; dash:singleLine false ; graphql:name "comments" ; sh:description "The comments of this, possibly in multiple languages." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "comments" ; sh:or dash:StringOrLangStringOrHTML ; sh:order "1"^^xsd:decimal ; . tosh:Resource-label a sh:PropertyShape ; sh:path rdfs:label ; dash:propertyRole dash:LabelRole ; graphql:name "labels" ; sh:description "The display name(s) of this, possibly in multiple languages." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "labels" ; sh:or dash:StringOrLangString ; sh:order "0"^^xsd:decimal ; . tosh:Resource-type a sh:PropertyShape ; sh:path rdf:type ; graphql:name "types" ; sh:class rdfs:Class ; sh:description "The type(s) of this." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "types" ; sh:order "10"^^xsd:decimal ; . tosh:ResourceAction-jsCondition a sh:PropertyShape ; sh:path dash:jsCondition ; sh:datatype xsd:string ; sh:description "An (ADS) JavaScript expression that will be executed to determine whether the action is applicable to the selected resource in the current context. The variable focusNode can be queried here. The expression needs to return true for the action to be deemed suitable." ; sh:group tosh:ImplementationPropertyGroup ; sh:name "action pre-condition" ; sh:order "25"^^xsd:decimal ; . tosh:ResourceView a sh:NodeShape ; rdfs:comment "A generic view shape that can be used as fallback to display typical resources that have an rdfs:label and an rdfs:comment." ; rdfs:label "Resource view" ; sh:property tosh:Resource-comment ; sh:property tosh:Resource-label ; . tosh:Rule-condition a sh:PropertyShape ; sh:path sh:condition ; sh:description "The pre-conditions that must apply before a rule gets executed. The focus node must conform to all conditions, which must be shapes." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "conditions" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "40"^^xsd:decimal ; . tosh:Rule-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactivate the rule so that it will not get executed." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:Rule-order a sh:PropertyShape ; sh:path sh:order ; sh:description "The order of this rule relative to other rules at the same shape. Rules with lower order are executed first. Default value is 0. Rules with the same order cannot \"see\" each other's inferences." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "order" ; sh:or ( [ sh:datatype xsd:decimal ; ] [ sh:datatype xsd:integer ; ] ) ; sh:order "35"^^xsd:decimal ; . tosh:Rule-rule-inverse a sh:PropertyShape ; sh:path [ sh:inversePath sh:rule ; ] ; sh:class sh:Shape ; sh:description "The shapes or classes that the rule is attached to." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "rule of" ; sh:order "20"^^xsd:decimal ; . tosh:SHMinMaxEditor a dash:SingleEditor ; dash:hidden true ; rdfs:comment "An internally used editor for min/max range values of property shapes."^^rdf:HTML ; rdfs:label "SHACL Min Max Editor" ; . tosh:SPARQLAskExecutable-ask a sh:PropertyShape ; sh:path sh:ask ; dash:singleLine false ; sh:datatype xsd:string ; sh:description "The SPARQL ASK query string." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "ask" ; sh:order "1"^^xsd:decimal ; . tosh:SPARQLConstraint-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactive this constraint." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:SPARQLConstraint-message a sh:PropertyShape ; sh:path sh:message ; sh:description "The message(s) that should be produced for constraint violations. The messages may contain placeholders such as {$value} for any variable returned in the SELECT clause of the SPARQL query." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "messages" ; sh:or dash:StringOrLangString ; sh:order "20"^^xsd:decimal ; . tosh:SPARQLConstructExecutable-construct a sh:PropertyShape ; sh:path sh:construct ; dash:singleLine false ; sh:datatype xsd:string ; sh:description "The SPARQL CONSTRUCT query string." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "construct" ; sh:order "1"^^xsd:decimal ; . tosh:SPARQLExecutable-prefixes a sh:PropertyShape ; sh:path sh:prefixes ; sh:class owl:Ontology ; sh:description "The Ontology declaring the SHACL prefix declarations to use for the SPARQL query." ; sh:group tosh:ImplementationPropertyGroup ; sh:name "prefixes" ; sh:order "0"^^xsd:decimal ; . tosh:SPARQLSelectExecutable-select a sh:PropertyShape ; sh:path sh:select ; dash:singleLine false ; sh:datatype xsd:string ; sh:description "The SPARQL SELECT query string." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "select" ; sh:order "1"^^xsd:decimal ; . tosh:SPARQLUpdateExecutable-update a sh:PropertyShape ; sh:path sh:update ; dash:singleLine false ; sh:datatype xsd:string ; sh:description "The SPARQL UPDATE request string." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "update" ; sh:order "1"^^xsd:decimal ; . tosh:Script-js a sh:PropertyShape ; sh:path dash:js ; sh:datatype xsd:string ; sh:description "The implementation as JavaScript." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "JavaScript code" ; sh:order "20"^^xsd:decimal ; . tosh:Script-onAllValues a sh:PropertyShape ; sh:path dash:onAllValues ; sh:datatype xsd:boolean ; sh:description "If true then all value nodes will be available to the script at once, through the variable \"values\"." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "on all values" ; sh:order "0"^^xsd:decimal ; . tosh:ScriptConstraint-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactivate this constraint." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:ScriptConstraint-message a sh:PropertyShape ; sh:path sh:message ; sh:description "The message(s) to use for violations produced by this script." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "messages" ; sh:or dash:StringOrLangString ; sh:order "20"^^xsd:decimal ; . tosh:ScriptFunction-canWrite a sh:PropertyShape ; sh:path dash:canWrite ; sh:datatype xsd:boolean ; sh:description "True to allow this function to have side effects. By default, functions are not permitted to modify the graph as this would violate SPARQL contracts. However, if canWrite is true then the function will not be available as a SPARQL function and only be injected into the generated API in read/write mode." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "can write" ; sh:order "15"^^xsd:decimal ; . tosh:ScriptTestCase-expectedResult a sh:PropertyShape ; sh:path dash:expectedResult ; sh:description "The expected result of the evaluation, as JSON object as produced by the servlet, or true or false." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "expected result" ; sh:or ( [ sh:datatype rdf:JSON ; ] [ sh:datatype xsd:boolean ; ] ) ; sh:order "0"^^xsd:decimal ; . tosh:ScriptTestCase-focusNode a sh:PropertyShape ; sh:path dash:focusNode ; sh:description "The selected resource, which will become value of focusNode for the script, with its \"most suitable\" JavaScript class as type. Defaults to the test case itself." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "focus node" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "10"^^xsd:decimal ; . tosh:ScriptsPropertyGroup a sh:PropertyGroup ; rdfs:comment "Scripts based on Active Data Shapes." ; rdfs:label "Scripts" ; sh:order "30"^^xsd:decimal ; . tosh:Service-canWrite a sh:PropertyShape ; sh:path dash:canWrite ; sh:datatype xsd:boolean ; sh:description "True if this service can modify the data, i.e. it will execute in read/write mode. By default, all services are read-only." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "can write" ; . tosh:Service-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactivate this service." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:Service-responseContentType a sh:PropertyShape ; sh:path dash:responseContentType ; sh:datatype xsd:string ; sh:description "The content type (mime type) of the service response, defaulting to \"application/json\". Use \"void\" to return nothing." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "response content type" ; sh:order "10"^^xsd:decimal ; . tosh:SetToDefaultValueSuggestionGenerator a dash:SPARQLUpdateSuggestionGenerator ; rdfs:comment "Produces a suggestion to set the given predicate at the focus node to the default value declared at the shape that has caused the violation. Does nothing if the shape does not declare a sh:defaultValue. Deletes any old value of the property." ; rdfs:label "Set to default value suggestion generator" ; sh:message "Set to default value" ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT ?defaultValue WHERE { GRAPH $shapesGraph { $sourceShape sh:defaultValue ?defaultValue . } }""" ; sh:update """DELETE { $focusNode $predicate ?oldValue . } INSERT { $focusNode $predicate ?defaultValue . } WHERE { OPTIONAL { $focusNode $predicate ?oldValue . } }""" ; . tosh:Shape-datatypes a sh:PropertyShape ; sh:path tosh:datatypes ; dash:neverMaterialize true ; dash:viewer tosh:DatatypesViewer ; sh:description "Zero of more datatypes that value nodes can take. In SHACL, the typical pattern is to either use a single sh:datatype or a sh:or of multiple sh:datatype constraints. This inferred property here provides a unified way to access these two design patterns." ; sh:group tosh:TypeOfValuesPropertyGroup ; sh:name "datatypes" ; sh:nodeKind sh:IRI ; sh:order "0"^^xsd:decimal ; sh:values [ sh:union ( [ sh:path sh:datatype ; ] [ sh:path ( sh:or [ sh:zeroOrMorePath rdf:rest ; ] rdf:first sh:datatype ) ; ] ) ; ] ; . tosh:Shape-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactivate this shape, making it literally invisible and without any effect." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:Shape-severity a sh:PropertyShape ; sh:path sh:severity ; dash:editor dash:InstancesSelectEditor ; sh:class sh:Severity ; sh:description "The severity to be used for validation results produced by the constraints." ; sh:group tosh:ValidationPropertyGroup ; sh:maxCount 1 ; sh:name "severity" ; sh:order "0"^^xsd:decimal ; . tosh:ShapeInGraphConstraintComponent a sh:ConstraintComponent ; dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; rdfs:comment """A constraint component that can be used to verify that the value nodes have a given shape, where the shape validation is executed in a given graph. This can, for example, be used to verify that a given value is declared as an instance of a given class in some specified (not imported) graph. A typical design pattern is as follows: ex:NodeShape sh:property [ sh:path ex:myProperty ; sh:nodeKind sh:IRI ; tosh:graph <http://example.org/externalGraph> ; tosh:shapeInGraph [ sh:class ex:ExternalClass ; ] ; tosh:editor tosh:InstancesInGraphSelectEditor ; tosh:viewer tosh:URIInGraphViewer ; ] .""" ; rdfs:label "Shape in graph constraint component" ; sh:labelTemplate "Values must have shape {$shapeInGraph} defined in graph {$graph}" ; sh:message "Value does not have shape {$shapeInGraph} defined in graph {$graph}" ; sh:parameter [ a sh:Parameter ; sh:path tosh:graph ; sh:nodeKind sh:IRI ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:shapeInGraph ; sh:nodeKind sh:BlankNodeOrIRI ; ] ; sh:validator [ a sh:SPARQLAskValidator ; sh:ask """ASK { GRAPH $graph { FILTER tosh:hasShape($value, $shapeInGraph) } }""" ; sh:prefixes <http://topbraid.org/tosh> ; ] ; . tosh:StringConstraintsPropertyGroup a sh:PropertyGroup ; rdfs:label "String Constraints" ; sh:order "70"^^xsd:decimal ; . tosh:SystemNamespaceShape a sh:NodeShape ; rdfs:comment "A shape that detects whether the focus node is a URI that has a namespace from one of the system namespaces - RDF, RDFS, OWL etc. The list of actual system namespaces is represented via tosh:systemNamespace true triples." ; rdfs:label "System namespace shape" ; sh:sparql [ a sh:SPARQLConstraint ; sh:message "Not a IRI from a system namespace" ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT $this WHERE { FILTER (!isIRI($this) || (isIRI($this) && EXISTS { BIND (IRI(afn:namespace($this)) AS ?ns) . FILTER NOT EXISTS { ?ns tosh:systemNamespace true } . } )) . }""" ; ] ; . tosh:TargetsPropertyGroup a sh:PropertyGroup ; rdfs:label "Targets" ; sh:order "5"^^xsd:decimal ; . tosh:TeamworkPlatform a dash:ExecutionPlatform ; dash:includedExecutionPlatform tosh:TopBraidPlatform ; rdfs:comment "The platform consisting of TopBraid plus any teamwork features used by TopBraid EDG." ; rdfs:label "Teamwork platform" ; . tosh:TestCase-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "If set to true, this test case will be skipped." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "50"^^xsd:decimal ; . tosh:TestPropertiesPropertyGroup a sh:PropertyGroup ; rdfs:label "Test Properties" ; sh:order "20"^^xsd:decimal ; . tosh:TopBraidPlatform a dash:ExecutionPlatform ; rdfs:comment "The platform consisting of TopBraid." ; rdfs:label "TopBraid platform" ; . tosh:TripleRule-object a sh:PropertyShape ; sh:path sh:object ; dash:viewer dash:NodeExpressionViewer ; sh:description "The node expression producing the object(s) of the triple inferred by the rule." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "object" ; sh:order 2 ; . tosh:TripleRule-predicate a sh:PropertyShape ; sh:path sh:predicate ; dash:viewer dash:NodeExpressionViewer ; sh:description "The node expression producing the predicate(s) of the triple inferred by the rule." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "predicate" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order 1 ; . tosh:TripleRule-subject a sh:PropertyShape ; sh:path sh:subject ; dash:viewer dash:NodeExpressionViewer ; sh:description "The node expression producing the subject(s) of the triple inferred by the rule." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "subject" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order 0 ; . tosh:TypeOfValuesPropertyGroup a sh:PropertyGroup ; rdfs:label "Type of Values" ; sh:order "50"^^xsd:decimal ; . tosh:URIInGraphViewer a dash:SingleViewer ; rdfs:comment "A viewer for URI resources that have their data in a given graph that may be outside of the imports closure. The graph must be specified using a tosh:graph constraint for the property." ; rdfs:label "URI in graph viewer" ; . tosh:UseDeclaredDatatypeConstraintComponent a sh:ConstraintComponent ; dash:propertySuggestionGenerator [ a dash:SPARQLUpdateSuggestionGenerator ; sh:message "Change datatype of the invalid value to the specified sh:datatype" ; sh:prefixes <http://topbraid.org/tosh> ; sh:update """DELETE { $subject $predicate $object . } INSERT { $subject $predicate ?newObject . } WHERE { $subject sh:datatype ?datatype . BIND (spif:cast(?object, ?datatype) AS ?newObject) . }""" ; ] ; rdfs:comment "Constrains the value nodes to be either non-literals or literals that have the same datatype as the declared sh:datatype for the given constraint node. This is used, among others, in properties such as sh:hasValue and sh:minExclusive." ; rdfs:label "Use declared datatype constraint component" ; sh:parameter [ a sh:Parameter ; sh:path tosh:useDeclaredDatatype ; sh:datatype xsd:boolean ; sh:description "True to state that the datatype of literal values must be the same as the declared sh:datatype." ; sh:name "use declared datatype" ; ] ; sh:propertyValidator [ a sh:SPARQLSelectValidator ; sh:message "Datatype must match the declared datatype " ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """ SELECT DISTINCT $this ?value ?datatype WHERE { { FILTER ($useDeclaredDatatype) } $this sh:datatype ?datatype . $this $PATH ?value . FILTER (isLiteral(?value) && datatype(?value) != ?datatype) . }""" ; ] ; sh:targetClass sh:PropertyShape ; . tosh:ValidationPropertyGroup a sh:PropertyGroup ; rdfs:label "Validation" ; sh:order "30"^^xsd:decimal ; . tosh:ValidationTestCase-expectedResult a sh:PropertyShape ; sh:path dash:expectedResult ; sh:description "The expected validation report, either as instance of sh:ValidationReport or a Turtle string with one instance of sh:ValidationReport in it when parsed." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:name "expected result" ; sh:or ( [ sh:datatype xsd:string ; ] [ sh:class sh:ValidationReport ; ] ) ; sh:order "10"^^xsd:decimal ; . tosh:ValidationTestCase-includeSuggestions a sh:PropertyShape ; sh:path dash:includeSuggestions ; sh:datatype xsd:boolean ; sh:description "True to also generate and verify suggestions." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "include suggestions" ; sh:order "0"^^xsd:decimal ; . tosh:ValidationTestCase-validateShapes a sh:PropertyShape ; sh:path dash:validateShapes ; sh:datatype xsd:boolean ; sh:description "True to also validate shapes themselves." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "validate shapes" ; sh:order "5"^^xsd:decimal ; . tosh:ValueConstraintsPropertyGroup a sh:PropertyGroup ; rdfs:label "Value Constraints" ; sh:order "60"^^xsd:decimal ; . tosh:ValueRangePropertyGroup a sh:PropertyGroup ; rdfs:label "Value Range" ; sh:order "60"^^xsd:decimal ; . tosh:countShapesWithMatchResult a sh:SPARQLFunction ; rdfs:comment "Counts the number of shapes from a given rdf:List (?arg2) defined in a given shapes graph (?arg3) where tosh:hasShape returns the provided match value (true or false, ?arg4) for a given focus node (?arg1). The function produces a failure if one of the shapes validated to a failure." ; rdfs:label "count shapes with match result" ; sh:parameter [ a sh:Parameter ; sh:path sh:expectedValue ; sh:datatype xsd:boolean ; sh:description "The expected value of tosh:hasShape to count." ; sh:order 3.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path sh:focusNode ; sh:class rdfs:Resource ; sh:description "The focus node." ; sh:order 0.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path sh:shapes ; sh:class rdf:List ; sh:description "The list of shapes to walk through." ; sh:order 1.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path sh:shapesGraph ; sh:class rdfs:Resource ; sh:description "The shapes graph." ; sh:order 2.0 ; ] ; sh:prefixes <http://topbraid.org/tosh> ; sh:returnType xsd:integer ; sh:select """ # The SUM will fail with an error if one of the operands is not a number # (this mechanism is used to propagate errors from tosh:hasShape calls) SELECT (SUM(?s) AS ?result) WHERE { GRAPH $shapesGraph { $shapes rdf:rest*/rdf:first ?shape . } BIND (tosh:hasShape($focusNode, ?shape, true) AS ?hasShape) . BIND (IF(bound(?hasShape), IF(?hasShape = $expectedValue, 1, 0), 'error') AS ?s) . } """ ; . tosh:editGroupDescription a rdf:Property ; rdfs:comment "A description of the property group when in \"edit\" mode." ; rdfs:domain sh:PropertyGroup ; rdfs:label "edit group description" ; rdfs:range xsd:string ; . tosh:graph a rdf:Property ; rdfs:comment "The graph that the shape is validated in." ; rdfs:label "graph" ; . tosh:hasDatatype a sh:SPARQLAskValidator ; rdfs:comment "Checks whether a given node ($value) is a literal with a given datatype ($datatype), and that the literal is well-formed." ; rdfs:label "has datatype" ; sh:ask """ ASK { FILTER (datatype($value) = $datatype && spif:isValidForDatatype($value, $datatype)) . } """ ; sh:prefixes <http://topbraid.org/tosh> ; . tosh:hasShape a sh:Function ; dash:apiStatus dash:Experimental ; rdfs:comment """A built-in function of the TopBraid SHACL implementation. Can be used to validate a given (focus) node against a given shape, returning <code>true</code> if the node is valid. If executed within a SHACL validation engine, this uses the shapes graph that was provided when the engine started. If executed in other contexts, e.g. in a stand-alone SPARQL query, the function attempts to use the URI of the current default graph as the shapes graph. This may not always be supported. If called from within an SWP engine, the shapes graph is the current query graph."""^^rdf:HTML ; rdfs:label "has shape" ; sh:parameter [ a sh:Parameter ; sh:path tosh:node ; sh:description "The node to validate." ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:shape ; sh:description "The shape that the node is supposed to have." ; ] ; sh:returnType xsd:boolean ; . tosh:isHiddenClass a sh:SPARQLFunction ; dash:apiStatus dash:Experimental ; rdfs:comment "Checks if a given resource is supposed to be hidden in typical class displays. This applies to owl:Nothing, owl:NamedIndividual and owl:Restriction and any class that has dash:hidden true." ; rdfs:label "is hidden class" ; sh:ask """ASK { ?resource dash:hidden true . }""" ; sh:parameter [ a sh:Parameter ; sh:path tosh:resource ; sh:description "The node to check." ; sh:name "resource" ; sh:nodeKind sh:BlankNodeOrIRI ; ] ; sh:prefixes <http://topbraid.org/tosh> ; sh:returnType xsd:boolean ; . tosh:isInTargetOf a sh:Function ; dash:apiStatus dash:Experimental ; rdfs:comment "Checks whether a given node is in the target of a given shape." ; rdfs:label "is in target of" ; sh:parameter [ a sh:Parameter ; sh:path tosh:node ; sh:description "The node to check." ; sh:name "node" ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:shape ; sh:class sh:Shape ; sh:description "The shape that the node is supposed to be in the target of." ; sh:name "shape" ; ] ; sh:returnType xsd:boolean ; . tosh:isReificationURI a sh:Function ; dash:apiStatus dash:Stable ; rdfs:comment "Checks whether a given URI represents a reified triple." ; rdfs:label "is reification URI" ; sh:parameter [ a sh:Parameter ; sh:path tosh:uri ; sh:description "The URI to check." ; sh:nodeKind sh:IRI ; ] ; sh:returnType xsd:boolean ; . tosh:isReified a sh:Function ; dash:apiStatus dash:Stable ; rdfs:comment "Checks whether there are any reified values for a given triple." ; rdfs:label "is reified" ; sh:parameter [ a sh:Parameter ; sh:path tosh:object ; sh:description "The object of the triple to reify." ; sh:name "object" ; sh:order 2.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:predicate ; sh:description "The predicate of the triple to reify." ; sh:name "predicate" ; sh:nodeKind sh:IRI ; sh:order 1.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:subject ; sh:description "The subject of the triple to reify." ; sh:name "subject" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order 0.0 ; ] ; sh:returnType xsd:boolean ; . tosh:isSystemResource a sh:SPARQLFunction ; dash:apiStatus dash:Stable ; rdfs:comment "Checks if a given resource is from a namespace that is marked with tosh:systemNamespace true." ; rdfs:label "is system resource" ; sh:ask """ASK { BIND (IRI(afn:namespace($resource)) AS ?namespace) . FILTER
263
Misc minor updates, including a bug fix with GRAPH access in sh:values rules
131
.ttl
ttl
apache-2.0
TopQuadrant/shacl
407
<NME> tosh.ttl <BEF> # baseURI: http://topbraid.org/tosh # imports: http://datashapes.org/dash # prefix: tosh @prefix dash: <http://datashapes.org/dash#> . @prefix graphql: <http://datashapes.org/graphql#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix sh: <http://www.w3.org/ns/shacl#> . @prefix swa: <http://topbraid.org/swa#> . @prefix tosh: <http://topbraid.org/tosh#> . @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . dash: tosh:systemNamespace true ; . dash:Action sh:property tosh:Action-actionGroup ; sh:property tosh:Action-actionIconClass ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order "10"^^xsd:decimal ; . dash:HasValueWithClassConstraintComponent-hasValueWithClass sh:group tosh:OtherConstraintPropertyGroup ; . sh:property tosh:ActionTestCase-focusNode ; sh:property tosh:ActionTestCase-variables ; . dash:ChangeScript sh:group tosh:RelationshipPropertyGroup ; . dash:PrimaryKeyConstraintComponent-uriStart tosh:editWidget swa:PlainTextFieldEditor ; sh:group tosh:PrimaryKeyPropertyGroup ; . dash:RootClassConstraintComponent dash:CoExistsWithConstraintComponent-coExistsWith sh:group tosh:PropertyPairConstraintsPropertyGroup ; sh:order "0"^^xsd:decimal ; . dash:DetailsEditor dash:hidden true ; owl:versionInfo "This is not yet supported by TopBraid." ; . dash:FunctionTestCase sh:property tosh:FunctionTestCase-expectedResult ; sh:property tosh:FunctionTestCase-expression ; . dash:GraphStoreTestCase sh:property tosh:GraphStoreTestCase-expectedResult ; sh:property tosh:GraphStoreTestCase-uri ; . dash:IndexedConstraintComponent-indexed sh:group tosh:ReificationPropertyGroup ; sh:order "1"^^xsd:decimal ; . dash:InferencingTestCase sh:property tosh:InferencingTestCase-expectedResult ; . dash:JSTestCase sh:property tosh:JSTestCase-expectedResult ; . dash:MultiFunction sh:property tosh:Function-apiStatus ; sh:property tosh:MultiFunction-resultVariable ; . dash:NonRecursiveConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; . dash:NonRecursiveConstraintComponent-nonRecursive sh:group tosh:ValueConstraintsPropertyGroup ; sh:order "5"^^xsd:decimal ; . dash:PrimaryKeyConstraintComponent-uriStart sh:group tosh:StringConstraintsPropertyGroup ; sh:order "40"^^xsd:decimal ; . dash:PropertyRole sh:property tosh:Resource-comment ; sh:property tosh:Resource-label ; . dash:QueryTestCase sh:property tosh:QueryTestCase-expectedResult ; . dash:ReifiableByConstraintComponent-reifiableBy sh:group tosh:ReificationPropertyGroup ; sh:order "0"^^xsd:decimal ; . dash:ResourceAction sh:property tosh:ResourceAction-jsCondition ; . dash:RootClassConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; . dash:RootClassConstraintComponent-rootClass sh:group tosh:ValueConstraintsPropertyGroup ; sh:order "10"^^xsd:decimal ; . tosh:AboutPropertyGroup a sh:PropertyGroup ; rdfs:label "This Shape" ; sh:order 0 ; . tosh:CardinalityConstraintPropertyGroup a sh:PropertyGroup ; rdfs:label "Number of Values" ; sh:order 2 ; . tosh:ComplexConstraintPropertyGroup a sh:PropertyGroup ; tosh:editGroupDescription "Most edit fields in this section currently require Turtle source code, esp to enter blank node expressions. To reference existing shapes via their URI, enter them as <URI>." ; tosh:openable true ; rdfs:label "Complex Constraint Expressions" ; sh:order 9 ; . tosh:ConstraintMetadataPropertyGroup a sh:PropertyGroup ; sh:group tosh:AdvancedPropertyGroup ; sh:order "20"^^xsd:decimal ; . dash:ScriptFunction rdfs:comment "Produces a suggestion that would delete the offending value in the validation result from the focus node." ; rdfs:label "Delete triple suggestion generator" ; sh:message "Delete the invalid statement" ; sh:order 100 ; sh:update """DELETE { $focusNode $predicate $value . } sh:property tosh:Script-onAllValues ; $focusNode $predicate $value . }""" ; . tosh:DisplayPropertyGroup a sh:PropertyGroup ; rdfs:comment "A group for properties that are primarily for display purposes (names, ordering etc)." ; rdfs:label "Display Settings" ; sh:order 1 ; . tosh:InferencesPropertyGroup a sh:PropertyGroup ; a sh:PropertyShape ; rdfs:label "Inferences" ; sh:order "11"^^xsd:decimal ; . tosh:MemberShapeConstraintComponent a sh:ConstraintComponent ; rdfs:comment "Can be used to specify constraints on the members of a given list, assuming that the given sh:property has rdf:Lists as values. A violation is reported for each member of the list that does not comply with the constraints specified by the given shape." ; sh:description "The graph containing the test case." ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "test graph" ; sh:nodeKind sh:IRI ; ] ; . dash:UniqueValueForClassConstraintComponent-uniqueValueForClass sh:group tosh:ValueConstraintsPropertyGroup ; sh:order "20"^^xsd:decimal ; . dash:ValidationTestCase sh:property tosh:ValidationTestCase-expectedResult ; sh:property tosh:ValidationTestCase-includeSuggestions ; sh:property tosh:ValidationTestCase-validateShapes ; . dash:Widget sh:property tosh:Resource-comment ; sh:property tosh:Resource-label ; . dash:Widget-hidden sh:group tosh:DisplayPropertyGroup ; . <http://spinrdf.org/sp#> tosh:systemNamespace true ; . <http://spinrdf.org/spin#> a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Other Constraints" ; sh:order 10 ; . tosh:PrimaryKeyPropertyGroup a sh:PropertyGroup ; dash:generateClass dash:ConstraintReificationShape ; dash:generateClass rdf:Property ; dash:generateClass rdfs:Class ; dash:generateClass rdfs:Datatype ; dash:generateClass owl:Class ; a sh:NodeShape ; rdfs:label "Property group shape" ; sh:property [ sh:path sh:order ; sh:maxCount 1 ; ] ; dash:generatePrefixConstants "rdf" ; dash:generatePrefixConstants "rdfs" ; dash:generatePrefixConstants "sh" ; a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Relationship to Other Properties" ; sh:order 6 ; . tosh:PropertyShapeShape a sh:NodeShape ; Some of these may be of general use outside of TopBraid too.""" ; rdfs:label "TopBraid Data Shapes Library" ; owl:imports <http://datashapes.org/dash> ; sh:declare [ a sh:PrefixDeclaration ; sh:namespace "http://jena.hpl.hp.com/ARQ/function#"^^xsd:anyURI ; sh:prefix "afn" ; ] ; ] ; sh:property [ a sh:PropertyShape ; sh:path sh:values ; tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget <http://topbraid.org/tosh.ui#ValuesExpressionDiagramViewer> ; sh:group tosh:InferencesPropertyGroup ; sh:name "values" ; sh:order "1"^^xsd:decimal ; sh:sparql [ sh:message "sh:values must be accompanied by a sh:path that is an IRI." ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT $this ?value WHERE { $this $PATH ?value . FILTER NOT EXISTS { $this sh:path ?path . FILTER isIRI(?path) } }""" ; ] ; ] ; sh:property [ sh:path tosh:editWidget ; tosh:editWidget swa:WidgetDropDownEditor ; tosh:viewWidget swa:ResourceInUIGraphViewer ; sh:description "The swa:ObjectEditorClass that shall be used to edit values of this predicate." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "edit widget" ; sh:nodeKind sh:IRI ; sh:order 21 ; ] ; sh:property [ sh:path tosh:searchWidget ; tosh:editWidget swa:WidgetDropDownEditor ; tosh:viewWidget swa:ResourceInUIGraphViewer ; sh:description "The swa:ObjectFacetClass that shall be used to search for values of this predicate." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "search widget" ; sh:nodeKind sh:IRI ; sh:order 22 ; ] ; sh:property [ sh:path tosh:viewWidget ; tosh:editWidget swa:WidgetDropDownEditor ; tosh:viewWidget swa:ResourceInUIGraphViewer ; sh:description "The swa:ObjectViewerClass that shall be used to view values of this predicate." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "view widget" ; sh:nodeKind sh:IRI ; sh:order 20 ; ] ; sh:property [ sh:path sh:defaultValue ; tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; tosh:viewWidget <http://topbraid.org/tosh.ui#DefaultValueViewer> ; sh:description "The default value to be used for this property if no other value has been asserted. This may be a constant value or a SHACL node expression, in which case the values can be derived from other values. Default values are typically inferred and not stored as RDF statements." ; sh:group tosh:ValueTypeConstraintPropertyGroup ; ] ; sh:property [ sh:path sh:description ; tosh:editWidget swa:TextAreaEditor ; sh:description "A human-readable description of the role of the property in the constraint." ; sh:group tosh:DisplayPropertyGroup ; sh:name "description" ; sh:order 2 ; ] ; sh:property [ sh:path sh:disjoint ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order 1 ; ] ; sh:property [ sh:path sh:equals ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order 0 ; ] ; sh:property [ sh:path sh:group ; sh:description "The sh:PropertyGroup that the property belongs to." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "group" ; sh:order 10 ; ] ; sh:property [ sh:path sh:lessThan ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order 2 ; ] ; sh:property [ sh:path sh:lessThanOrEquals ; sh:group tosh:PropertyPairConstraintPropertyGroup ; sh:order 3 ; ] ; sh:property [ sh:path sh:name ; tosh:editWidget swa:TextFieldEditorWithLang ; sh:description "The display name of the property." ; sh:group tosh:DisplayPropertyGroup ; sh:name "name" ; sh:order 1 ; ] ; sh:property [ sh:path sh:order ; sh:description "The relative position of the property among its peers, e.g. a property with order 5 shows up before one with order 6." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "order" ; sh:order 11 ; ] ; sh:property [ sh:path sh:path ; tosh:editWidget <http://topbraid.org/tosh.ui#PathEditor> ; tosh:viewWidget <http://topbraid.org/tosh.ui#PathViewer> ; sh:group tosh:AboutPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "on property" ; sh:order 0 ; ] ; sh:sparql [ sh:message "Property shapes cannot have both class and datatype constraints." ; For parameters that declare dash:mimeTypes (i.e. file upload parameters), the value needs to be the path to a file relative to the workspace root. This file will be temporarily uploaded for the duration of the test case execution.""" ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "variables" ; sh:order "2"^^xsd:decimal ; . tosh:AdvancedPropertyGroup a sh:PropertyGroup ; rdfs:label "Advanced" ; sh:order "95"^^xsd:decimal ; . a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Relationship" ; sh:order 8 ; . tosh:RemoteValuesPropertyGroup a sh:PropertyGroup ; sh:name "deactivated" ; sh:order "10"^^xsd:decimal ; . tosh:ChangeScript-order a sh:PropertyShape ; sh:path sh:order ; sh:description "The relative order of this script compared to other change scripts. The default value is 0. Scripts with lower numbers are executed first." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "order" ; sh:or ( [ sh:datatype xsd:decimal ; ] [ sh:datatype xsd:integer ; ] ) ; sh:order "40"^^xsd:decimal ; . tosh:Class-ShapeScript a dash:ShapeScript ; dash:js """ /** * Returns this class as an instance of sh:NodeShape. * @returns {sh_NodeShape} */ asNodeShape() { return sh.asNodeShape(this); } /** * @callback rdfs_Class_callback * @param {rdfs_Class} class the visited class */ /** * Performs a depth-first traversal this class and its superclasses, visiting each (super) class * once until the callback function returns a non-null/undefined result. This becomes the result of this function. * The order in which sibling classes are traversed is undefined, so results may be inconsistent in * multiple-inheritance scenarios. * @param {rdfs_Class_callback} callback the callback for each class * @param {Set} [reached] the Set of reached URI strings, used internally * @returns the return value of the first callback that returned any value */ walkSuperclasses(callback, reached) { if(!reached) { reached = new Set(); tosh:ShapeInGraphConstraintComponent a sh:ConstraintComponent ; dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; rdfs:comment "A constraint component that can be used to verify that the value nodes have a given shape, where the shape validation is executed in a given graph. This can, for example, be used to verify that a given value is declared as an instance of a given class in some specified (not imported) graph." ; rdfs:label "Shape in graph constraint component" ; sh:labelTemplate "Values must have shape {$shapeInGraph} defined in graph {$graph}" ; sh:message "Value does not have shape {$shapeInGraph} defined in graph {$graph}" ; sh:path dash:abstract ; sh:datatype xsd:boolean ; sh:description "States whether this class is abstract, i.e. cannot have direct instances. Abstract classes are typically used to defined shared properties of its subclasses." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "abstract" ; sh:order "30"^^xsd:decimal ; . tosh:Class-classIcon a sh:PropertyShape ; sh:path tosh:classIcon ; dash:hidden true ; dash:propertyRole dash:IconRole ; sh:datatype xsd:string ; sh:defaultValue "http://datashapes.org/icons/class.svg" ; sh:description "Used to return the default icon for all classes." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "class icon" ; sh:order "1"^^xsd:decimal ; . tosh:Class-constructor a sh:PropertyShape ; sh:path dash:constructor ; graphql:name "constructorScript" ; sh:class dash:Constructor ; sh:description "The Constructor that shall be used to create new instances of this class or its subclasses." ; sh:group tosh:ScriptsPropertyGroup ; sh:maxCount 1 ; sh:name "constructor" ; sh:order "20"^^xsd:decimal ; . tosh:Class-disjointWith a sh:PropertyShape ; sh:path owl:disjointWith ; sh:class owl:Class ; sh:group tosh:OWLAxiomsPropertyGroup ; sh:name "disjoint with" ; sh:order "1"^^xsd:decimal ; . tosh:Class-domain-inverse a sh:PropertyShape ; sh:path [ sh:inversePath rdfs:domain ; ] ; dash:editor dash:PropertyAutoCompleteEditor ; sh:class rdf:Property ; sh:description "The properties that declare to have this class in their domain." ; sh:group tosh:RDFSPropertyAxiomsPropertyGroup ; tosh:ShapeShape-severity a sh:PropertyShape ; sh:path sh:severity ; tosh:editWidget swa:InstancesSelectEditor ; sh:class sh:Severity ; sh:description "The severity to be used for validation results produced by the associated constraint." ; sh:group tosh:AboutPropertyGroup ; sh:path owl:equivalentClass ; sh:class owl:Class ; sh:group tosh:OWLAxiomsPropertyGroup ; sh:name "equivalent classes" ; sh:order "0"^^xsd:decimal ; a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Constraints for Strings and Text" ; sh:order 7 ; . tosh:SystemNamespaceShape a sh:NodeShape ; sh:maxCount 1 ; sh:name "hidden" ; sh:order "0"^^xsd:decimal ; . tosh:Class-range-inverse a sh:PropertyShape ; sh:path [ sh:inversePath rdfs:range ; ] ; dash:editor dash:PropertyAutoCompleteEditor ; sh:class rdf:Property ; sh:description "The properties that have this class in their rdfs:range." ; sh:group tosh:RDFSPropertyAxiomsPropertyGroup ; sh:name "range of" ; sh:nodeKind sh:IRI ; sh:order "1"^^xsd:decimal ; . tosh:Class-resourceAction a sh:PropertyShape ; sh:path dash:resourceAction ; graphql:name "resourceActions" ; sh:class dash:ResourceAction ; sh:description "The Resource Actions that can be applied to instances of this class." ; sh:group tosh:ScriptsPropertyGroup ; rdfs:comment "The platform consisting of TopBraid." ; rdfs:label "TopBraid platform" ; . tosh:UseDeclaredDatatypeConstraintComponent a sh:ConstraintComponent ; dash:propertySuggestionGenerator [ sh:order "10"^^xsd:decimal ; . tosh:Class-subClassOf a sh:PropertyShape ; sh:path rdfs:subClassOf ; graphql:name "superclasses" ; sh:class rdfs:Class ; sh:description "The (direct) parent classes of this class." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "superclasses" ; sh:order "20"^^xsd:decimal ; . tosh:Class-subClassOf-inverse a sh:PropertyShape ; sh:path [ sh:inversePath rdfs:subClassOf ; ] ; dash:hidden true ; graphql:name "subclasses" ; sh:class rdfs:Class ; sh:description "The (direct) subclasses of this class." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "subclasses" ; sh:order "21"^^xsd:decimal ; . tosh:ConstraintComponent-localConstraint a sh:PropertyShape ; sh:path dash:localConstraint ; sh:datatype xsd:boolean ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "local constraint" ; sh:order "10"^^xsd:decimal ; . tosh:ConstraintComponent-message a sh:PropertyShape ; sh:path sh:message ; sh:description "The message to generate on violations." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "messages" ; a sh:PropertyGroup ; tosh:openable true ; rdfs:label "Min/Max Values" ; sh:order 5 ; . tosh:ValueTypeConstraintPropertyGroup a sh:PropertyGroup ; tosh:editGroupDescription "Hint: Use \"or\" under Complex Constraints to represent choices between multiple value types." ; rdfs:comment "A property group for constraint parameters that restrict the value types of values." ; rdfs:label "Type of Values" ; sh:order 3 ; . tosh:closed a rdf:Property ; a owl:DeprecatedProperty ; rdfs:comment "If set to true, then the corresponding form section will be closed by default." ; rdfs:domain sh:PropertyGroup ; rdfs:label "closed" ; rdfs:range xsd:boolean ; . tosh:ConstraintComponent-propertyValidator a sh:PropertyShape ; sh:path sh:propertyValidator ; sh:class sh:Validator ; sh:description "The validator(s) used to evaluate a constraint in the context of a property shape." ; sh:path sh:expectedValue ; sh:datatype xsd:boolean ; sh:description "The expected value of tosh:hasShape to count." ; sh:order 3 ; ] ; sh:parameter [ sh:path sh:focusNode ; sh:class rdfs:Resource ; sh:description "The focus node." ; sh:order 0 ; ] ; sh:parameter [ sh:path sh:shapes ; sh:class rdf:List ; sh:description "The list of shapes to walk through." ; sh:order 1 ; ] ; sh:parameter [ sh:path sh:shapesGraph ; sh:class rdfs:Resource ; sh:description "The shapes graph." ; sh:order 2 ; ] ; sh:prefixes <http://topbraid.org/tosh> ; sh:returnType xsd:integer ; rdfs:label "Attribute view" ; sh:node tosh:PropertyShapeView ; sh:property dash:PrimaryKeyConstraintComponent-uriStart ; sh:property dash:SingleLineConstraintComponent-singleLine ; sh:property tosh:Shape-datatypes ; sh:property sh:LanguageInConstraintComponent-languageIn ; sh:property sh:LessThanConstraintComponent-lessThan ; sh:property sh:LessThanOrEqualsConstraintComponent-lessThanOrEquals ; sh:property sh:MaxExclusiveConstraintComponent-maxExclusive ; sh:property sh:MaxInclusiveConstraintComponent-maxInclusive ; sh:property sh:MaxLengthConstraintComponent-maxLength ; sh:property sh:MinExclusiveConstraintComponent-minExclusive ; sh:property sh:MinInclusiveConstraintComponent-minInclusive ; sh:property sh:MinLengthConstraintComponent-minLength ; sh:property sh:PatternConstraintComponent-flags ; sh:property sh:PatternConstraintComponent-pattern ; sh:property sh:UniqueLangConstraintComponent-uniqueLang ; rdfs:label "edit group description" ; rdfs:range xsd:string ; . tosh:editWidget a rdf:Property ; rdfs:label "edit widget" ; rdfs:range swa:ObjectEditorClass ; . tosh:graph a rdf:Property ; rdfs:comment "The graph that the shape is validated in." ; tosh:DefinitionPropertyGroup a sh:PropertyGroup ; rdfs:label "Definition" ; sh:order "0"^^xsd:decimal ; . tosh:DeleteTripleSuggestionGenerator a dash:SPARQLUpdateSuggestionGenerator ; rdfs:comment "Produces a suggestion that would delete the offending value in the validation result from the focus node." ; rdfs:label "Delete triple suggestion generator" ; sh:message "Delete the invalid statement" ; sh:order 100.0 ; sh:update """DELETE { $focusNode $predicate $value . } WHERE { $focusNode $predicate $value . }""" ; . tosh:DependentEnumSelectEditor a dash:SingleEditor ; rdfs:comment """A drop-down editor for enumerated values that are dynamically determined via a node shape that has sh:target dash:HasValueTarget. Example: states:USAddressShape rdf:type sh:NodeShape ; rdfs:label \"US Address shape\" ; sh:property [ rdf:type sh:PropertyShape ; sh:path states:state ; sh:in ( ] ; sh:returnType xsd:boolean ; . tosh:isInTargetOf a sh:Function ; rdfs:comment "Checks whether a given node is in the target of a given shape." ; sh:group tosh:DefinitionPropertyGroup ; sh:in ( dash:Experimental dash:Stable dash:Deprecated ) ; sh:maxCount 1 ; sh:name "API status" ; sh:order "15"^^xsd:decimal ; . tosh:Function-cachable ] ; sh:returnType xsd:boolean ; . tosh:isSystemResource a sh:SPARQLFunction ; rdfs:comment "Checks if a given resource is from a namespace that is marked with tosh:systemNamespace true." ; sh:path dash:expectedResult ; sh:datatype xsd:string ; sh:description "The expected RDF graph, as a Turtle string." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:order "10"^^xsd:decimal ; . tosh:GraphStoreTestCase-uri a sh:PropertyShape ; sh:path dash:uri ; sh:datatype xsd:anyURI ; sh:description "The URI of the graph to load." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "uri" ; sh:order "0"^^xsd:decimal ; . tosh:ImplementationPropertyGroup a sh:PropertyGroup ; rdfs:label "Implementation" ; sh:order "10"^^xsd:decimal ; . tosh:IncludedScript-exports a sh:PropertyShape ; sh:path dash:exports ; sh:datatype xsd:string ; sh:description "Declares the symbols that shall be exported from the surrounding module, e.g. for use in Node.js applications." ; sh:group tosh:ImplementationPropertyGroup ; sh:name "exports" ; sh:order "30"^^xsd:decimal ; rdfs:label "openable" ; rdfs:range xsd:boolean ; . tosh:searchWidget a rdf:Property ; rdfs:label "search widget" ; rdfs:range swa:ObjectFacetClass ; . tosh:shaclExists a sh:Function ; sh:name "member shape" ; . tosh:ModifyAction-skipPreview a sh:PropertyShape ; sh:path dash:skipPreview ; sh:datatype xsd:boolean ; sh:description "For actions that take no parameters, this can be set to true to skip any means for the user to preview the action. It will instead directly execute the modification." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "skip preview" ; sh:order "11"^^xsd:decimal ; . tosh:MultiFunction-resultVariable a sh:PropertyShape ; sh:path dash:resultVariable ; sh:class sh:Parameter ; sh:description "The result variables." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "result variables" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "30"^^xsd:decimal ; . tosh:NodeShape-ShapeScript a dash:ShapeScript ; dash:js """ /** * Returns this class as an instance of rdfs_Class, assuming this node shape is also a class. * @returns {rdfs_Class} */ asClass() { return rdfs.asClass(this); } /** * Gets the \"nearest\" constraint of a given type and a given path property. Deactivated shapes are skipped. * For example, call it with (ex.myProperty, sh.datatype) to find the closest sh:datatype constraint for ex:myProperty. * @param {NamedNode} path the property that is the sh:path of matching property shapes * @param {NamedNode} predicate the property to fetch the nearest value of */ nearestPropertyShapeValue(path, predicate) { return this.walkSupershapes(s => { if(!s.deactivated) { let ps = s.properties; for(let i = 0; i < ps.length; i++) { if(!ps[i].deactivated && graph.contains(ps[i], sh.path, path)) { let value = ps[i].value(predicate); if(value !== null && value !== undefined) { return value; } } } } }) } /** * @callback sh_NodeShape_callback * @param {sh_NodeShape} nodeShape the visited node shape */ /** * Performs a depth-first traversal of this and its superclasses (via rdfs:subClassOf) and supershapes (via sh:node), * visiting each (super) shape once until the callback function returns a non-null/undefined result. This becomes the result of this function. * The order in which sibling parents are traversed is undefined. * @param {sh_NodeShape_callback} callback the callback for each shape * @param {Set} [reached] the Set of reached URI strings, used internally but may also be used to terminate at certain supers * @returns the return value of the first callback that returned any value */ walkSupershapes(callback, reached) { if(!reached) { reached = new Set(); } if(!reached.has(this.uri)) { reached.add(this.uri); let result = callback(this); if(result !== undefined && result !== null) { return result; } let superClasses = this.asClass().superclasses; for(let i = 0; i < superClasses.length; i++) { result = superClasses[i].asNodeShape().walkSupershapes(callback, reached); if(result !== undefined && result !== null) { return result; } } let superShapes = this.supershapes; for(let i = 0; i < superShapes.length; i++) { result = superShapes[i].walkSupershapes(callback, reached); if(result !== undefined && result !== null) { return result; } } } } """ ; . tosh:NodeShape-applicableToClass a sh:PropertyShape ; sh:path dash:applicableToClass ; sh:class rdfs:Class ; sh:description "Links a node shape with the classes that it can be applied to." ; sh:group tosh:TargetsPropertyGroup ; sh:name "applicable to classes" ; sh:nodeKind sh:IRI ; sh:order "10"^^xsd:decimal ; . tosh:NodeShape-defaultViewForRole a sh:PropertyShape ; sh:path dash:defaultViewForRole ; dash:editor tosh:GovernanceRoleSelectEditor ; dash:viewer tosh:GovernanceRoleViewer ; sh:description "The user roles that this shape shall be used as default view for." ; sh:group tosh:TargetsPropertyGroup ; sh:name "default view for roles" ; sh:nodeKind sh:IRI ; owl: tosh:systemNamespace true ; . sh: tosh:systemNamespace true ; . sh:minus sh:this ; sh:nodes [ sh:distinct [ sh:path [ sh:oneOrMorePath [ sh:alternativePath ( rdfs:subClassOf sh:node ) ; ] ; ] ; ] ; ] ; ] ; ] ; . tosh:NodeShape-node a sh:PropertyShape ; sh:path sh:node ; graphql:name "supershapes" ; sh:description "The node shapes that this must also conform to, forming a kind of inheritance between shapes similar to a subclass-of relationship." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "node (super shapes)" ; sh:node sh:NodeShape ; sh:nodeKind sh:BlankNodeOrIRI ; ] ; . sh:AndConstraintComponent-and tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 11 ; . sh:ClassConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; sh:name "target classes" ; sh:nodeKind sh:IRI ; sh:order "0"^^xsd:decimal ; . tosh:NodeShape-targetObjectsOf a sh:PropertyShape ; sh:path sh:targetObjectsOf ; sh:group tosh:TargetsPropertyGroup ; sh:name "target objects of" ; sh:node rdf:Property ; sh:nodeKind sh:IRI ; sh:order "1"^^xsd:decimal ; . tosh:NodeShape-targetSubjectsOf a sh:PropertyShape ; sh:path sh:targetSubjectsOf ; sh:group tosh:TargetsPropertyGroup ; sh:name "target subjects of" ; sh:node rdf:Property ; sh:nodeKind sh:IRI ; sh:order "2"^^xsd:decimal ; . tosh:NodeShapeConstraintsShape a sh:NodeShape ; rdfs:comment "A shape that can be used to validate the syntax of node shapes, and to enter constraints for node shapes on forms." ; rdfs:label "Node shape constraints" ; . sh:ClassConstraintComponent-class sh:group tosh:ValueTypeConstraintPropertyGroup ; sh:order 2 ; . sh:ClosedConstraintComponent-closed sh:group tosh:OtherConstraintPropertyGroup ; sh:property sh:ClosedConstraintComponent-ignoredProperties ; sh:property sh:DatatypeConstraintComponent-datatype ; sh:property sh:HasValueConstraintComponent-hasValue ; sh:property sh:InConstraintComponent-in ; sh:property sh:LanguageInConstraintComponent-languageIn ; sh:property sh:MaxExclusiveConstraintComponent-maxExclusive ; sh:property sh:MaxInclusiveConstraintComponent-maxInclusive ; sh:property sh:MaxLengthConstraintComponent-maxLength ; sh:property sh:MinExclusiveConstraintComponent-minExclusive ; sh:property sh:MinInclusiveConstraintComponent-minInclusive ; sh:property sh:MinLengthConstraintComponent-minLength ; sh:property sh:NodeKindConstraintComponent-nodeKind ; sh:property sh:PatternConstraintComponent-flags ; sh:property sh:PatternConstraintComponent-pattern ; sh:property sh:SPARQLConstraintComponent-sparql ; sh:targetClass sh:NodeShape ; . tosh:NumberOfValuesPropertyGroup a sh:PropertyGroup ; rdfs:label "Number of Values" ; sh:order "40"^^xsd:decimal ; . tosh:OWLAxiomsPropertyGroup a sh:PropertyGroup ; rdfs:label "OWL Axioms" ; sh:order "17"^^xsd:decimal ; . tosh:ObjectPropertyShapeView a sh:NodeShape ; rdfs:comment "The default view shape for property shapes on object values." ; rdfs:label "Relationship view" ; sh:node tosh:PropertyShapeView ; sh:property dash:NonRecursiveConstraintComponent-nonRecursive ; sh:property dash:RootClassConstraintComponent-rootClass ; sh:property dash:StemConstraintComponent-stem ; sh:property dash:SymmetricConstraintComponent-symmetric ; sh:property tosh:ObjectPropertyShapeView-node ; sh:property sh:ClassConstraintComponent-class ; sh:property sh:NodeKindConstraintComponent-nodeKind ; . tosh:ObjectPropertyShapeView-node a sh:PropertyShape ; sh:path sh:node ; dash:reifiableBy dash:ConstraintReificationShape ; sh:validator tosh:hasDatatype ; . sh:DatatypeConstraintComponent-datatype tosh:editWidget <http://topbraid.org/tosh.ui#DatatypeEditor> ; sh:class rdfs:Datatype ; sh:group tosh:ValueTypeConstraintPropertyGroup ; sh:maxCount 1 ; sh:order 1 ; . sh:DisjointConstraintComponent-disjoint sh:deactivated true ; sh:name "imports" ; sh:nodeKind sh:IRI ; . tosh:Parameterizable-labelTemplate a sh:PropertyShape ; sh:path sh:labelTemplate ; sh:description "Outlines how human-readable labels of instances of the associated Parameterizable shall be produced. The values can contain {?paramName} as placeholders for the actual values of the given parameter." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "label template" ; sh:or dash:StringOrLangString ; sh:order "25"^^xsd:decimal ; . }""" ; ] ; sh:property [ sh:path sh:hasValue ; tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; ] ; . sh:order "20"^^xsd:decimal ; . tosh:PathStringViewer a dash:MultiViewer ; dash:hidden true ; rdfs:label "Path string viewer" ; dash:propertySuggestionGenerator [ a dash:SPARQLUpdateSuggestionGenerator ; sh:message "Replace invalid value with {$newObject}" ; sh:order 2 ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT ?newObject WHERE { tosh:Property-domain a sh:PropertyShape ; sh:path rdfs:domain ; graphql:name "domains" ; sh:description "The domain(s) of this property." ; sh:group tosh:PropertyAxiomsPropertyGroup ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "0"^^xsd:decimal ; . tosh:Property-range a sh:PropertyShape ; sh:path rdfs:range ; graphql:name "ranges" ; sh:description "The range(s) of this property." ; sh:group tosh:PropertyAxiomsPropertyGroup ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "1"^^xsd:decimal ; . tosh:Property-subPropertyOf a sh:PropertyShape ; sh:path rdfs:subPropertyOf ; graphql:name "superproperties" ; sh:class rdf:Property ; sh:group tosh:StringBasedConstraintPropertyGroup ; sh:order "9"^^xsd:decimal ; sh:property [ sh:path ( [ sh:zeroOrMorePath rdf:rest ; a sh:PropertyShape ; sh:path [ sh:inversePath rdfs:subPropertyOf ; ] ; graphql:name "subproperties" ; sh:class rdf:Property ; sh:description "The (direct) subproperties of this." ; sh:group tosh:PropertyAxiomsPropertyGroup ; sh:name "subproperties" ; sh:nodeKind sh:IRI ; sh:order "3"^^xsd:decimal ; . . sh:MaxCountConstraintComponent-maxCount sh:group tosh:CardinalityConstraintPropertyGroup ; sh:order 1 ; . sh:MaxExclusiveConstraintComponent-maxExclusive tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; sh:group tosh:ValueRangeConstraintPropertyGroup ; sh:order 3 ; . sh:MaxInclusiveConstraintComponent dash:propertySuggestionGenerator [ sh:or ( [ sh:datatype xsd:decimal ; ] [ sh:datatype xsd:integer ; ] ) ; sh:order "0"^^xsd:decimal ; . ] ; . sh:MaxInclusiveConstraintComponent-maxInclusive tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; sh:group tosh:ValueRangeConstraintPropertyGroup ; sh:order 2 ; . sh:MaxLengthConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; dash:viewer dash:NodeExpressionViewer ; dash:propertySuggestionGenerator [ a dash:SPARQLUpdateSuggestionGenerator ; sh:message "Prune string to only {$maxLength} characters" ; sh:order 1 ; sh:prefixes <http://topbraid.org/tosh> ; sh:update """DELETE { $focusNode $predicate $value . a sh:PropertyShape ; sh:path sh:description ; dash:singleLine false ; graphql:name "descriptions" ; sh:description "The description(s) of the property, possibly in multiple languages." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "descriptions" ; sh:nodeKind sh:Literal ; sh:or dash:StringOrLangStringOrHTML ; . sh:MaxLengthConstraintComponent-maxLength sh:group tosh:StringBasedConstraintPropertyGroup ; sh:order 4 ; . sh:MinCountConstraintComponent-minCount sh:group tosh:CardinalityConstraintPropertyGroup ; sh:order 0 ; . sh:MinExclusiveConstraintComponent-minExclusive tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; sh:group tosh:ValueRangeConstraintPropertyGroup ; sh:order 0 ; . sh:MinInclusiveConstraintComponent dash:propertySuggestionGenerator [ sh:datatype xsd:string ; sh:maxCount 1 ; sh:name "details endpoint" ; . tosh:PropertyShape-editor a sh:PropertyShape ; sh:path dash:editor ; dash:editor dash:InstancesSelectEditor ; sh:class dash:Editor ; sh:description "The editor component that should be used to edit values of this property." ; ] ; . sh:MinInclusiveConstraintComponent-minInclusive tosh:editWidget <http://topbraid.org/tosh.ui#UseDeclaredDatatypeEditor> ; tosh:useDeclaredDatatype true ; sh:group tosh:ValueRangeConstraintPropertyGroup ; sh:order 1 ; . sh:MinLengthConstraintComponent-minLength sh:group tosh:StringBasedConstraintPropertyGroup ; sh:order 3 ; . sh:NodeConstraintComponent sh:nodeValidator [ sh:order "0"^^xsd:decimal ; . tosh:PropertyShape-hidden a sh:PropertyShape ; sh:path dash:hidden ; dash:editor dash:BooleanSelectEditor ; sh:datatype xsd:boolean ; sh:description "True to mark this property as hidden in user interface, yet still used in data tasks." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:order "30"^^xsd:decimal ; . tosh:PropertyShape-indexed a sh:PropertyShape ; sh:path dash:indexed ; sh:datatype xsd:boolean ; sh:description "True to indicate that the values of this shall be indexed, forming ordered arrays." ; sh:maxCount 1 ; sh:name "indexed" ; . tosh:PropertyShape-name a sh:PropertyShape ; sh:path sh:name ; ] ; . sh:NodeConstraintComponent-node tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 0 ; . sh:NodeKindConstraintComponent-nodeKind tosh:editWidget <http://topbraid.org/tosh.ui#NodeKindEditor> ; sh:group tosh:ValueTypeConstraintPropertyGroup ; sh:name "value kinds" ; sh:order 0 ; . sh:NotConstraintComponent sh:nodeValidator [ sh:maxCount 1 ; sh:name "never materialize" ; sh:order "11"^^xsd:decimal ; . tosh:PropertyShape-order a sh:PropertyShape ; sh:path sh:order ; sh:description "The relative order of this property shape compared to others." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "order" ; sh:or ( [ sh:datatype xsd:decimal ; ] [ sh:datatype xsd:integer ; ] ) ; sh:order "1"^^xsd:decimal ; . tosh:PropertyShape-path a sh:PropertyShape ; ] ; . sh:NotConstraintComponent-not tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 10 ; . sh:OrConstraintComponent sh:nodeValidator [ a sh:PropertyShape ; sh:path dash:propertyRole ; sh:class dash:PropertyRole ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:name "role" ; sh:order "40"^^xsd:decimal ; . tosh:PropertyShape-readOnly a sh:PropertyShape ; sh:path dash:readOnly ; dash:editor dash:BooleanSelectEditor ; dash:viewer dash:NodeExpressionViewer ; sh:datatype xsd:boolean ; sh:description """If set to true then the values of this property should not be editable in the user interface. Note that low-level access such as source code editors may still allow editing, but form-based editors would not. More generally, the values of this property are SHACL node expressions, e.g. function calls, in which case the property counts as read-only if the expression evaluates to true.""" ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:order "20"^^xsd:decimal ; . tosh:PropertyShape-values a sh:PropertyShape ; sh:path sh:values ; dash:viewer dash:NodeExpressionViewer ; ] ; . sh:OrConstraintComponent-or tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 12 ; . sh:PatternConstraintComponent dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; dash:propertySuggestionGenerator tosh:ReplaceWithDefaultValueSuggestionGenerator ; . sh:PatternConstraintComponent-flags tosh:editWidget <http://topbraid.org/tosh.ui#FlagsEditor> ; sh:group tosh:StringBasedConstraintPropertyGroup ; sh:maxCount 1 ; sh:name "regex flags" ; . sh:PatternConstraintComponent-pattern tosh:editWidget swa:PlainTextFieldEditor ; sh:group tosh:StringBasedConstraintPropertyGroup ; sh:maxCount 1 ; sh:name "regex pattern" ; sh:class dash:Viewer ; sh:description "The viewer component that should be used to render values of this property." ; sh:group tosh:DisplayPropertyGroup ; sh:maxCount 1 ; sh:nodeKind sh:IRI ; sh:order "10"^^xsd:decimal ; . tosh:PropertyShapeView a sh:NodeShape ; rdfs:comment "Base view shape for either datatype or object property shapes." ; rdfs:label "Property shape view" ; sh:QualifiedMaxCountConstraintComponent-qualifiedMaxCount sh:group tosh:ComplexConstraintPropertyGroup ; sh:maxCount 1 ; sh:order 3 ; . sh:QualifiedMinCountConstraintComponent-qualifiedMinCount sh:group tosh:ComplexConstraintPropertyGroup ; sh:maxCount 1 ; sh:order 2 ; . sh:QualifiedMinCountConstraintComponent-qualifiedValueShape tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:maxCount 1 ; sh:order 1 ; . sh:UniqueLangConstraintComponent-uniqueLang sh:group tosh:StringBasedConstraintPropertyGroup ; sh:order 8 ; . sh:XoneConstraintComponent sh:nodeValidator [ sh:property tosh:PropertyShapeView-qualifiedValueShapesDisjoint ; sh:property tosh:Shape-deactivated ; sh:property tosh:Shape-severity ; sh:property sh:DisjointConstraintComponent-disjoint ; sh:property sh:EqualsConstraintComponent-equals ; sh:property sh:MaxCountConstraintComponent-maxCount ; sh:property sh:MinCountConstraintComponent-minCount ; sh:property sh:SPARQLConstraintComponent-sparql ; . tosh:PropertyShapeView-indexed a sh:PropertyShape ; sh:path dash:indexed ; sh:datatype xsd:boolean ; sh:description "Indicates whether the values are sorted by an index. The user interface will display them in-order." ; sh:group tosh:ReificationPropertyGroup ; sh:maxCount 1 ; sh:name "indexed" ; sh:order "1"^^xsd:decimal ; . tosh:PropertyShapeView-message a sh:PropertyShape ; sh:path sh:message ; sh:description "The message that shall be generated for all constraint violations produced by this property shape." ; sh:group tosh:ValidationPropertyGroup ; sh:name "messages" ; ] ; . sh:XoneConstraintComponent-xone tosh:editWidget swa:SourceCodeEditor ; tosh:viewWidget swa:SourceCodeViewer ; sh:group tosh:ComplexConstraintPropertyGroup ; sh:order 13 ; . sh:count a rdf:Property ; sh:description "A display label of the sh:path based on qnames." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "property path" ; sh:order "2"^^xsd:decimal ; sh:values [ sh:else [ <http://uispin.org/ui#label> ( [ sh:path sh:path ; ] ) ; ] ; sh:if [ <http://datashapes.org/sparql#isIRI> ( [ sh:path sh:path ; ] ) ; ] ; sh:then [ <http://topbraid.org/sparqlmotionfunctions#qname> ( [ sh:path sh:path ; ] ) ; ] ; ] ; . tosh:PropertyShapeView-qualifiedMaxCount a sh:PropertyShape ; sh:path sh:qualifiedMaxCount ; sh:datatype xsd:integer ; sh:description "The maximum number of values that may conform to the qualified value shape." ; sh:group tosh:QualifiedCardinalityConstraintsPropertyGroup ; sh:maxCount 1 ; sh:name "qualified max count" ; sh:order "1"^^xsd:decimal ; . tosh:PropertyShapeView-qualifiedMinCount a sh:PropertyShape ; sh:path sh:qualifiedMinCount ; sh:datatype xsd:integer ; sh:description "The minimum number of values that must conform to the qualified value shape." ; sh:group tosh:QualifiedCardinalityConstraintsPropertyGroup ; sh:maxCount 1 ; sh:name "qualified min count" ; sh:order "0"^^xsd:decimal ; . tosh:PropertyShapeView-qualifiedValueShape a sh:PropertyShape ; sh:path sh:qualifiedValueShape ; sh:class sh:NodeShape ; sh:description "The shape that the specified number of values must conform to." ; sh:group tosh:QualifiedCardinalityConstraintsPropertyGroup ; sh:name "qualified value shape" ; sh:order "2"^^xsd:decimal ; . tosh:PropertyShapeView-qualifiedValueShapesDisjoint a sh:PropertyShape ; sh:path sh:qualifiedValueShapesDisjoint ; sh:datatype xsd:boolean ; sh:description "True to treat all qualified values as disjoint." ; sh:group tosh:QualifiedCardinalityConstraintsPropertyGroup ; sh:maxCount 1 ; sh:name "qualified value shapes disjoint" ; sh:order "3"^^xsd:decimal ; . tosh:PropertyTableViewer a dash:MultiViewer ; dash:hidden true ; rdfs:label "Property table viewer" ; . tosh:QualifiedCardinalityConstraintsPropertyGroup a sh:PropertyGroup ; rdfs:comment "The properties in this group are used together to express that a certain number of values must conform to a given shape." ; rdfs:label "Qualified Cardinality Constraints" ; sh:order "77"^^xsd:decimal ; . tosh:QueryTestCase-expectedResult a sh:PropertyShape ; sh:path dash:expectedResult ; dash:singleLine false ; sh:description "The expected result set, as a JSON string." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "expected result" ; sh:or ( [ sh:datatype rdf:JSON ; ] [ sh:datatype xsd:string ; ] ) ; . tosh:RDFSOWLClassView a sh:NodeShape ; dash:applicableToClass rdfs:Class ; rdfs:comment "A node shape collecting RDFS and OWL axioms for classes." ; rdfs:label "RDFS/OWL class view" ; sh:property tosh:Class-disjointWith ; sh:property tosh:Class-domain-inverse ; sh:property tosh:Class-equivalentClass ; sh:property tosh:Class-range-inverse ; sh:property tosh:Class-subClassOf ; sh:property tosh:Class-subClassOf-inverse ; sh:property tosh:Resource-comment ; sh:property tosh:Resource-label ; sh:property tosh:Resource-type ; . tosh:RDFSPropertyAxiomsPropertyGroup a sh:PropertyGroup ; rdfs:label "RDFS Property Axioms" ; sh:order "15"^^xsd:decimal ; . tosh:ReferencesPropertyGroup a sh:PropertyGroup ; rdfs:comment "A property group typically used for incoming references or usages."^^rdf:HTML ; rdfs:label "References" ; sh:order "100"^^xsd:decimal ; . tosh:ReificationPropertyGroup a sh:PropertyGroup ; rdfs:label "Reification (Statements about Statements)" ; sh:order "90"^^xsd:decimal ; . tosh:ReplaceWithDefaultValueSuggestionGenerator a dash:SPARQLUpdateSuggestionGenerator ; rdfs:comment "Produces a suggestion to replace all values of the given predicate (which must exist) at the focus node to the default value declared at the shape that has caused the violation. Does nothing if the shape does not declare a sh:defaultValue. Deletes any old value of the property." ; rdfs:label "Replace with default value suggestion generator" ; sh:message "Replace with default value" ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT ?defaultValue WHERE { GRAPH $shapesGraph { $sourceShape sh:defaultValue ?defaultValue . } }""" ; sh:update """DELETE { $focusNode $predicate ?oldValue . } INSERT { $focusNode $predicate ?defaultValue . } WHERE { $focusNode $predicate ?oldValue . }""" ; . tosh:Resource-comment a sh:PropertyShape ; sh:path rdfs:comment ; dash:propertyRole dash:DescriptionRole ; dash:singleLine false ; graphql:name "comments" ; sh:description "The comments of this, possibly in multiple languages." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "comments" ; sh:or dash:StringOrLangStringOrHTML ; sh:order "1"^^xsd:decimal ; . tosh:Resource-label a sh:PropertyShape ; sh:path rdfs:label ; dash:propertyRole dash:LabelRole ; graphql:name "labels" ; sh:description "The display name(s) of this, possibly in multiple languages." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "labels" ; sh:or dash:StringOrLangString ; sh:order "0"^^xsd:decimal ; . tosh:Resource-type a sh:PropertyShape ; sh:path rdf:type ; graphql:name "types" ; sh:class rdfs:Class ; sh:description "The type(s) of this." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "types" ; sh:order "10"^^xsd:decimal ; . tosh:ResourceAction-jsCondition a sh:PropertyShape ; sh:path dash:jsCondition ; sh:datatype xsd:string ; sh:description "An (ADS) JavaScript expression that will be executed to determine whether the action is applicable to the selected resource in the current context. The variable focusNode can be queried here. The expression needs to return true for the action to be deemed suitable." ; sh:group tosh:ImplementationPropertyGroup ; sh:name "action pre-condition" ; sh:order "25"^^xsd:decimal ; . tosh:ResourceView a sh:NodeShape ; rdfs:comment "A generic view shape that can be used as fallback to display typical resources that have an rdfs:label and an rdfs:comment." ; rdfs:label "Resource view" ; sh:property tosh:Resource-comment ; sh:property tosh:Resource-label ; . tosh:Rule-condition a sh:PropertyShape ; sh:path sh:condition ; sh:description "The pre-conditions that must apply before a rule gets executed. The focus node must conform to all conditions, which must be shapes." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "conditions" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "40"^^xsd:decimal ; . tosh:Rule-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactivate the rule so that it will not get executed." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:Rule-order a sh:PropertyShape ; sh:path sh:order ; sh:description "The order of this rule relative to other rules at the same shape. Rules with lower order are executed first. Default value is 0. Rules with the same order cannot \"see\" each other's inferences." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "order" ; sh:or ( [ sh:datatype xsd:decimal ; ] [ sh:datatype xsd:integer ; ] ) ; sh:order "35"^^xsd:decimal ; . tosh:Rule-rule-inverse a sh:PropertyShape ; sh:path [ sh:inversePath sh:rule ; ] ; sh:class sh:Shape ; sh:description "The shapes or classes that the rule is attached to." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "rule of" ; sh:order "20"^^xsd:decimal ; . tosh:SHMinMaxEditor a dash:SingleEditor ; dash:hidden true ; rdfs:comment "An internally used editor for min/max range values of property shapes."^^rdf:HTML ; rdfs:label "SHACL Min Max Editor" ; . tosh:SPARQLAskExecutable-ask a sh:PropertyShape ; sh:path sh:ask ; dash:singleLine false ; sh:datatype xsd:string ; sh:description "The SPARQL ASK query string." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "ask" ; sh:order "1"^^xsd:decimal ; . tosh:SPARQLConstraint-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactive this constraint." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:SPARQLConstraint-message a sh:PropertyShape ; sh:path sh:message ; sh:description "The message(s) that should be produced for constraint violations. The messages may contain placeholders such as {$value} for any variable returned in the SELECT clause of the SPARQL query." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "messages" ; sh:or dash:StringOrLangString ; sh:order "20"^^xsd:decimal ; . tosh:SPARQLConstructExecutable-construct a sh:PropertyShape ; sh:path sh:construct ; dash:singleLine false ; sh:datatype xsd:string ; sh:description "The SPARQL CONSTRUCT query string." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "construct" ; sh:order "1"^^xsd:decimal ; . tosh:SPARQLExecutable-prefixes a sh:PropertyShape ; sh:path sh:prefixes ; sh:class owl:Ontology ; sh:description "The Ontology declaring the SHACL prefix declarations to use for the SPARQL query." ; sh:group tosh:ImplementationPropertyGroup ; sh:name "prefixes" ; sh:order "0"^^xsd:decimal ; . tosh:SPARQLSelectExecutable-select a sh:PropertyShape ; sh:path sh:select ; dash:singleLine false ; sh:datatype xsd:string ; sh:description "The SPARQL SELECT query string." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "select" ; sh:order "1"^^xsd:decimal ; . tosh:SPARQLUpdateExecutable-update a sh:PropertyShape ; sh:path sh:update ; dash:singleLine false ; sh:datatype xsd:string ; sh:description "The SPARQL UPDATE request string." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "update" ; sh:order "1"^^xsd:decimal ; . tosh:Script-js a sh:PropertyShape ; sh:path dash:js ; sh:datatype xsd:string ; sh:description "The implementation as JavaScript." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "JavaScript code" ; sh:order "20"^^xsd:decimal ; . tosh:Script-onAllValues a sh:PropertyShape ; sh:path dash:onAllValues ; sh:datatype xsd:boolean ; sh:description "If true then all value nodes will be available to the script at once, through the variable \"values\"." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "on all values" ; sh:order "0"^^xsd:decimal ; . tosh:ScriptConstraint-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactivate this constraint." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:ScriptConstraint-message a sh:PropertyShape ; sh:path sh:message ; sh:description "The message(s) to use for violations produced by this script." ; sh:group tosh:DefinitionPropertyGroup ; sh:name "messages" ; sh:or dash:StringOrLangString ; sh:order "20"^^xsd:decimal ; . tosh:ScriptFunction-canWrite a sh:PropertyShape ; sh:path dash:canWrite ; sh:datatype xsd:boolean ; sh:description "True to allow this function to have side effects. By default, functions are not permitted to modify the graph as this would violate SPARQL contracts. However, if canWrite is true then the function will not be available as a SPARQL function and only be injected into the generated API in read/write mode." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "can write" ; sh:order "15"^^xsd:decimal ; . tosh:ScriptTestCase-expectedResult a sh:PropertyShape ; sh:path dash:expectedResult ; sh:description "The expected result of the evaluation, as JSON object as produced by the servlet, or true or false." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "expected result" ; sh:or ( [ sh:datatype rdf:JSON ; ] [ sh:datatype xsd:boolean ; ] ) ; sh:order "0"^^xsd:decimal ; . tosh:ScriptTestCase-focusNode a sh:PropertyShape ; sh:path dash:focusNode ; sh:description "The selected resource, which will become value of focusNode for the script, with its \"most suitable\" JavaScript class as type. Defaults to the test case itself." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "focus node" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order "10"^^xsd:decimal ; . tosh:ScriptsPropertyGroup a sh:PropertyGroup ; rdfs:comment "Scripts based on Active Data Shapes." ; rdfs:label "Scripts" ; sh:order "30"^^xsd:decimal ; . tosh:Service-canWrite a sh:PropertyShape ; sh:path dash:canWrite ; sh:datatype xsd:boolean ; sh:description "True if this service can modify the data, i.e. it will execute in read/write mode. By default, all services are read-only." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "can write" ; . tosh:Service-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactivate this service." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:Service-responseContentType a sh:PropertyShape ; sh:path dash:responseContentType ; sh:datatype xsd:string ; sh:description "The content type (mime type) of the service response, defaulting to \"application/json\". Use \"void\" to return nothing." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:name "response content type" ; sh:order "10"^^xsd:decimal ; . tosh:SetToDefaultValueSuggestionGenerator a dash:SPARQLUpdateSuggestionGenerator ; rdfs:comment "Produces a suggestion to set the given predicate at the focus node to the default value declared at the shape that has caused the violation. Does nothing if the shape does not declare a sh:defaultValue. Deletes any old value of the property." ; rdfs:label "Set to default value suggestion generator" ; sh:message "Set to default value" ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT ?defaultValue WHERE { GRAPH $shapesGraph { $sourceShape sh:defaultValue ?defaultValue . } }""" ; sh:update """DELETE { $focusNode $predicate ?oldValue . } INSERT { $focusNode $predicate ?defaultValue . } WHERE { OPTIONAL { $focusNode $predicate ?oldValue . } }""" ; . tosh:Shape-datatypes a sh:PropertyShape ; sh:path tosh:datatypes ; dash:neverMaterialize true ; dash:viewer tosh:DatatypesViewer ; sh:description "Zero of more datatypes that value nodes can take. In SHACL, the typical pattern is to either use a single sh:datatype or a sh:or of multiple sh:datatype constraints. This inferred property here provides a unified way to access these two design patterns." ; sh:group tosh:TypeOfValuesPropertyGroup ; sh:name "datatypes" ; sh:nodeKind sh:IRI ; sh:order "0"^^xsd:decimal ; sh:values [ sh:union ( [ sh:path sh:datatype ; ] [ sh:path ( sh:or [ sh:zeroOrMorePath rdf:rest ; ] rdf:first sh:datatype ) ; ] ) ; ] ; . tosh:Shape-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "True to deactivate this shape, making it literally invisible and without any effect." ; sh:group tosh:DefinitionPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "30"^^xsd:decimal ; . tosh:Shape-severity a sh:PropertyShape ; sh:path sh:severity ; dash:editor dash:InstancesSelectEditor ; sh:class sh:Severity ; sh:description "The severity to be used for validation results produced by the constraints." ; sh:group tosh:ValidationPropertyGroup ; sh:maxCount 1 ; sh:name "severity" ; sh:order "0"^^xsd:decimal ; . tosh:ShapeInGraphConstraintComponent a sh:ConstraintComponent ; dash:propertySuggestionGenerator tosh:DeleteTripleSuggestionGenerator ; rdfs:comment """A constraint component that can be used to verify that the value nodes have a given shape, where the shape validation is executed in a given graph. This can, for example, be used to verify that a given value is declared as an instance of a given class in some specified (not imported) graph. A typical design pattern is as follows: ex:NodeShape sh:property [ sh:path ex:myProperty ; sh:nodeKind sh:IRI ; tosh:graph <http://example.org/externalGraph> ; tosh:shapeInGraph [ sh:class ex:ExternalClass ; ] ; tosh:editor tosh:InstancesInGraphSelectEditor ; tosh:viewer tosh:URIInGraphViewer ; ] .""" ; rdfs:label "Shape in graph constraint component" ; sh:labelTemplate "Values must have shape {$shapeInGraph} defined in graph {$graph}" ; sh:message "Value does not have shape {$shapeInGraph} defined in graph {$graph}" ; sh:parameter [ a sh:Parameter ; sh:path tosh:graph ; sh:nodeKind sh:IRI ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:shapeInGraph ; sh:nodeKind sh:BlankNodeOrIRI ; ] ; sh:validator [ a sh:SPARQLAskValidator ; sh:ask """ASK { GRAPH $graph { FILTER tosh:hasShape($value, $shapeInGraph) } }""" ; sh:prefixes <http://topbraid.org/tosh> ; ] ; . tosh:StringConstraintsPropertyGroup a sh:PropertyGroup ; rdfs:label "String Constraints" ; sh:order "70"^^xsd:decimal ; . tosh:SystemNamespaceShape a sh:NodeShape ; rdfs:comment "A shape that detects whether the focus node is a URI that has a namespace from one of the system namespaces - RDF, RDFS, OWL etc. The list of actual system namespaces is represented via tosh:systemNamespace true triples." ; rdfs:label "System namespace shape" ; sh:sparql [ a sh:SPARQLConstraint ; sh:message "Not a IRI from a system namespace" ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """SELECT $this WHERE { FILTER (!isIRI($this) || (isIRI($this) && EXISTS { BIND (IRI(afn:namespace($this)) AS ?ns) . FILTER NOT EXISTS { ?ns tosh:systemNamespace true } . } )) . }""" ; ] ; . tosh:TargetsPropertyGroup a sh:PropertyGroup ; rdfs:label "Targets" ; sh:order "5"^^xsd:decimal ; . tosh:TeamworkPlatform a dash:ExecutionPlatform ; dash:includedExecutionPlatform tosh:TopBraidPlatform ; rdfs:comment "The platform consisting of TopBraid plus any teamwork features used by TopBraid EDG." ; rdfs:label "Teamwork platform" ; . tosh:TestCase-deactivated a sh:PropertyShape ; sh:path sh:deactivated ; sh:datatype xsd:boolean ; sh:description "If set to true, this test case will be skipped." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "deactivated" ; sh:order "50"^^xsd:decimal ; . tosh:TestPropertiesPropertyGroup a sh:PropertyGroup ; rdfs:label "Test Properties" ; sh:order "20"^^xsd:decimal ; . tosh:TopBraidPlatform a dash:ExecutionPlatform ; rdfs:comment "The platform consisting of TopBraid." ; rdfs:label "TopBraid platform" ; . tosh:TripleRule-object a sh:PropertyShape ; sh:path sh:object ; dash:viewer dash:NodeExpressionViewer ; sh:description "The node expression producing the object(s) of the triple inferred by the rule." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "object" ; sh:order 2 ; . tosh:TripleRule-predicate a sh:PropertyShape ; sh:path sh:predicate ; dash:viewer dash:NodeExpressionViewer ; sh:description "The node expression producing the predicate(s) of the triple inferred by the rule." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "predicate" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order 1 ; . tosh:TripleRule-subject a sh:PropertyShape ; sh:path sh:subject ; dash:viewer dash:NodeExpressionViewer ; sh:description "The node expression producing the subject(s) of the triple inferred by the rule." ; sh:group tosh:ImplementationPropertyGroup ; sh:maxCount 1 ; sh:minCount 1 ; sh:name "subject" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order 0 ; . tosh:TypeOfValuesPropertyGroup a sh:PropertyGroup ; rdfs:label "Type of Values" ; sh:order "50"^^xsd:decimal ; . tosh:URIInGraphViewer a dash:SingleViewer ; rdfs:comment "A viewer for URI resources that have their data in a given graph that may be outside of the imports closure. The graph must be specified using a tosh:graph constraint for the property." ; rdfs:label "URI in graph viewer" ; . tosh:UseDeclaredDatatypeConstraintComponent a sh:ConstraintComponent ; dash:propertySuggestionGenerator [ a dash:SPARQLUpdateSuggestionGenerator ; sh:message "Change datatype of the invalid value to the specified sh:datatype" ; sh:prefixes <http://topbraid.org/tosh> ; sh:update """DELETE { $subject $predicate $object . } INSERT { $subject $predicate ?newObject . } WHERE { $subject sh:datatype ?datatype . BIND (spif:cast(?object, ?datatype) AS ?newObject) . }""" ; ] ; rdfs:comment "Constrains the value nodes to be either non-literals or literals that have the same datatype as the declared sh:datatype for the given constraint node. This is used, among others, in properties such as sh:hasValue and sh:minExclusive." ; rdfs:label "Use declared datatype constraint component" ; sh:parameter [ a sh:Parameter ; sh:path tosh:useDeclaredDatatype ; sh:datatype xsd:boolean ; sh:description "True to state that the datatype of literal values must be the same as the declared sh:datatype." ; sh:name "use declared datatype" ; ] ; sh:propertyValidator [ a sh:SPARQLSelectValidator ; sh:message "Datatype must match the declared datatype " ; sh:prefixes <http://topbraid.org/tosh> ; sh:select """ SELECT DISTINCT $this ?value ?datatype WHERE { { FILTER ($useDeclaredDatatype) } $this sh:datatype ?datatype . $this $PATH ?value . FILTER (isLiteral(?value) && datatype(?value) != ?datatype) . }""" ; ] ; sh:targetClass sh:PropertyShape ; . tosh:ValidationPropertyGroup a sh:PropertyGroup ; rdfs:label "Validation" ; sh:order "30"^^xsd:decimal ; . tosh:ValidationTestCase-expectedResult a sh:PropertyShape ; sh:path dash:expectedResult ; sh:description "The expected validation report, either as instance of sh:ValidationReport or a Turtle string with one instance of sh:ValidationReport in it when parsed." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:name "expected result" ; sh:or ( [ sh:datatype xsd:string ; ] [ sh:class sh:ValidationReport ; ] ) ; sh:order "10"^^xsd:decimal ; . tosh:ValidationTestCase-includeSuggestions a sh:PropertyShape ; sh:path dash:includeSuggestions ; sh:datatype xsd:boolean ; sh:description "True to also generate and verify suggestions." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "include suggestions" ; sh:order "0"^^xsd:decimal ; . tosh:ValidationTestCase-validateShapes a sh:PropertyShape ; sh:path dash:validateShapes ; sh:datatype xsd:boolean ; sh:description "True to also validate shapes themselves." ; sh:group tosh:TestPropertiesPropertyGroup ; sh:maxCount 1 ; sh:name "validate shapes" ; sh:order "5"^^xsd:decimal ; . tosh:ValueConstraintsPropertyGroup a sh:PropertyGroup ; rdfs:label "Value Constraints" ; sh:order "60"^^xsd:decimal ; . tosh:ValueRangePropertyGroup a sh:PropertyGroup ; rdfs:label "Value Range" ; sh:order "60"^^xsd:decimal ; . tosh:countShapesWithMatchResult a sh:SPARQLFunction ; rdfs:comment "Counts the number of shapes from a given rdf:List (?arg2) defined in a given shapes graph (?arg3) where tosh:hasShape returns the provided match value (true or false, ?arg4) for a given focus node (?arg1). The function produces a failure if one of the shapes validated to a failure." ; rdfs:label "count shapes with match result" ; sh:parameter [ a sh:Parameter ; sh:path sh:expectedValue ; sh:datatype xsd:boolean ; sh:description "The expected value of tosh:hasShape to count." ; sh:order 3.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path sh:focusNode ; sh:class rdfs:Resource ; sh:description "The focus node." ; sh:order 0.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path sh:shapes ; sh:class rdf:List ; sh:description "The list of shapes to walk through." ; sh:order 1.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path sh:shapesGraph ; sh:class rdfs:Resource ; sh:description "The shapes graph." ; sh:order 2.0 ; ] ; sh:prefixes <http://topbraid.org/tosh> ; sh:returnType xsd:integer ; sh:select """ # The SUM will fail with an error if one of the operands is not a number # (this mechanism is used to propagate errors from tosh:hasShape calls) SELECT (SUM(?s) AS ?result) WHERE { GRAPH $shapesGraph { $shapes rdf:rest*/rdf:first ?shape . } BIND (tosh:hasShape($focusNode, ?shape, true) AS ?hasShape) . BIND (IF(bound(?hasShape), IF(?hasShape = $expectedValue, 1, 0), 'error') AS ?s) . } """ ; . tosh:editGroupDescription a rdf:Property ; rdfs:comment "A description of the property group when in \"edit\" mode." ; rdfs:domain sh:PropertyGroup ; rdfs:label "edit group description" ; rdfs:range xsd:string ; . tosh:graph a rdf:Property ; rdfs:comment "The graph that the shape is validated in." ; rdfs:label "graph" ; . tosh:hasDatatype a sh:SPARQLAskValidator ; rdfs:comment "Checks whether a given node ($value) is a literal with a given datatype ($datatype), and that the literal is well-formed." ; rdfs:label "has datatype" ; sh:ask """ ASK { FILTER (datatype($value) = $datatype && spif:isValidForDatatype($value, $datatype)) . } """ ; sh:prefixes <http://topbraid.org/tosh> ; . tosh:hasShape a sh:Function ; dash:apiStatus dash:Experimental ; rdfs:comment """A built-in function of the TopBraid SHACL implementation. Can be used to validate a given (focus) node against a given shape, returning <code>true</code> if the node is valid. If executed within a SHACL validation engine, this uses the shapes graph that was provided when the engine started. If executed in other contexts, e.g. in a stand-alone SPARQL query, the function attempts to use the URI of the current default graph as the shapes graph. This may not always be supported. If called from within an SWP engine, the shapes graph is the current query graph."""^^rdf:HTML ; rdfs:label "has shape" ; sh:parameter [ a sh:Parameter ; sh:path tosh:node ; sh:description "The node to validate." ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:shape ; sh:description "The shape that the node is supposed to have." ; ] ; sh:returnType xsd:boolean ; . tosh:isHiddenClass a sh:SPARQLFunction ; dash:apiStatus dash:Experimental ; rdfs:comment "Checks if a given resource is supposed to be hidden in typical class displays. This applies to owl:Nothing, owl:NamedIndividual and owl:Restriction and any class that has dash:hidden true." ; rdfs:label "is hidden class" ; sh:ask """ASK { ?resource dash:hidden true . }""" ; sh:parameter [ a sh:Parameter ; sh:path tosh:resource ; sh:description "The node to check." ; sh:name "resource" ; sh:nodeKind sh:BlankNodeOrIRI ; ] ; sh:prefixes <http://topbraid.org/tosh> ; sh:returnType xsd:boolean ; . tosh:isInTargetOf a sh:Function ; dash:apiStatus dash:Experimental ; rdfs:comment "Checks whether a given node is in the target of a given shape." ; rdfs:label "is in target of" ; sh:parameter [ a sh:Parameter ; sh:path tosh:node ; sh:description "The node to check." ; sh:name "node" ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:shape ; sh:class sh:Shape ; sh:description "The shape that the node is supposed to be in the target of." ; sh:name "shape" ; ] ; sh:returnType xsd:boolean ; . tosh:isReificationURI a sh:Function ; dash:apiStatus dash:Stable ; rdfs:comment "Checks whether a given URI represents a reified triple." ; rdfs:label "is reification URI" ; sh:parameter [ a sh:Parameter ; sh:path tosh:uri ; sh:description "The URI to check." ; sh:nodeKind sh:IRI ; ] ; sh:returnType xsd:boolean ; . tosh:isReified a sh:Function ; dash:apiStatus dash:Stable ; rdfs:comment "Checks whether there are any reified values for a given triple." ; rdfs:label "is reified" ; sh:parameter [ a sh:Parameter ; sh:path tosh:object ; sh:description "The object of the triple to reify." ; sh:name "object" ; sh:order 2.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:predicate ; sh:description "The predicate of the triple to reify." ; sh:name "predicate" ; sh:nodeKind sh:IRI ; sh:order 1.0 ; ] ; sh:parameter [ a sh:Parameter ; sh:path tosh:subject ; sh:description "The subject of the triple to reify." ; sh:name "subject" ; sh:nodeKind sh:BlankNodeOrIRI ; sh:order 0.0 ; ] ; sh:returnType xsd:boolean ; . tosh:isSystemResource a sh:SPARQLFunction ; dash:apiStatus dash:Stable ; rdfs:comment "Checks if a given resource is from a namespace that is marked with tosh:systemNamespace true." ; rdfs:label "is system resource" ; sh:ask """ASK { BIND (IRI(afn:namespace($resource)) AS ?namespace) . FILTER
263
Misc minor updates, including a bug fix with GRAPH access in sh:values rules
131
.ttl
ttl
apache-2.0
TopQuadrant/shacl
408
<NME> TestDASHTestCases.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.util.FileUtils; import org.apache.jena.vocabulary.OWL; import org.apache.jena.vocabulary.RDF; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.topbraid.jenax.util.JenaUtil; import org.topbraid.shacl.testcases.TestCase; import org.topbraid.shacl.testcases.TestCaseType; import org.topbraid.shacl.testcases.TestCaseTypes; import org.topbraid.shacl.util.SHACLSystemModel; import org.topbraid.shacl.vocabulary.DASH; import org.topbraid.shacl.vocabulary.SH; @RunWith(Parameterized.class) public class TestDASHTestCases { @Parameters(name="{0}") public static Collection<Object[]> data() throws Exception { List<TestCase> testCases = new LinkedList<TestCase>(); File rootFolder = new File("src/test/resources"); collectTestCases(rootFolder, testCases); List<Object[]> results = new LinkedList<Object[]>(); for(TestCase testCase : testCases) { results.add(new Object[]{ testCase }); } return results; @Override protected Reader createScriptReader(String url) throws Exception { if(DASH_JS.equals(url)) { return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/rdf/dash.js")); } else if(RDFQUERY_JS.equals(url)) { return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/rdf/rdfquery.js")); } else if(url.startsWith("http://datashapes.org/js/")) { return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream(url.substring(21))); InputStream is = new FileInputStream(f); testModel.read(is, "urn:dummy", FileUtils.langTurtle); testModel.add(SHACLSystemModel.getSHACLModel()); Resource ontology = testModel.listStatements(null, OWL.imports, ResourceFactory.createResource(DASH.BASE_URI)).next().getSubject(); for(TestCaseType type : TestCaseTypes.getTypes()) { testCases.addAll(type.getTestCases(testModel, ontology)); } } } } private TestCase testCase; public TestDASHTestCases(TestCase testCase) { this.testCase = testCase; } @Test public void testTestCase() { System.out.println(" - " + testCase.getResource()); Model results = JenaUtil.createMemoryModel(); try { testCase.run(results); } catch(Exception ex) { testCase.createFailure(results, "Exception during test case execution: " + ex); ex.printStackTrace(); } for(Statement s : results.listStatements(null, RDF.type, DASH.FailureTestCaseResult).toList()) { String message = JenaUtil.getStringProperty(s.getSubject(), SH.resultMessage); if(message == null) { message = "(No " + SH.PREFIX + ":" + SH.resultMessage.getLocalName() + " found in failure)"; } Assert.fail(testCase.getResource() + ": " + message); } } } <MSG> Alignment with latest TopBraid code, including misc bug fixes, changes to system-triples and .js files <DFF> @@ -61,10 +61,10 @@ public class TestDASHTestCases { @Override protected Reader createScriptReader(String url) throws Exception { if(DASH_JS.equals(url)) { - return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/rdf/dash.js")); + return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/js/dash.js")); } else if(RDFQUERY_JS.equals(url)) { - return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/rdf/rdfquery.js")); + return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/js/rdfquery.js")); } else if(url.startsWith("http://datashapes.org/js/")) { return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream(url.substring(21)));
2
Alignment with latest TopBraid code, including misc bug fixes, changes to system-triples and .js files
2
.java
java
apache-2.0
TopQuadrant/shacl
409
<NME> TestDASHTestCases.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.util.FileUtils; import org.apache.jena.vocabulary.OWL; import org.apache.jena.vocabulary.RDF; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.topbraid.jenax.util.JenaUtil; import org.topbraid.shacl.testcases.TestCase; import org.topbraid.shacl.testcases.TestCaseType; import org.topbraid.shacl.testcases.TestCaseTypes; import org.topbraid.shacl.util.SHACLSystemModel; import org.topbraid.shacl.vocabulary.DASH; import org.topbraid.shacl.vocabulary.SH; @RunWith(Parameterized.class) public class TestDASHTestCases { @Parameters(name="{0}") public static Collection<Object[]> data() throws Exception { List<TestCase> testCases = new LinkedList<TestCase>(); File rootFolder = new File("src/test/resources"); collectTestCases(rootFolder, testCases); List<Object[]> results = new LinkedList<Object[]>(); for(TestCase testCase : testCases) { results.add(new Object[]{ testCase }); } return results; @Override protected Reader createScriptReader(String url) throws Exception { if(DASH_JS.equals(url)) { return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/rdf/dash.js")); } else if(RDFQUERY_JS.equals(url)) { return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/rdf/rdfquery.js")); } else if(url.startsWith("http://datashapes.org/js/")) { return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream(url.substring(21))); InputStream is = new FileInputStream(f); testModel.read(is, "urn:dummy", FileUtils.langTurtle); testModel.add(SHACLSystemModel.getSHACLModel()); Resource ontology = testModel.listStatements(null, OWL.imports, ResourceFactory.createResource(DASH.BASE_URI)).next().getSubject(); for(TestCaseType type : TestCaseTypes.getTypes()) { testCases.addAll(type.getTestCases(testModel, ontology)); } } } } private TestCase testCase; public TestDASHTestCases(TestCase testCase) { this.testCase = testCase; } @Test public void testTestCase() { System.out.println(" - " + testCase.getResource()); Model results = JenaUtil.createMemoryModel(); try { testCase.run(results); } catch(Exception ex) { testCase.createFailure(results, "Exception during test case execution: " + ex); ex.printStackTrace(); } for(Statement s : results.listStatements(null, RDF.type, DASH.FailureTestCaseResult).toList()) { String message = JenaUtil.getStringProperty(s.getSubject(), SH.resultMessage); if(message == null) { message = "(No " + SH.PREFIX + ":" + SH.resultMessage.getLocalName() + " found in failure)"; } Assert.fail(testCase.getResource() + ": " + message); } } } <MSG> Alignment with latest TopBraid code, including misc bug fixes, changes to system-triples and .js files <DFF> @@ -61,10 +61,10 @@ public class TestDASHTestCases { @Override protected Reader createScriptReader(String url) throws Exception { if(DASH_JS.equals(url)) { - return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/rdf/dash.js")); + return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/js/dash.js")); } else if(RDFQUERY_JS.equals(url)) { - return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/rdf/rdfquery.js")); + return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream("/js/rdfquery.js")); } else if(url.startsWith("http://datashapes.org/js/")) { return new InputStreamReader(NashornScriptEngine.class.getResourceAsStream(url.substring(21)));
2
Alignment with latest TopBraid code, including misc bug fixes, changes to system-triples and .js files
2
.java
java
apache-2.0
TopQuadrant/shacl
410
<NME> ValidationEngine.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl.validation; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import org.apache.jena.graph.Graph; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.graph.compose.MultiUnion; import org.apache.jena.query.Dataset; import org.apache.jena.query.QuerySolution; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import org.apache.jena.sparql.path.P_Inverse; import org.apache.jena.sparql.path.P_Link; import org.apache.jena.sparql.path.Path; import org.apache.jena.sparql.path.eval.PathEval; import org.apache.jena.sparql.util.Context; import org.apache.jena.vocabulary.RDF; import org.topbraid.jenax.util.ExceptionUtil; import org.topbraid.jenax.util.JenaDatatypes; import org.topbraid.jenax.util.JenaUtil; import org.topbraid.jenax.util.RDFLabels; import org.topbraid.shacl.arq.SHACLPaths; import org.topbraid.shacl.engine.AbstractEngine; import org.topbraid.shacl.engine.Constraint; import org.topbraid.shacl.engine.SHACLScriptEngineManager; import org.topbraid.shacl.engine.Shape; import org.topbraid.shacl.engine.ShapesGraph; import org.topbraid.shacl.engine.filters.ExcludeMetaShapesFilter; import org.topbraid.shacl.expr.NodeExpression; import org.topbraid.shacl.expr.NodeExpressionFactory; import org.topbraid.shacl.model.SHNodeShape; import org.topbraid.shacl.model.SHPropertyShape; import org.topbraid.shacl.targets.InstancesTarget; import org.topbraid.shacl.targets.Target; import org.topbraid.shacl.util.FailureLog; import org.topbraid.shacl.util.SHACLPreferences; import org.topbraid.shacl.util.SHACLUtil; import org.topbraid.shacl.validation.sparql.SPARQLSubstitutions; import org.topbraid.shacl.vocabulary.DASH; import org.topbraid.shacl.vocabulary.SH; /** * A ValidationEngine uses a given shapes graph (represented via an instance of ShapesGraph) * and performs SHACL validation on a given Dataset. * * Instances of this class should be created via the ValidatorFactory. * * @author Holger Knublauch */ public class ValidationEngine extends AbstractEngine { // The currently active ValidationEngine for cases where no direct pointer can be acquired, e.g. from HasShapeFunction private static ThreadLocal<ValidationEngine> current = new ThreadLocal<>(); public static ValidationEngine getCurrent() { return current.get(); } public static void setCurrent(ValidationEngine value) { current.set(value); } // Avoids repeatedly walking up/down the class hierarchy for sh:class constraints private ClassesCache classesCache; private ValidationEngineConfiguration configuration; // Can be used to drop certain focus nodes from validation private Predicate<RDFNode> focusNodeFilter; // The inferred triples if the shapes graph declares an entailment regime private Model inferencesModel; // The label function for rendering nodes in validation results (message templates etc) private Function<RDFNode,String> labelFunction = (node -> RDFLabels.get().getNodeLabel(node)); // Avoids repeatedly fetching labels private Map<RDFNode,String> labelsCache = new ConcurrentHashMap<>(); setConfiguration(new ValidationEngineConfiguration()); if(report == null) { Model reportModel = JenaUtil.createMemoryModel(); reportModel.setNsPrefixes(dataset.getDefaultModel()); this.report = reportModel.createResource(SH.ValidationReport); } // Number of created results, e.g. for progress monitor private int resultsCount = 0; // Avoids repeatedly fetching the value nodes of a focus node / path combination private Map<ValueNodesCacheKey,Collection<RDFNode>> valueNodes = new WeakHashMap<>(); // Number of created violations, e.g. for progress monitor private int violationsCount = 0; /** * Constructs a new ValidationEngine. * @param dataset the Dataset to operate on * @param shapesGraphURI the URI of the shapes graph (must be in the dataset) * @param shapesGraph the ShapesGraph with the shapes to validate against * @param report the sh:ValidationReport object in the results Model, or null to create a new one */ protected ValidationEngine(Dataset dataset, URI shapesGraphURI, ShapesGraph shapesGraph, Resource report) { super(dataset, shapesGraph, shapesGraphURI); setConfiguration(new ValidationEngineConfiguration()); if(report == null) { Model reportModel = JenaUtil.createMemoryModel(); reportModel.setNsPrefixes(dataset.getDefaultModel()); // This can be very expensive in some databases reportModel.withDefaultMappings(shapesGraph.getShapesModel()); this.report = reportModel.createResource(SH.ValidationReport); } else { this.report = report; } } /** * Checks if entailments are active for the current shapes graph and applies them for a given focus node. * This will only work for the sh:Rules entailment, e.g. to compute sh:values and sh:defaultValue. * If any inferred triples exist, the focus node will be returned attached to the model that includes those inferences. * The dataset used internally will also be switched to use that new model as its default model, so that if * a node gets validated it will "see" the inferred triples too. * @param focusNode the focus node * @return the focus node, possibly in a different Model than originally */ public RDFNode applyEntailments(Resource focusNode) { Model shapesModel = dataset.getNamedModel(shapesGraphURI.toString()); if(shapesModel.contains(null, SH.entailment, SH.Rules)) { // Create union of data model and inferences if called for the first time if(inferencesModel == null) { inferencesModel = JenaUtil.createDefaultModel(); Model dataModel = dataset.getDefaultModel(); MultiUnion multiUnion = new MultiUnion(new Graph[]{ dataModel.getGraph(), inferencesModel.getGraph() }); multiUnion.setBaseGraph(dataModel.getGraph()); dataset.setDefaultModel(ModelFactory.createModelForGraph(multiUnion)); } // Apply sh:values rules Map<Property,RDFNode> defaultValueMap = new HashMap<>(); for(SHNodeShape nodeShape : SHACLUtil.getAllShapesAtNode(focusNode)) { if(!nodeShape.hasProperty(SH.deactivated, JenaDatatypes.TRUE)) { for(SHPropertyShape ps : nodeShape.getPropertyShapes()) { if(!ps.hasProperty(SH.deactivated, JenaDatatypes.TRUE)) { Resource path = ps.getPath(); if(path instanceof Resource) { Statement values = ps.getProperty(SH.values); if(values != null) { NodeExpression ne = NodeExpressionFactory.get().create(values.getObject()); ne.eval(focusNode, this).forEachRemaining(v -> inferencesModel.getGraph().add(Triple.create(focusNode.asNode(), path.asNode(), v.asNode()))); } Statement defaultValue = ps.getProperty(SH.defaultValue); if(defaultValue != null) { defaultValueMap.put(JenaUtil.asProperty(path), defaultValue.getObject()); } } } } } } // Add sh:defaultValue where needed Model dataModel = dataset.getDefaultModel(); // This is now the union model Resource newFocusNode = focusNode.inModel(dataModel); for(Property predicate : defaultValueMap.keySet()) { if(!newFocusNode.hasProperty(predicate)) { NodeExpression ne = NodeExpressionFactory.get().create(defaultValueMap.get(predicate)); ne.eval(focusNode, this).forEachRemaining(v -> inferencesModel.add(focusNode, predicate, v)); } } return newFocusNode; } return focusNode; } public void addResultMessage(Resource result, Literal message, QuerySolution bindings) { result.addProperty(SH.resultMessage, SPARQLSubstitutions.withSubstitutions(message, bindings, getLabelFunction())); } // Note: does not set sh:path public Resource createResult(Resource type, Constraint constraint, RDFNode focusNode) { Resource result = report.getModel().createResource(type); report.addProperty(SH.result, result); result.addProperty(SH.resultSeverity, constraint.getSeverity()); result.addProperty(SH.sourceConstraintComponent, constraint.getComponent()); result.addProperty(SH.sourceShape, constraint.getShapeResource()); if(focusNode != null) { result.addProperty(SH.focusNode, focusNode); } checkMaximumNumberFailures(constraint); resultsCount++; return result; } public Resource createValidationResult(Constraint constraint, RDFNode focusNode, RDFNode value, Supplier<String> defaultMessage) { Resource result = createResult(SH.ValidationResult, constraint, focusNode); if(value != null) { result.addProperty(SH.value, value); } if(!constraint.getShape().isNodeShape()) { result.addProperty(SH.resultPath, SHACLPaths.clonePath(constraint.getShapeResource().getPath(), result.getModel())); } Collection<RDFNode> messages = constraint.getMessages(); if(messages.size() > 0) { messages.stream().forEach(message -> result.addProperty(SH.resultMessage, message)); } else if(defaultMessage != null) { String m = defaultMessage.get(); if(m != null) { result.addProperty(SH.resultMessage, m); } } return result; } private void checkMaximumNumberFailures(Constraint constraint) { if (SH.Violation.equals(constraint.getShape().getSeverity())) { this.violationsCount++; if (configuration.getValidationErrorBatch() != -1 && violationsCount >= configuration.getValidationErrorBatch()) { throw new MaximumNumberViolations(violationsCount); } } } public ClassesCache getClassesCache() { return classesCache; } public ValidationEngineConfiguration getConfiguration() { return configuration; } public String getLabel(RDFNode node) { return labelsCache.computeIfAbsent(node, n -> getLabelFunction().apply(n)); } public Function<RDFNode,String> getLabelFunction() { return labelFunction; } public ValidationProfile getProfile() { return profile; } /** * Gets the validation report as a Resource in the report Model. * @return the report Resource */ public Resource getReport() { return report; } /** * Gets a Set of all shapes that should be evaluated for a given resource. * @param focusNode the focus node to get the shapes for * @param dataset the Dataset containing the resource * @param shapesModel the shapes Model * @return a Set of shape resources */ private Set<Resource> getShapesForNode(RDFNode focusNode, Dataset dataset, Model shapesModel) { Set<Resource> shapes = new HashSet<>(); for(Shape rootShape : shapesGraph.getRootShapes()) { for(Target target : rootShape.getTargets()) { if(!(target instanceof InstancesTarget)) { if(target.contains(dataset, focusNode)) { shapes.add(rootShape.getShapeResource()); } } } } // rdf:type / sh:targetClass if(focusNode instanceof Resource) { for(Resource type : JenaUtil.getAllTypes((Resource)focusNode)) { if(JenaUtil.hasIndirectType(type.inModel(shapesModel), SH.Shape)) { shapes.add(type); } for(Statement s : shapesModel.listStatements(null, SH.targetClass, type).toList()) { shapes.add(s.getSubject()); } } } return shapes; } public ValidationReport getValidationReport() { return new ResourceValidationReport(report); } public Collection<RDFNode> getValueNodes(Constraint constraint, RDFNode focusNode) { if(constraint.getShape().isNodeShape()) { return Collections.singletonList(focusNode); } else { // We use a cache here because many shapes contains for example both sh:datatype and sh:minCount, and fetching // the value nodes each time may be expensive, esp for sh:minCount/maxCount constraints. ValueNodesCacheKey key = new ValueNodesCacheKey(focusNode, constraint.getShape().getPath()); return valueNodes.computeIfAbsent(key, k -> getValueNodesHelper(focusNode, constraint)); } } private Collection<RDFNode> getValueNodesHelper(RDFNode focusNode, Constraint constraint) { Property predicate = constraint.getShape().getPredicate(); if(predicate != null) { List<RDFNode> results = new LinkedList<>(); if(focusNode instanceof Resource) { Iterator<Statement> it = ((Resource)focusNode).listProperties(predicate); while(it.hasNext()) { results.add(it.next().getObject()); } } return results; } else { Path jenaPath = constraint.getShape().getJenaPath(); if(jenaPath instanceof P_Inverse && ((P_Inverse)jenaPath).getSubPath() instanceof P_Link) { List<RDFNode> results = new LinkedList<>(); Property inversePredicate = ResourceFactory.createProperty(((P_Link)((P_Inverse)jenaPath).getSubPath()).getNode().getURI()); Iterator<Statement> it = focusNode.getModel().listStatements(null, inversePredicate, focusNode); while(it.hasNext()) { results.add(it.next().getSubject()); } return results; } Set<RDFNode> results = new HashSet<>(); Iterator<Node> it = PathEval.eval(focusNode.getModel().getGraph(), focusNode.asNode(), jenaPath, Context.emptyContext()); while(it.hasNext()) { Node node = it.next(); results.add(focusNode.getModel().asRDFNode(node)); } return results; } } /** * Validates a given list of focus nodes against a given Shape, and stops as soon * as one validation result is reported. No results are recorded. * @param focusNodes the nodes to validate * @param shape the sh:Shape to validate against * @return true if there were no validation results, false for violations */ public boolean nodesConformToShape(List<RDFNode> focusNodes, Node shape) { if(!shapesGraph.isIgnored(shape)) { Resource oldReport = report; report = JenaUtil.createMemoryModel().createResource(); try { Shape vs = shapesGraph.getShape(shape); if(!vs.isDeactivated()) { boolean nested = SHACLScriptEngineManager.get().begin(); try { for(Constraint constraint : vs.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); if(report.hasProperty(SH.result)) { return false; } } } finally { SHACLScriptEngineManager.get().end(nested); } } } finally { this.report = oldReport; } } return true; } public void setClassesCache(ClassesCache value) { this.classesCache = value; } /** * Sets a filter that can be used to skip certain focus node from validation. * The filter must return true if the given candidate focus node shall be validated, * and false to skip it. * @param value the new filter */ public void setFocusNodeFilter(Predicate<RDFNode> value) { this.focusNodeFilter = value; } public void setLabelFunction(Function<RDFNode,String> value) { this.labelFunction = value; } public void updateConforms() { boolean conforms = true; StmtIterator it = report.listProperties(SH.result); while(it.hasNext()) { Statement s = it.next(); if(s.getResource().hasProperty(RDF.type, SH.ValidationResult)) { conforms = false; it.close(); break; } } if(report.hasProperty(SH.conforms)) { report.removeAll(SH.conforms); } report.addProperty(SH.conforms, conforms ? JenaDatatypes.TRUE : JenaDatatypes.FALSE); } /** * Validates all target nodes against all of their shapes. * To further narrow down which nodes to validate, use {@link #setFocusNodeFilter(Predicate)}. * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateAll() throws InterruptedException { List<Shape> rootShapes = shapesGraph.getRootShapes(); return validateShapes(rootShapes); } /** * Validates a given focus node against all of the shapes that have matching targets. * @param focusNode the node to validate * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateNode(Node focusNode) throws InterruptedException { Model shapesModel = dataset.getNamedModel(shapesGraphURI.toString()); RDFNode focusRDFNode = dataset.getDefaultModel().asRDFNode(focusNode); Set<Resource> shapes = getShapesForNode(focusRDFNode, dataset, shapesModel); boolean nested = SHACLScriptEngineManager.get().begin(); try { for(Resource shape : shapes) { if(monitor != null && monitor.isCanceled()) { throw new InterruptedException(); } validateNodesAgainstShape(Collections.singletonList(focusRDFNode), shape.asNode()); } } finally { SHACLScriptEngineManager.get().end(nested); } return report; } /** * Validates a given list of focus node against a given Shape. * @param focusNodes the nodes to validate * @param shape the sh:Shape to validate against * @return an instance of sh:ValidationReport in the results Model */ public Resource validateNodesAgainstShape(List<RDFNode> focusNodes, Node shape) { if(!shapesGraph.isIgnored(shape)) { Shape vs = shapesGraph.getShape(shape); if(!vs.isDeactivated()) { boolean nested = SHACLScriptEngineManager.get().begin(); ValidationEngine oldEngine = current.get(); current.set(this); try { for(Constraint constraint : vs.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); } } finally { current.set(oldEngine); SHACLScriptEngineManager.get().end(nested); } } } return report; } /** * Validates all target nodes of a given collection of shapes against these shapes. * To further narrow down which nodes to validate, use {@link #setFocusNodeFilter(Predicate)}. * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateShapes(Collection<Shape> shapes) throws InterruptedException { boolean nested = SHACLScriptEngineManager.get().begin(); try { if(monitor != null) { monitor.beginTask("Validating " + shapes.size() + " shapes", shapes.size()); } if(classesCache == null) { // If we are doing everything then the cache should be used, but not for validation of individual focus nodes classesCache = new ClassesCache(); } int i = 0; for(Shape shape : shapes) { if(monitor != null) { String label = "Shape " + (++i) + ": " + getLabelFunction().apply(shape.getShapeResource()); if(resultsCount > 0) { label = "" + resultsCount + " results. " + label; } monitor.subTask(label); } Collection<RDFNode> focusNodes = shape.getTargetNodes(dataset); if(focusNodeFilter != null) { List<RDFNode> filteredFocusNodes = new LinkedList<>(); for(RDFNode focusNode : focusNodes) { if(focusNodeFilter.test(focusNode)) { filteredFocusNodes.add(focusNode); } } focusNodes = filteredFocusNodes; } if(!focusNodes.isEmpty()) { for(Constraint constraint : shape.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); } } if(monitor != null) { monitor.worked(1); if(monitor.isCanceled()) { throw new InterruptedException(); } } } } catch(MaximumNumberViolations ex) { // Ignore as this is just our way to stop validation when max number of violations is reached } finally { SHACLScriptEngineManager.get().end(nested); } updateConforms(); return report; } protected void validateNodesAgainstConstraint(Collection<RDFNode> focusNodes, Constraint constraint) { if(configuration != null && configuration.isSkippedConstraintComponent(constraint.getComponent())) { return; } ConstraintExecutor executor; try { executor = constraint.getExecutor(); } catch(Exception ex) { Resource result = createResult(DASH.FailureResult, constraint, constraint.getShapeResource()); result.addProperty(SH.resultMessage, "Failed to create validator: " + ExceptionUtil.getStackTrace(ex)); return; } if(executor != null) { if(SHACLPreferences.isProduceFailuresMode()) { try { executor.executeConstraint(constraint, this, focusNodes); } catch(Exception ex) { Resource result = createResult(DASH.FailureResult, constraint, constraint.getShapeResource()); result.addProperty(SH.resultMessage, "Exception during validation: " + ExceptionUtil.getStackTrace(ex)); } } else { executor.executeConstraint(constraint, this, focusNodes); } } else { FailureLog.get().logWarning("No suitable validator found for constraint " + constraint); } } public void setConfiguration(ValidationEngineConfiguration configuration) { this.configuration = configuration; if(!configuration.getValidateShapes()) { shapesGraph.setShapeFilter(new ExcludeMetaShapesFilter()); } } public void setProfile(ValidationProfile profile) { this.profile = profile; } // Used to avoid repeated computation of value nodes for a focus node / path combination private static class ValueNodesCacheKey { Resource path; RDFNode focusNode; ValueNodesCacheKey(RDFNode focusNode, Resource path) { this.path = path; this.focusNode = focusNode; } public boolean equals(Object o) { if(o instanceof ValueNodesCacheKey) { return path.equals(((ValueNodesCacheKey)o).path) && focusNode.equals(((ValueNodesCacheKey)o).focusNode); } else { return false; } } @Override public int hashCode() { return path.hashCode() + focusNode.hashCode(); } @Override public String toString() { return focusNode.toString() + " . " + path; } } } <MSG> #95: Added prefixes from shapes graph <DFF> @@ -118,6 +118,7 @@ public class ValidationEngine extends AbstractEngine implements ConfigurableEngi setConfiguration(new ValidationEngineConfiguration()); if(report == null) { Model reportModel = JenaUtil.createMemoryModel(); + reportModel.setNsPrefixes(shapesGraph.getShapesModel()); reportModel.setNsPrefixes(dataset.getDefaultModel()); this.report = reportModel.createResource(SH.ValidationReport); }
1
#95: Added prefixes from shapes graph
0
.java
java
apache-2.0
TopQuadrant/shacl
411
<NME> ValidationEngine.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl.validation; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import org.apache.jena.graph.Graph; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.graph.compose.MultiUnion; import org.apache.jena.query.Dataset; import org.apache.jena.query.QuerySolution; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import org.apache.jena.sparql.path.P_Inverse; import org.apache.jena.sparql.path.P_Link; import org.apache.jena.sparql.path.Path; import org.apache.jena.sparql.path.eval.PathEval; import org.apache.jena.sparql.util.Context; import org.apache.jena.vocabulary.RDF; import org.topbraid.jenax.util.ExceptionUtil; import org.topbraid.jenax.util.JenaDatatypes; import org.topbraid.jenax.util.JenaUtil; import org.topbraid.jenax.util.RDFLabels; import org.topbraid.shacl.arq.SHACLPaths; import org.topbraid.shacl.engine.AbstractEngine; import org.topbraid.shacl.engine.Constraint; import org.topbraid.shacl.engine.SHACLScriptEngineManager; import org.topbraid.shacl.engine.Shape; import org.topbraid.shacl.engine.ShapesGraph; import org.topbraid.shacl.engine.filters.ExcludeMetaShapesFilter; import org.topbraid.shacl.expr.NodeExpression; import org.topbraid.shacl.expr.NodeExpressionFactory; import org.topbraid.shacl.model.SHNodeShape; import org.topbraid.shacl.model.SHPropertyShape; import org.topbraid.shacl.targets.InstancesTarget; import org.topbraid.shacl.targets.Target; import org.topbraid.shacl.util.FailureLog; import org.topbraid.shacl.util.SHACLPreferences; import org.topbraid.shacl.util.SHACLUtil; import org.topbraid.shacl.validation.sparql.SPARQLSubstitutions; import org.topbraid.shacl.vocabulary.DASH; import org.topbraid.shacl.vocabulary.SH; /** * A ValidationEngine uses a given shapes graph (represented via an instance of ShapesGraph) * and performs SHACL validation on a given Dataset. * * Instances of this class should be created via the ValidatorFactory. * * @author Holger Knublauch */ public class ValidationEngine extends AbstractEngine { // The currently active ValidationEngine for cases where no direct pointer can be acquired, e.g. from HasShapeFunction private static ThreadLocal<ValidationEngine> current = new ThreadLocal<>(); public static ValidationEngine getCurrent() { return current.get(); } public static void setCurrent(ValidationEngine value) { current.set(value); } // Avoids repeatedly walking up/down the class hierarchy for sh:class constraints private ClassesCache classesCache; private ValidationEngineConfiguration configuration; // Can be used to drop certain focus nodes from validation private Predicate<RDFNode> focusNodeFilter; // The inferred triples if the shapes graph declares an entailment regime private Model inferencesModel; // The label function for rendering nodes in validation results (message templates etc) private Function<RDFNode,String> labelFunction = (node -> RDFLabels.get().getNodeLabel(node)); // Avoids repeatedly fetching labels private Map<RDFNode,String> labelsCache = new ConcurrentHashMap<>(); setConfiguration(new ValidationEngineConfiguration()); if(report == null) { Model reportModel = JenaUtil.createMemoryModel(); reportModel.setNsPrefixes(dataset.getDefaultModel()); this.report = reportModel.createResource(SH.ValidationReport); } // Number of created results, e.g. for progress monitor private int resultsCount = 0; // Avoids repeatedly fetching the value nodes of a focus node / path combination private Map<ValueNodesCacheKey,Collection<RDFNode>> valueNodes = new WeakHashMap<>(); // Number of created violations, e.g. for progress monitor private int violationsCount = 0; /** * Constructs a new ValidationEngine. * @param dataset the Dataset to operate on * @param shapesGraphURI the URI of the shapes graph (must be in the dataset) * @param shapesGraph the ShapesGraph with the shapes to validate against * @param report the sh:ValidationReport object in the results Model, or null to create a new one */ protected ValidationEngine(Dataset dataset, URI shapesGraphURI, ShapesGraph shapesGraph, Resource report) { super(dataset, shapesGraph, shapesGraphURI); setConfiguration(new ValidationEngineConfiguration()); if(report == null) { Model reportModel = JenaUtil.createMemoryModel(); reportModel.setNsPrefixes(dataset.getDefaultModel()); // This can be very expensive in some databases reportModel.withDefaultMappings(shapesGraph.getShapesModel()); this.report = reportModel.createResource(SH.ValidationReport); } else { this.report = report; } } /** * Checks if entailments are active for the current shapes graph and applies them for a given focus node. * This will only work for the sh:Rules entailment, e.g. to compute sh:values and sh:defaultValue. * If any inferred triples exist, the focus node will be returned attached to the model that includes those inferences. * The dataset used internally will also be switched to use that new model as its default model, so that if * a node gets validated it will "see" the inferred triples too. * @param focusNode the focus node * @return the focus node, possibly in a different Model than originally */ public RDFNode applyEntailments(Resource focusNode) { Model shapesModel = dataset.getNamedModel(shapesGraphURI.toString()); if(shapesModel.contains(null, SH.entailment, SH.Rules)) { // Create union of data model and inferences if called for the first time if(inferencesModel == null) { inferencesModel = JenaUtil.createDefaultModel(); Model dataModel = dataset.getDefaultModel(); MultiUnion multiUnion = new MultiUnion(new Graph[]{ dataModel.getGraph(), inferencesModel.getGraph() }); multiUnion.setBaseGraph(dataModel.getGraph()); dataset.setDefaultModel(ModelFactory.createModelForGraph(multiUnion)); } // Apply sh:values rules Map<Property,RDFNode> defaultValueMap = new HashMap<>(); for(SHNodeShape nodeShape : SHACLUtil.getAllShapesAtNode(focusNode)) { if(!nodeShape.hasProperty(SH.deactivated, JenaDatatypes.TRUE)) { for(SHPropertyShape ps : nodeShape.getPropertyShapes()) { if(!ps.hasProperty(SH.deactivated, JenaDatatypes.TRUE)) { Resource path = ps.getPath(); if(path instanceof Resource) { Statement values = ps.getProperty(SH.values); if(values != null) { NodeExpression ne = NodeExpressionFactory.get().create(values.getObject()); ne.eval(focusNode, this).forEachRemaining(v -> inferencesModel.getGraph().add(Triple.create(focusNode.asNode(), path.asNode(), v.asNode()))); } Statement defaultValue = ps.getProperty(SH.defaultValue); if(defaultValue != null) { defaultValueMap.put(JenaUtil.asProperty(path), defaultValue.getObject()); } } } } } } // Add sh:defaultValue where needed Model dataModel = dataset.getDefaultModel(); // This is now the union model Resource newFocusNode = focusNode.inModel(dataModel); for(Property predicate : defaultValueMap.keySet()) { if(!newFocusNode.hasProperty(predicate)) { NodeExpression ne = NodeExpressionFactory.get().create(defaultValueMap.get(predicate)); ne.eval(focusNode, this).forEachRemaining(v -> inferencesModel.add(focusNode, predicate, v)); } } return newFocusNode; } return focusNode; } public void addResultMessage(Resource result, Literal message, QuerySolution bindings) { result.addProperty(SH.resultMessage, SPARQLSubstitutions.withSubstitutions(message, bindings, getLabelFunction())); } // Note: does not set sh:path public Resource createResult(Resource type, Constraint constraint, RDFNode focusNode) { Resource result = report.getModel().createResource(type); report.addProperty(SH.result, result); result.addProperty(SH.resultSeverity, constraint.getSeverity()); result.addProperty(SH.sourceConstraintComponent, constraint.getComponent()); result.addProperty(SH.sourceShape, constraint.getShapeResource()); if(focusNode != null) { result.addProperty(SH.focusNode, focusNode); } checkMaximumNumberFailures(constraint); resultsCount++; return result; } public Resource createValidationResult(Constraint constraint, RDFNode focusNode, RDFNode value, Supplier<String> defaultMessage) { Resource result = createResult(SH.ValidationResult, constraint, focusNode); if(value != null) { result.addProperty(SH.value, value); } if(!constraint.getShape().isNodeShape()) { result.addProperty(SH.resultPath, SHACLPaths.clonePath(constraint.getShapeResource().getPath(), result.getModel())); } Collection<RDFNode> messages = constraint.getMessages(); if(messages.size() > 0) { messages.stream().forEach(message -> result.addProperty(SH.resultMessage, message)); } else if(defaultMessage != null) { String m = defaultMessage.get(); if(m != null) { result.addProperty(SH.resultMessage, m); } } return result; } private void checkMaximumNumberFailures(Constraint constraint) { if (SH.Violation.equals(constraint.getShape().getSeverity())) { this.violationsCount++; if (configuration.getValidationErrorBatch() != -1 && violationsCount >= configuration.getValidationErrorBatch()) { throw new MaximumNumberViolations(violationsCount); } } } public ClassesCache getClassesCache() { return classesCache; } public ValidationEngineConfiguration getConfiguration() { return configuration; } public String getLabel(RDFNode node) { return labelsCache.computeIfAbsent(node, n -> getLabelFunction().apply(n)); } public Function<RDFNode,String> getLabelFunction() { return labelFunction; } public ValidationProfile getProfile() { return profile; } /** * Gets the validation report as a Resource in the report Model. * @return the report Resource */ public Resource getReport() { return report; } /** * Gets a Set of all shapes that should be evaluated for a given resource. * @param focusNode the focus node to get the shapes for * @param dataset the Dataset containing the resource * @param shapesModel the shapes Model * @return a Set of shape resources */ private Set<Resource> getShapesForNode(RDFNode focusNode, Dataset dataset, Model shapesModel) { Set<Resource> shapes = new HashSet<>(); for(Shape rootShape : shapesGraph.getRootShapes()) { for(Target target : rootShape.getTargets()) { if(!(target instanceof InstancesTarget)) { if(target.contains(dataset, focusNode)) { shapes.add(rootShape.getShapeResource()); } } } } // rdf:type / sh:targetClass if(focusNode instanceof Resource) { for(Resource type : JenaUtil.getAllTypes((Resource)focusNode)) { if(JenaUtil.hasIndirectType(type.inModel(shapesModel), SH.Shape)) { shapes.add(type); } for(Statement s : shapesModel.listStatements(null, SH.targetClass, type).toList()) { shapes.add(s.getSubject()); } } } return shapes; } public ValidationReport getValidationReport() { return new ResourceValidationReport(report); } public Collection<RDFNode> getValueNodes(Constraint constraint, RDFNode focusNode) { if(constraint.getShape().isNodeShape()) { return Collections.singletonList(focusNode); } else { // We use a cache here because many shapes contains for example both sh:datatype and sh:minCount, and fetching // the value nodes each time may be expensive, esp for sh:minCount/maxCount constraints. ValueNodesCacheKey key = new ValueNodesCacheKey(focusNode, constraint.getShape().getPath()); return valueNodes.computeIfAbsent(key, k -> getValueNodesHelper(focusNode, constraint)); } } private Collection<RDFNode> getValueNodesHelper(RDFNode focusNode, Constraint constraint) { Property predicate = constraint.getShape().getPredicate(); if(predicate != null) { List<RDFNode> results = new LinkedList<>(); if(focusNode instanceof Resource) { Iterator<Statement> it = ((Resource)focusNode).listProperties(predicate); while(it.hasNext()) { results.add(it.next().getObject()); } } return results; } else { Path jenaPath = constraint.getShape().getJenaPath(); if(jenaPath instanceof P_Inverse && ((P_Inverse)jenaPath).getSubPath() instanceof P_Link) { List<RDFNode> results = new LinkedList<>(); Property inversePredicate = ResourceFactory.createProperty(((P_Link)((P_Inverse)jenaPath).getSubPath()).getNode().getURI()); Iterator<Statement> it = focusNode.getModel().listStatements(null, inversePredicate, focusNode); while(it.hasNext()) { results.add(it.next().getSubject()); } return results; } Set<RDFNode> results = new HashSet<>(); Iterator<Node> it = PathEval.eval(focusNode.getModel().getGraph(), focusNode.asNode(), jenaPath, Context.emptyContext()); while(it.hasNext()) { Node node = it.next(); results.add(focusNode.getModel().asRDFNode(node)); } return results; } } /** * Validates a given list of focus nodes against a given Shape, and stops as soon * as one validation result is reported. No results are recorded. * @param focusNodes the nodes to validate * @param shape the sh:Shape to validate against * @return true if there were no validation results, false for violations */ public boolean nodesConformToShape(List<RDFNode> focusNodes, Node shape) { if(!shapesGraph.isIgnored(shape)) { Resource oldReport = report; report = JenaUtil.createMemoryModel().createResource(); try { Shape vs = shapesGraph.getShape(shape); if(!vs.isDeactivated()) { boolean nested = SHACLScriptEngineManager.get().begin(); try { for(Constraint constraint : vs.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); if(report.hasProperty(SH.result)) { return false; } } } finally { SHACLScriptEngineManager.get().end(nested); } } } finally { this.report = oldReport; } } return true; } public void setClassesCache(ClassesCache value) { this.classesCache = value; } /** * Sets a filter that can be used to skip certain focus node from validation. * The filter must return true if the given candidate focus node shall be validated, * and false to skip it. * @param value the new filter */ public void setFocusNodeFilter(Predicate<RDFNode> value) { this.focusNodeFilter = value; } public void setLabelFunction(Function<RDFNode,String> value) { this.labelFunction = value; } public void updateConforms() { boolean conforms = true; StmtIterator it = report.listProperties(SH.result); while(it.hasNext()) { Statement s = it.next(); if(s.getResource().hasProperty(RDF.type, SH.ValidationResult)) { conforms = false; it.close(); break; } } if(report.hasProperty(SH.conforms)) { report.removeAll(SH.conforms); } report.addProperty(SH.conforms, conforms ? JenaDatatypes.TRUE : JenaDatatypes.FALSE); } /** * Validates all target nodes against all of their shapes. * To further narrow down which nodes to validate, use {@link #setFocusNodeFilter(Predicate)}. * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateAll() throws InterruptedException { List<Shape> rootShapes = shapesGraph.getRootShapes(); return validateShapes(rootShapes); } /** * Validates a given focus node against all of the shapes that have matching targets. * @param focusNode the node to validate * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateNode(Node focusNode) throws InterruptedException { Model shapesModel = dataset.getNamedModel(shapesGraphURI.toString()); RDFNode focusRDFNode = dataset.getDefaultModel().asRDFNode(focusNode); Set<Resource> shapes = getShapesForNode(focusRDFNode, dataset, shapesModel); boolean nested = SHACLScriptEngineManager.get().begin(); try { for(Resource shape : shapes) { if(monitor != null && monitor.isCanceled()) { throw new InterruptedException(); } validateNodesAgainstShape(Collections.singletonList(focusRDFNode), shape.asNode()); } } finally { SHACLScriptEngineManager.get().end(nested); } return report; } /** * Validates a given list of focus node against a given Shape. * @param focusNodes the nodes to validate * @param shape the sh:Shape to validate against * @return an instance of sh:ValidationReport in the results Model */ public Resource validateNodesAgainstShape(List<RDFNode> focusNodes, Node shape) { if(!shapesGraph.isIgnored(shape)) { Shape vs = shapesGraph.getShape(shape); if(!vs.isDeactivated()) { boolean nested = SHACLScriptEngineManager.get().begin(); ValidationEngine oldEngine = current.get(); current.set(this); try { for(Constraint constraint : vs.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); } } finally { current.set(oldEngine); SHACLScriptEngineManager.get().end(nested); } } } return report; } /** * Validates all target nodes of a given collection of shapes against these shapes. * To further narrow down which nodes to validate, use {@link #setFocusNodeFilter(Predicate)}. * @return an instance of sh:ValidationReport in the results Model * @throws InterruptedException if the monitor has canceled this */ public Resource validateShapes(Collection<Shape> shapes) throws InterruptedException { boolean nested = SHACLScriptEngineManager.get().begin(); try { if(monitor != null) { monitor.beginTask("Validating " + shapes.size() + " shapes", shapes.size()); } if(classesCache == null) { // If we are doing everything then the cache should be used, but not for validation of individual focus nodes classesCache = new ClassesCache(); } int i = 0; for(Shape shape : shapes) { if(monitor != null) { String label = "Shape " + (++i) + ": " + getLabelFunction().apply(shape.getShapeResource()); if(resultsCount > 0) { label = "" + resultsCount + " results. " + label; } monitor.subTask(label); } Collection<RDFNode> focusNodes = shape.getTargetNodes(dataset); if(focusNodeFilter != null) { List<RDFNode> filteredFocusNodes = new LinkedList<>(); for(RDFNode focusNode : focusNodes) { if(focusNodeFilter.test(focusNode)) { filteredFocusNodes.add(focusNode); } } focusNodes = filteredFocusNodes; } if(!focusNodes.isEmpty()) { for(Constraint constraint : shape.getConstraints()) { validateNodesAgainstConstraint(focusNodes, constraint); } } if(monitor != null) { monitor.worked(1); if(monitor.isCanceled()) { throw new InterruptedException(); } } } } catch(MaximumNumberViolations ex) { // Ignore as this is just our way to stop validation when max number of violations is reached } finally { SHACLScriptEngineManager.get().end(nested); } updateConforms(); return report; } protected void validateNodesAgainstConstraint(Collection<RDFNode> focusNodes, Constraint constraint) { if(configuration != null && configuration.isSkippedConstraintComponent(constraint.getComponent())) { return; } ConstraintExecutor executor; try { executor = constraint.getExecutor(); } catch(Exception ex) { Resource result = createResult(DASH.FailureResult, constraint, constraint.getShapeResource()); result.addProperty(SH.resultMessage, "Failed to create validator: " + ExceptionUtil.getStackTrace(ex)); return; } if(executor != null) { if(SHACLPreferences.isProduceFailuresMode()) { try { executor.executeConstraint(constraint, this, focusNodes); } catch(Exception ex) { Resource result = createResult(DASH.FailureResult, constraint, constraint.getShapeResource()); result.addProperty(SH.resultMessage, "Exception during validation: " + ExceptionUtil.getStackTrace(ex)); } } else { executor.executeConstraint(constraint, this, focusNodes); } } else { FailureLog.get().logWarning("No suitable validator found for constraint " + constraint); } } public void setConfiguration(ValidationEngineConfiguration configuration) { this.configuration = configuration; if(!configuration.getValidateShapes()) { shapesGraph.setShapeFilter(new ExcludeMetaShapesFilter()); } } public void setProfile(ValidationProfile profile) { this.profile = profile; } // Used to avoid repeated computation of value nodes for a focus node / path combination private static class ValueNodesCacheKey { Resource path; RDFNode focusNode; ValueNodesCacheKey(RDFNode focusNode, Resource path) { this.path = path; this.focusNode = focusNode; } public boolean equals(Object o) { if(o instanceof ValueNodesCacheKey) { return path.equals(((ValueNodesCacheKey)o).path) && focusNode.equals(((ValueNodesCacheKey)o).focusNode); } else { return false; } } @Override public int hashCode() { return path.hashCode() + focusNode.hashCode(); } @Override public String toString() { return focusNode.toString() + " . " + path; } } } <MSG> #95: Added prefixes from shapes graph <DFF> @@ -118,6 +118,7 @@ public class ValidationEngine extends AbstractEngine implements ConfigurableEngi setConfiguration(new ValidationEngineConfiguration()); if(report == null) { Model reportModel = JenaUtil.createMemoryModel(); + reportModel.setNsPrefixes(shapesGraph.getShapesModel()); reportModel.setNsPrefixes(dataset.getDefaultModel()); this.report = reportModel.createResource(SH.ValidationReport); }
1
#95: Added prefixes from shapes graph
0
.java
java
apache-2.0
TopQuadrant/shacl
412
<NME> TOSH.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl.vocabulary; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; /** * Vocabulary for http://topbraid.org/tosh */ public class TOSH { public final static String BASE_URI = "http://topbraid.org/tosh"; public final static String NAME = "TopBraid Data Shapes Vocabulary"; public final static String NS = BASE_URI + "#"; public final static String PREFIX = "tosh"; public final static Resource count = ResourceFactory.createResource(NS + "count"); public final static Resource DatatypePropertyShapeView = ResourceFactory.createResource(NS + "DatatypePropertyShapeView"); public final static Resource DeleteTripleSuggestionGenerator = ResourceFactory.createResource(NS + "DeleteTripleSuggestionGenerator"); public final static Resource NodeProcessor = ResourceFactory.createResource(NS + "NodeProcessor"); public final static Resource NodeShapeConstraintsShape = ResourceFactory.createResource(NS + "NodeShapeConstraintsShape"); public final static Resource ObjectPropertyShapeView = ResourceFactory.createResource(NS + "ObjectPropertyShapeView"); public final static Resource TeamworkPlatform = ResourceFactory.createResource(NS + "TeamworkPlatform"); public final static Resource TopBraidPlatform = ResourceFactory.createResource(NS + "TopBraidPlatform"); public final static Resource evalExpr = ResourceFactory.createResource(NS + "evalExpr"); public final static Resource hasShape = ResourceFactory.createResource(NS + "hasShape"); public final static Resource isInTargetOf = ResourceFactory.createResource(NS + "isInTargetOf"); public final static Resource targetContains = ResourceFactory.createResource(NS + "targetContains"); public final static Resource values = ResourceFactory.createResource(NS + "values"); public final static Property closed = ResourceFactory.createProperty(NS + "closed"); public final static Property editGroupDescription = ResourceFactory.createProperty(NS + "editGroupDescription"); public final static Property javaMethod = ResourceFactory.createProperty(NS + "javaMethod"); public final static Property useDeclaredDatatype = ResourceFactory.createProperty(NS + "useDeclaredDatatype"); // Note this property may be deleted in future versions public final static Property viewGadget = ResourceFactory.createProperty(NS + "viewGadget"); public final static Property viewGroupDescription = ResourceFactory.createProperty(NS + "viewGroupDescription"); public final static Property viewWidget = ResourceFactory.createProperty(NS + "viewWidget"); public static String getURI() { return NS; } } <MSG> Alignment with current TQ code base <DFF> @@ -45,6 +45,8 @@ public class TOSH { public final static Resource NodeShapeConstraintsShape = ResourceFactory.createResource(NS + "NodeShapeConstraintsShape"); public final static Resource ObjectPropertyShapeView = ResourceFactory.createResource(NS + "ObjectPropertyShapeView"); + + public final static Resource ResultsGenerators = ResourceFactory.createResource(NS + "ResultsGenerators"); public final static Resource TeamworkPlatform = ResourceFactory.createResource(NS + "TeamworkPlatform");
2
Alignment with current TQ code base
0
.java
java
apache-2.0
TopQuadrant/shacl
413
<NME> TOSH.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl.vocabulary; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; /** * Vocabulary for http://topbraid.org/tosh */ public class TOSH { public final static String BASE_URI = "http://topbraid.org/tosh"; public final static String NAME = "TopBraid Data Shapes Vocabulary"; public final static String NS = BASE_URI + "#"; public final static String PREFIX = "tosh"; public final static Resource count = ResourceFactory.createResource(NS + "count"); public final static Resource DatatypePropertyShapeView = ResourceFactory.createResource(NS + "DatatypePropertyShapeView"); public final static Resource DeleteTripleSuggestionGenerator = ResourceFactory.createResource(NS + "DeleteTripleSuggestionGenerator"); public final static Resource NodeProcessor = ResourceFactory.createResource(NS + "NodeProcessor"); public final static Resource NodeShapeConstraintsShape = ResourceFactory.createResource(NS + "NodeShapeConstraintsShape"); public final static Resource ObjectPropertyShapeView = ResourceFactory.createResource(NS + "ObjectPropertyShapeView"); public final static Resource TeamworkPlatform = ResourceFactory.createResource(NS + "TeamworkPlatform"); public final static Resource TopBraidPlatform = ResourceFactory.createResource(NS + "TopBraidPlatform"); public final static Resource evalExpr = ResourceFactory.createResource(NS + "evalExpr"); public final static Resource hasShape = ResourceFactory.createResource(NS + "hasShape"); public final static Resource isInTargetOf = ResourceFactory.createResource(NS + "isInTargetOf"); public final static Resource targetContains = ResourceFactory.createResource(NS + "targetContains"); public final static Resource values = ResourceFactory.createResource(NS + "values"); public final static Property closed = ResourceFactory.createProperty(NS + "closed"); public final static Property editGroupDescription = ResourceFactory.createProperty(NS + "editGroupDescription"); public final static Property javaMethod = ResourceFactory.createProperty(NS + "javaMethod"); public final static Property useDeclaredDatatype = ResourceFactory.createProperty(NS + "useDeclaredDatatype"); // Note this property may be deleted in future versions public final static Property viewGadget = ResourceFactory.createProperty(NS + "viewGadget"); public final static Property viewGroupDescription = ResourceFactory.createProperty(NS + "viewGroupDescription"); public final static Property viewWidget = ResourceFactory.createProperty(NS + "viewWidget"); public static String getURI() { return NS; } } <MSG> Alignment with current TQ code base <DFF> @@ -45,6 +45,8 @@ public class TOSH { public final static Resource NodeShapeConstraintsShape = ResourceFactory.createResource(NS + "NodeShapeConstraintsShape"); public final static Resource ObjectPropertyShapeView = ResourceFactory.createResource(NS + "ObjectPropertyShapeView"); + + public final static Resource ResultsGenerators = ResourceFactory.createResource(NS + "ResultsGenerators"); public final static Resource TeamworkPlatform = ResourceFactory.createResource(NS + "TeamworkPlatform");
2
Alignment with current TQ code base
0
.java
java
apache-2.0
TopQuadrant/shacl
414
<NME> SHACLFunctionsCache.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl.arq; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.jena.graph.Node; import org.apache.jena.query.Dataset; import org.apache.jena.query.QuerySolution; import org.apache.jena.rdf.model.Model; import org.apache.jena.sparql.expr.ExprEvalException; import org.apache.jena.sparql.expr.NodeValue; /** * A cache that remembers previous calls to SHACL functions marked with sh:cachable. * * @author Holger Knublauch */ public class SHACLFunctionsCache { private static SHACLFunctionsCache singleton = new SHACLFunctionsCache(); public static SHACLFunctionsCache get() { return singleton; } public static void set(SHACLFunctionsCache value) { SHACLFunctionsCache.singleton = value; } private static final int capacity = 10000; @SuppressWarnings("serial") private static class MyCache extends LinkedHashMap<Key,Result> { MyCache() { super(capacity + 1, 1.1f, true); } @Override protected boolean removeEldestEntry(Entry<Key, Result> eldest) { if(size() > capacity) { return true; } else { return false; } } }; private Map<Key,Result> cache = Collections.synchronizedMap(new MyCache()); public void clear() { cache.clear(); } public NodeValue execute(SHACLARQFunction function, Dataset dataset, Model defaultModel, QuerySolution bindings, Node[] args) { Key key = new Key(function.getSHACLFunction().getURI(), args); Result result = cache.get(key); if(result == null) { result = new Result(); try { result.nodeValue = function.executeBody(dataset, defaultModel, bindings); } catch(ExprEvalException ex) { result.ex = ex; } cache.put(key, result); } if(result.ex != null) { throw new ExprEvalException(result.ex.getMessage()); } else { return result.nodeValue; } } private static class Key { private int hashCode; private Node[] args; private String functionURI; Key(String functionURI, Node[] args) { this.args = args; this.functionURI = functionURI; hashCode = functionURI.hashCode(); for(Node arg : args) { if(arg != null) { hashCode += arg.hashCode(); } } } private boolean argEquals(Node arg1, Node arg2) { if(arg1 == null) { return arg2 == null; } else if(arg2 == null) { return false; } else { return arg1.equals(arg2); } } @Override public boolean equals(Object obj) { if(!(obj instanceof Key)) { return false; } Key other = (Key) obj; if(!functionURI.equals(other.functionURI)) { return false; } if(args.length != other.args.length) { return false; } for(int i = 0; i < args.length; i++) { if(!argEquals(args[i], other.args[i])) { return false; } } return true; } @Override public int hashCode() { return hashCode; } } private static class Result { ExprEvalException ex; NodeValue nodeValue; } } <MSG> Merge pull request #131 from linked-art/master Corrected established pattern for newly added @Override methods <DFF> @@ -48,10 +48,9 @@ public class SHACLFunctionsCache { private static final int capacity = 10000; - @SuppressWarnings("serial") private static class MyCache extends LinkedHashMap<Key,Result> { - MyCache() { + MyCache() { super(capacity + 1, 1.1f, true); }
1
Merge pull request #131 from linked-art/master
2
.java
java
apache-2.0
TopQuadrant/shacl
415
<NME> SHACLFunctionsCache.java <BEF> /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. */ package org.topbraid.shacl.arq; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.jena.graph.Node; import org.apache.jena.query.Dataset; import org.apache.jena.query.QuerySolution; import org.apache.jena.rdf.model.Model; import org.apache.jena.sparql.expr.ExprEvalException; import org.apache.jena.sparql.expr.NodeValue; /** * A cache that remembers previous calls to SHACL functions marked with sh:cachable. * * @author Holger Knublauch */ public class SHACLFunctionsCache { private static SHACLFunctionsCache singleton = new SHACLFunctionsCache(); public static SHACLFunctionsCache get() { return singleton; } public static void set(SHACLFunctionsCache value) { SHACLFunctionsCache.singleton = value; } private static final int capacity = 10000; @SuppressWarnings("serial") private static class MyCache extends LinkedHashMap<Key,Result> { MyCache() { super(capacity + 1, 1.1f, true); } @Override protected boolean removeEldestEntry(Entry<Key, Result> eldest) { if(size() > capacity) { return true; } else { return false; } } }; private Map<Key,Result> cache = Collections.synchronizedMap(new MyCache()); public void clear() { cache.clear(); } public NodeValue execute(SHACLARQFunction function, Dataset dataset, Model defaultModel, QuerySolution bindings, Node[] args) { Key key = new Key(function.getSHACLFunction().getURI(), args); Result result = cache.get(key); if(result == null) { result = new Result(); try { result.nodeValue = function.executeBody(dataset, defaultModel, bindings); } catch(ExprEvalException ex) { result.ex = ex; } cache.put(key, result); } if(result.ex != null) { throw new ExprEvalException(result.ex.getMessage()); } else { return result.nodeValue; } } private static class Key { private int hashCode; private Node[] args; private String functionURI; Key(String functionURI, Node[] args) { this.args = args; this.functionURI = functionURI; hashCode = functionURI.hashCode(); for(Node arg : args) { if(arg != null) { hashCode += arg.hashCode(); } } } private boolean argEquals(Node arg1, Node arg2) { if(arg1 == null) { return arg2 == null; } else if(arg2 == null) { return false; } else { return arg1.equals(arg2); } } @Override public boolean equals(Object obj) { if(!(obj instanceof Key)) { return false; } Key other = (Key) obj; if(!functionURI.equals(other.functionURI)) { return false; } if(args.length != other.args.length) { return false; } for(int i = 0; i < args.length; i++) { if(!argEquals(args[i], other.args[i])) { return false; } } return true; } @Override public int hashCode() { return hashCode; } } private static class Result { ExprEvalException ex; NodeValue nodeValue; } } <MSG> Merge pull request #131 from linked-art/master Corrected established pattern for newly added @Override methods <DFF> @@ -48,10 +48,9 @@ public class SHACLFunctionsCache { private static final int capacity = 10000; - @SuppressWarnings("serial") private static class MyCache extends LinkedHashMap<Key,Result> { - MyCache() { + MyCache() { super(capacity + 1, 1.1f, true); }
1
Merge pull request #131 from linked-art/master
2
.java
java
apache-2.0
TopQuadrant/shacl
416
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); }); }); }); if (typeof(Promise) === 'function') { t.test('promises are supported', function(st){ var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #178 from abetomo/update_eslint_rule Update 'space-unary-ops' of eslint <DFF> @@ -127,7 +127,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); }); - if (typeof(Promise) === 'function') { + if (typeof Promise === 'function') { t.test('promises are supported', function(st){ var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) {
1
Merge pull request #178 from abetomo/update_eslint_rule
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
417
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); }); }); }); if (typeof(Promise) === 'function') { t.test('promises are supported', function(st){ var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #178 from abetomo/update_eslint_rule Update 'space-unary-ops' of eslint <DFF> @@ -127,7 +127,7 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); }); - if (typeof(Promise) === 'function') { + if (typeof Promise === 'function') { t.test('promises are supported', function(st){ var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) {
1
Merge pull request #178 from abetomo/update_eslint_rule
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
418
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data // or AWS.restore(); this will restore all the methods and services ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1: /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Updated README.md to include Sinon spy example. <DFF> @@ -62,6 +62,27 @@ AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` +You can also pass Sinon spies to the mock: + +```js +var updateTableSpy = sinon.spy(); +AWS.mock('DynamoDB', 'updateTable', updateTableSpy); + +// Object under test +myDynamoManager.scaleDownTable(); + +// Assert on your Sinon spy as normal +assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); +var expectedParams = { + TableName: 'testTableName', + ProvisionedThroughput: { + ReadCapacityUnits: 1, + WriteCapacityUnits: 1 + } +}; +assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); +``` + **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1:
21
Updated README.md to include Sinon spy example.
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
419
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data // or AWS.restore(); this will restore all the methods and services ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1: /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Updated README.md to include Sinon spy example. <DFF> @@ -62,6 +62,27 @@ AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` +You can also pass Sinon spies to the mock: + +```js +var updateTableSpy = sinon.spy(); +AWS.mock('DynamoDB', 'updateTable', updateTableSpy); + +// Object under test +myDynamoManager.scaleDownTable(); + +// Assert on your Sinon spy as normal +assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); +var expectedParams = { + TableName: 'testTableName', + ProvisionedThroughput: { + ReadCapacityUnits: 1, + WriteCapacityUnits: 1 + } +}; +assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); +``` + **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1:
21
Updated README.md to include Sinon spy example.
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
420
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ``` AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ``` // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #147 from JeongUkJae/master edit README.md <DFF> @@ -53,7 +53,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); -// S3 getObject mock - return a Bffer object with file data +// S3 getObject mock - return a Buffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); @@ -116,7 +116,7 @@ exports.handler = function(event, context) { It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: -``` +```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); @@ -124,7 +124,7 @@ AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: -``` +```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message');
3
Merge pull request #147 from JeongUkJae/master
3
.md
md
apache-2.0
dwyl/aws-sdk-mock
421
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ``` AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ``` // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #147 from JeongUkJae/master edit README.md <DFF> @@ -53,7 +53,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); -// S3 getObject mock - return a Bffer object with file data +// S3 getObject mock - return a Buffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); @@ -116,7 +116,7 @@ exports.handler = function(event, context) { It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: -``` +```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); @@ -124,7 +124,7 @@ AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: -``` +```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message');
3
Merge pull request #147 from JeongUkJae/master
3
.md
md
apache-2.0
dwyl/aws-sdk-mock
422
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Added documentation for enabling promises <DFF> @@ -167,6 +167,22 @@ AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); **/ ``` +### Configuring promises + +You'll need to explicitly enable promises on `aws-sdk-mock` if you use `promise()` functionality of the AWS SDK anywhere in your code. Set the value of `AWS.Promise` to the constructor for your chosen promise library. + +Example (if Q is your promise library of choice): +```js +var AWS = require('aws-sdk-mock'), + Q = require('q'); + +AWS.Promise = Q.Promise; + +/** + TESTS +**/ +``` + ## Documentation ### `AWS.mock(service, method, replace)`
16
Added documentation for enabling promises
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
423
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Added documentation for enabling promises <DFF> @@ -167,6 +167,22 @@ AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); **/ ``` +### Configuring promises + +You'll need to explicitly enable promises on `aws-sdk-mock` if you use `promise()` functionality of the AWS SDK anywhere in your code. Set the value of `AWS.Promise` to the constructor for your chosen promise library. + +Example (if Q is your promise library of choice): +```js +var AWS = require('aws-sdk-mock'), + Q = require('q'); + +AWS.Promise = Q.Promise; + +/** + TESTS +**/ +``` + ## Documentation ### `AWS.mock(service, method, replace)`
16
Added documentation for enabling promises
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
424
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); /** // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #134 from MichaelPaulukonis/you-bffer Corrected spelling of 'Bffer' to 'Buffer' <DFF> @@ -53,7 +53,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); -// S3 getObject mock - return a Bffer object with file data +// S3 getObject mock - return a Buffer object with file data awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); /**
1
Merge pull request #134 from MichaelPaulukonis/you-bffer
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
425
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); /** // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #134 from MichaelPaulukonis/you-bffer Corrected spelling of 'Bffer' to 'Buffer' <DFF> @@ -53,7 +53,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); -// S3 getObject mock - return a Bffer object with file data +// S3 getObject mock - return a Buffer object with file data awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); /**
1
Merge pull request #134 from MichaelPaulukonis/you-bffer
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
426
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); /** TESTS // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> changed new Buffer to Buffer.from <DFF> @@ -54,7 +54,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data -awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); +awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); /** TESTS
1
changed new Buffer to Buffer.from
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
427
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); /** TESTS // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> changed new Buffer to Buffer.from <DFF> @@ -54,7 +54,7 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Bffer object with file data -awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); +awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); /** TESTS
1
changed new Buffer to Buffer.from
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
428
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: https://github.com/dwyl/learn-aws-lambda * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from "aws-sdk-mock"; import AWS from "aws-sdk"; import { GetItemInput } from "aws-sdk/clients/dynamodb"; beforeAll(async (done) => { //get requires env vars done(); }); describe("the module", () => { /** TESTS below here **/ it("should mock getItem from DynamoDB", async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: "foo", sk: "bar"}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it("should mock reading from DocumentClient", async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: "foo", sk: "bar"}); }) const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> readme cleanup and consistency <DFF> @@ -18,7 +18,7 @@ If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: -https://github.com/dwyl/learn-aws-lambda +<https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) @@ -47,18 +47,19 @@ npm install aws-sdk-mock --save-dev ### Use in your Tests #### Using plain JavaScript + ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ - callback(null, "successfully put item in database"); + callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data -awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); +awsMock.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** @@ -74,47 +75,47 @@ AWS.restore('S3'); #### Using TypeScript ```typescript -import AWSMock from "aws-sdk-mock"; -import AWS from "aws-sdk"; -import { GetItemInput } from "aws-sdk/clients/dynamodb"; +import AWSMock from 'aws-sdk-mock'; +import AWS from 'aws-sdk'; +import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); -describe("the module", () => { +describe('the module', () => { /** TESTS below here **/ - it("should mock getItem from DynamoDB", async () => { + it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); - callback(null, {pk: "foo", sk: "bar"}); + callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); - expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); + expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); - it("should mock reading from DocumentClient", async () => { + it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); - callback(null, {pk: "foo", sk: "bar"}); - }) + callback(null, {pk: 'foo', sk: 'bar'}); + }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); - expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); + expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); @@ -122,6 +123,7 @@ describe("the module", () => { ``` #### Sinon + You can also pass Sinon spies to the mock: ```js @@ -146,6 +148,7 @@ assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct pa **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1: + ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); @@ -157,6 +160,7 @@ exports.handler = function(event, context) { ``` Example 2: + ```js const AWS = require('aws-sdk'); @@ -170,6 +174,7 @@ exports.handler = function(event, context) { Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): + ```js exports.handler = function(event, context) { someAsyncFunction(() => { @@ -181,6 +186,7 @@ exports.handler = function(event, context) { ``` Example 2 (will work): + ```js exports.handler = function(event, context) { const sns = AWS.SNS(); @@ -228,18 +234,18 @@ const csd = new AWS.CloudSearchDomain({ region: 'eu-west' }); ``` -Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. +Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. - ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: + ```js const path = require('path'); const AWS = require('aws-sdk-mock'); @@ -256,6 +262,7 @@ AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: + ```js // test code const AWSMock = require('aws-sdk-mock'); @@ -267,12 +274,12 @@ AWSMock.mock('SQS', /* ... */); const sqs = new AWS.SQS(); ``` - ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): + ```js const AWS = require('aws-sdk-mock'), Q = require('q'); @@ -291,14 +298,12 @@ AWS.Promise = Q.Promise; Replaces a method on an AWS service with a replacement function or string. - | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | - ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service @@ -311,19 +316,16 @@ Removes the mock to restore the specified AWS service If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. - ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. - | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | - ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` @@ -340,8 +342,6 @@ Explicitly set the `aws-sdk` instance to use | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | - - ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/)
24
readme cleanup and consistency
24
.md
md
apache-2.0
dwyl/aws-sdk-mock
429
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: https://github.com/dwyl/learn-aws-lambda * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from "aws-sdk-mock"; import AWS from "aws-sdk"; import { GetItemInput } from "aws-sdk/clients/dynamodb"; beforeAll(async (done) => { //get requires env vars done(); }); describe("the module", () => { /** TESTS below here **/ it("should mock getItem from DynamoDB", async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: "foo", sk: "bar"}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it("should mock reading from DocumentClient", async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: "foo", sk: "bar"}); }) const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> readme cleanup and consistency <DFF> @@ -18,7 +18,7 @@ If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: -https://github.com/dwyl/learn-aws-lambda +<https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) @@ -47,18 +47,19 @@ npm install aws-sdk-mock --save-dev ### Use in your Tests #### Using plain JavaScript + ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ - callback(null, "successfully put item in database"); + callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data -awsMock.mock("S3", "getObject", Buffer.from(require("fs").readFileSync("testFile.csv"))); +awsMock.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** @@ -74,47 +75,47 @@ AWS.restore('S3'); #### Using TypeScript ```typescript -import AWSMock from "aws-sdk-mock"; -import AWS from "aws-sdk"; -import { GetItemInput } from "aws-sdk/clients/dynamodb"; +import AWSMock from 'aws-sdk-mock'; +import AWS from 'aws-sdk'; +import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); -describe("the module", () => { +describe('the module', () => { /** TESTS below here **/ - it("should mock getItem from DynamoDB", async () => { + it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); - callback(null, {pk: "foo", sk: "bar"}); + callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); - expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); + expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); - it("should mock reading from DocumentClient", async () => { + it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); - callback(null, {pk: "foo", sk: "bar"}); - }) + callback(null, {pk: 'foo', sk: 'bar'}); + }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); - expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); + expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); @@ -122,6 +123,7 @@ describe("the module", () => { ``` #### Sinon + You can also pass Sinon spies to the mock: ```js @@ -146,6 +148,7 @@ assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct pa **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `region not defined in config` whereas in example 2 the sdk will be successfully mocked. Example 1: + ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); @@ -157,6 +160,7 @@ exports.handler = function(event, context) { ``` Example 2: + ```js const AWS = require('aws-sdk'); @@ -170,6 +174,7 @@ exports.handler = function(event, context) { Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): + ```js exports.handler = function(event, context) { someAsyncFunction(() => { @@ -181,6 +186,7 @@ exports.handler = function(event, context) { ``` Example 2 (will work): + ```js exports.handler = function(event, context) { const sns = AWS.SNS(); @@ -228,18 +234,18 @@ const csd = new AWS.CloudSearchDomain({ region: 'eu-west' }); ``` -Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. +Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. - ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: + ```js const path = require('path'); const AWS = require('aws-sdk-mock'); @@ -256,6 +262,7 @@ AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: + ```js // test code const AWSMock = require('aws-sdk-mock'); @@ -267,12 +274,12 @@ AWSMock.mock('SQS', /* ... */); const sqs = new AWS.SQS(); ``` - ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): + ```js const AWS = require('aws-sdk-mock'), Q = require('q'); @@ -291,14 +298,12 @@ AWS.Promise = Q.Promise; Replaces a method on an AWS service with a replacement function or string. - | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | - ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service @@ -311,19 +316,16 @@ Removes the mock to restore the specified AWS service If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. - ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. - | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | - ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` @@ -340,8 +342,6 @@ Explicitly set the `aws-sdk` instance to use | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | - - ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/)
24
readme cleanup and consistency
24
.md
md
apache-2.0
dwyl/aws-sdk-mock
430
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Merge pull request #35 from H34D/master made restoreService more robust <DFF> @@ -157,7 +157,8 @@ function restoreAllServices() { function restoreService(service) { if (services[service]) { restoreAllMethods(service); - services[service].stub.restore(); + if( services[service].stub) + services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.');
2
Merge pull request #35 from H34D/master
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
431
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> Merge pull request #35 from H34D/master made restoreService more robust <DFF> @@ -157,7 +157,8 @@ function restoreAllServices() { function restoreService(service) { if (services[service]) { restoreAllMethods(service); - services[service].stub.restore(); + if( services[service].stub) + services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.');
2
Merge pull request #35 from H34D/master
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
432
<NME> .travis.yml <BEF> language: node_js node_js: - "4" - "6" - "8" - "10" <MSG> remove support for Node.js v.4 as no longer supported by aws-sdk see: https://github.com/dwyl/aws-sdk-mock/pull/162#issuecomment-444165373 <DFF> @@ -1,6 +1,6 @@ language: node_js node_js: - - "4" + - "node" - "6" - "8" - "10"
1
remove support for Node.js v.4 as no longer supported by aws-sdk see: https://github.com/dwyl/aws-sdk-mock/pull/162#issuecomment-444165373
1
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
433
<NME> .travis.yml <BEF> language: node_js node_js: - "4" - "6" - "8" - "10" <MSG> remove support for Node.js v.4 as no longer supported by aws-sdk see: https://github.com/dwyl/aws-sdk-mock/pull/162#issuecomment-444165373 <DFF> @@ -1,6 +1,6 @@ language: node_js node_js: - - "4" + - "node" - "6" - "8" - "10"
1
remove support for Node.js v.4 as no longer supported by aws-sdk see: https://github.com/dwyl/aws-sdk-mock/pull/162#issuecomment-444165373
1
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
434
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.is(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #276 from abetomo/upgrade_dependencies Upgrade dependencies <DFF> @@ -466,7 +466,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ - st.is(err, null); + st.equal(err, null); st.equal(data, 'test'); st.end(); });
1
Merge pull request #276 from abetomo/upgrade_dependencies
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
435
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.is(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #276 from abetomo/upgrade_dependencies Upgrade dependencies <DFF> @@ -466,7 +466,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ - st.is(err, null); + st.equal(err, null); st.equal(data, 'test'); st.end(); });
1
Merge pull request #276 from abetomo/upgrade_dependencies
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
436
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Update README.md <DFF> @@ -34,7 +34,7 @@ Using stubs means you can prevent a specific method from being called directly. ## What? -Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods. +Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*)
1
Update README.md
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
437
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Update README.md <DFF> @@ -34,7 +34,7 @@ Using stubs means you can prevent a specific method from being called directly. ## What? -Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods. +Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*)
1
Update README.md
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
438
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }) t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); var s3 = new AWS.S3(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }) t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); }) }) t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); lambda.createFunction({}, function(err, data) { st.equals(data, 'message'); st.end(); }) }); }); if (typeof(Promise) === 'function') { callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise() }).catch(function(data){ st.equals(data, error); st.end(); }); }) t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise() }).catch(function(data){ st.equals(data, error); st.end(); }); }) t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { const lambda = new AWS.Lambda(); }); var lambda = new AWS.Lambda(); function P(handler) { var self = this function yay (value) { self.value = value } handler(yay, function(){}) } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P) var promise = lambda.getFunction({}).promise() st.equals(promise.constructor.name, 'P') promise.then(function(data) { st.equals(data, 'message'); st.end(); }); }) } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body') awsMock.restore('S3', 'getObject'); st.end(); })); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body') awsMock.restore('S3', 'getObject'); st.end(); })); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), '') awsMock.restore('S3', 'getObject'); st.end(); })); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), '') awsMock.restore('S3', 'getObject'); st.end(); })); t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }) }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); }) }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); st.equals(data, 'message'); }); st.end(); }) t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e) } }); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message') }); awsMock.setSDK('aws-sdk'); awsMock.restore() st.end(); }); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { var aws2 = require('aws-sdk') awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); var sns = new AWS.SNS(); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ st.equals(data, 'message2'); awsMock.restore('SNS'); st.end(); }) }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { var bad = {} awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message') }); awsMock.setSDKInstance(AWS); awsMock.restore() st.end(); }); t.end(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #78 from abetomo/fix_add_semicolon Fix add semicolon <DFF> @@ -14,7 +14,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ @@ -25,8 +25,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); var s3 = new AWS.S3(); @@ -83,8 +83,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -97,8 +97,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -112,7 +112,7 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.createFunction({}, function(err, data) { st.equals(data, 'message'); st.end(); - }) + }); }); }); if (typeof(Promise) === 'function') { @@ -130,12 +130,12 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ - return lambda.createFunction({}).promise() + return lambda.createFunction({}).promise(); }).catch(function(data){ st.equals(data, error); st.end(); }); - }) + }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); @@ -150,12 +150,12 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ - return lambda.createFunction({}).promise() + return lambda.createFunction({}).promise(); }).catch(function(data){ st.equals(data, error); st.end(); }); - }) + }); t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { @@ -163,21 +163,21 @@ test('AWS.mock function should mock AWS service and method on the service', func }); var lambda = new AWS.Lambda(); function P(handler) { - var self = this + var self = this; function yay (value) { - self.value = value + self.value = value; } - handler(yay, function(){}) + handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; - AWS.config.setPromisesDependency(P) - var promise = lambda.getFunction({}).promise() - st.equals(promise.constructor.name, 'P') + AWS.config.setPromisesDependency(P); + var promise = lambda.getFunction({}).promise(); + st.equals(promise.constructor.name, 'P'); promise.then(function(data) { st.equals(data, 'message'); st.end(); }); - }) + }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); @@ -202,7 +202,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), 'body') + st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -213,7 +213,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), 'body') + st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -224,7 +224,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), '') + st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -235,7 +235,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), '') + st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -251,7 +251,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -265,7 +265,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -296,7 +296,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); @@ -325,7 +325,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); - }) + }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { @@ -340,7 +340,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); - }) + }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); @@ -405,7 +405,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); }); st.end(); - }) + }); t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); @@ -420,7 +420,7 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { - console.log(e) + console.log(e); } }); @@ -435,16 +435,16 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { - awsMock.mock('SNS', 'publish', 'message') + awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); - awsMock.restore() + awsMock.restore(); st.end(); }); @@ -453,7 +453,7 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { - var aws2 = require('aws-sdk') + var aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); var sns = new AWS.SNS(); @@ -461,17 +461,17 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t st.equals(data, 'message2'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { - var bad = {} + var bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { - awsMock.mock('SNS', 'publish', 'message') + awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); - awsMock.restore() + awsMock.restore(); st.end(); }); t.end();
38
Merge pull request #78 from abetomo/fix_add_semicolon
38
.js
test
apache-2.0
dwyl/aws-sdk-mock
439
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }) t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); var s3 = new AWS.S3(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }) t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); }) }) t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); lambda.createFunction({}, function(err, data) { st.equals(data, 'message'); st.end(); }) }); }); if (typeof(Promise) === 'function') { callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise() }).catch(function(data){ st.equals(data, error); st.end(); }); }) t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise() }).catch(function(data){ st.equals(data, error); st.end(); }); }) t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { const lambda = new AWS.Lambda(); }); var lambda = new AWS.Lambda(); function P(handler) { var self = this function yay (value) { self.value = value } handler(yay, function(){}) } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P) var promise = lambda.getFunction({}).promise() st.equals(promise.constructor.name, 'P') promise.then(function(data) { st.equals(data, 'message'); st.end(); }); }) } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body') awsMock.restore('S3', 'getObject'); st.end(); })); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body') awsMock.restore('S3', 'getObject'); st.end(); })); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), '') awsMock.restore('S3', 'getObject'); st.end(); })); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), '') awsMock.restore('S3', 'getObject'); st.end(); })); t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }) }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); }) }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); st.equals(data, 'message'); }); st.end(); }) t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e) } }); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }) }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message') }); awsMock.setSDK('aws-sdk'); awsMock.restore() st.end(); }); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { var aws2 = require('aws-sdk') awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); var sns = new AWS.SNS(); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ st.equals(data, 'message2'); awsMock.restore('SNS'); st.end(); }) }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { var bad = {} awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message') }); awsMock.setSDKInstance(AWS); awsMock.restore() st.end(); }); t.end(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #78 from abetomo/fix_add_semicolon Fix add semicolon <DFF> @@ -14,7 +14,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ @@ -25,8 +25,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); var s3 = new AWS.S3(); @@ -83,8 +83,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -97,8 +97,8 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); - }) - }) + }); + }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -112,7 +112,7 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.createFunction({}, function(err, data) { st.equals(data, 'message'); st.end(); - }) + }); }); }); if (typeof(Promise) === 'function') { @@ -130,12 +130,12 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ - return lambda.createFunction({}).promise() + return lambda.createFunction({}).promise(); }).catch(function(data){ st.equals(data, error); st.end(); }); - }) + }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); @@ -150,12 +150,12 @@ test('AWS.mock function should mock AWS service and method on the service', func lambda.getFunction({}).promise().then(function(data) { st.equals(data, 'message'); }).then(function(){ - return lambda.createFunction({}).promise() + return lambda.createFunction({}).promise(); }).catch(function(data){ st.equals(data, error); st.end(); }); - }) + }); t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { @@ -163,21 +163,21 @@ test('AWS.mock function should mock AWS service and method on the service', func }); var lambda = new AWS.Lambda(); function P(handler) { - var self = this + var self = this; function yay (value) { - self.value = value + self.value = value; } - handler(yay, function(){}) + handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; - AWS.config.setPromisesDependency(P) - var promise = lambda.getFunction({}).promise() - st.equals(promise.constructor.name, 'P') + AWS.config.setPromisesDependency(P); + var promise = lambda.getFunction({}).promise(); + st.equals(promise.constructor.name, 'P'); promise.then(function(data) { st.equals(data, 'message'); st.end(); }); - }) + }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); @@ -202,7 +202,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), 'body') + st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -213,7 +213,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), 'body') + st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -224,7 +224,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), '') + st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -235,7 +235,7 @@ test('AWS.mock function should mock AWS service and method on the service', func var req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { - st.equals(actual.toString(), '') + st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); @@ -251,7 +251,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -265,7 +265,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); @@ -296,7 +296,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); - }) + }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); @@ -325,7 +325,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); - }) + }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { @@ -340,7 +340,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); - }) + }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); @@ -405,7 +405,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(data, 'message'); }); st.end(); - }) + }); t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); @@ -420,7 +420,7 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { - console.log(e) + console.log(e); } }); @@ -435,16 +435,16 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { - awsMock.mock('SNS', 'publish', 'message') + awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); - awsMock.restore() + awsMock.restore(); st.end(); }); @@ -453,7 +453,7 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { - var aws2 = require('aws-sdk') + var aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); var sns = new AWS.SNS(); @@ -461,17 +461,17 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t st.equals(data, 'message2'); awsMock.restore('SNS'); st.end(); - }) + }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { - var bad = {} + var bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { - awsMock.mock('SNS', 'publish', 'message') + awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); - awsMock.restore() + awsMock.restore(); st.end(); }); t.end();
38
Merge pull request #78 from abetomo/fix_add_semicolon
38
.js
test
apache-2.0
dwyl/aws-sdk-mock
440
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equals(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equals(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> When method is restored, it should be restored on all clients <DFF> @@ -113,28 +113,6 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('all instances of service are re-mocked when remock called', function(st){ - awsMock.mock('SNS', 'subscribe', function(params, callback){ - callback(null, 'message 1'); - }); - const sns1 = new AWS.SNS(); - const sns2 = new AWS.SNS(); - - awsMock.remock('SNS', 'subscribe', function(params, callback){ - callback(null, 'message 2'); - }); - - sns1.subscribe({}, function(err, data){ - st.equals(data, 'message 2'); - - sns2.subscribe({}, function(err, data){ - st.equals(data, 'message 2'); - st.end(); - }); - - }); - }); - t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -332,6 +310,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); + t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); @@ -346,6 +325,27 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); + + t.test('methods on all service instances are restored', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, 'message'); + }); + + const sns1 = new AWS.SNS(); + const sns2 = new AWS.SNS(); + + st.equals(AWS.SNS.isSinonProxy, true); + st.equals(sns1.publish.isSinonProxy, true); + st.equals(sns2.publish.isSinonProxy, true); + + awsMock.restore('SNS', 'publish'); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); + st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false); + st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); + st.end(); + }); + t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message');
22
When method is restored, it should be restored on all clients
22
.js
test
apache-2.0
dwyl/aws-sdk-mock
441
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equals(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equals(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> When method is restored, it should be restored on all clients <DFF> @@ -113,28 +113,6 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('all instances of service are re-mocked when remock called', function(st){ - awsMock.mock('SNS', 'subscribe', function(params, callback){ - callback(null, 'message 1'); - }); - const sns1 = new AWS.SNS(); - const sns2 = new AWS.SNS(); - - awsMock.remock('SNS', 'subscribe', function(params, callback){ - callback(null, 'message 2'); - }); - - sns1.subscribe({}, function(err, data){ - st.equals(data, 'message 2'); - - sns2.subscribe({}, function(err, data){ - st.equals(data, 'message 2'); - st.end(); - }); - - }); - }); - t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -332,6 +310,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); + t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); @@ -346,6 +325,27 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); + + t.test('methods on all service instances are restored', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, 'message'); + }); + + const sns1 = new AWS.SNS(); + const sns2 = new AWS.SNS(); + + st.equals(AWS.SNS.isSinonProxy, true); + st.equals(sns1.publish.isSinonProxy, true); + st.equals(sns2.publish.isSinonProxy, true); + + awsMock.restore('SNS', 'publish'); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); + st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false); + st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); + st.end(); + }); + t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message');
22
When method is restored, it should be restored on all clients
22
.js
test
apache-2.0
dwyl/aws-sdk-mock
442
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); st.end(); }) }) t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #10 from dwyl/fixed-multiple-functions-bug You can now mock out multiple methods on the same service <DFF> @@ -51,6 +51,22 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }) }) + t.test('multiple methods can be mocked on the same service', function(st){ + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + callback(null, 'message'); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}, function(err, data) { + st.equals(data, 'message'); + lambda.createFunction({}, function(err, data) { + st.equals(data, 'message'); + st.end(); + }) + }); + }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
16
Merge pull request #10 from dwyl/fixed-multiple-functions-bug
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
443
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); st.end(); }) }) t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #10 from dwyl/fixed-multiple-functions-bug You can now mock out multiple methods on the same service <DFF> @@ -51,6 +51,22 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }) }) + t.test('multiple methods can be mocked on the same service', function(st){ + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + callback(null, 'message'); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}, function(err, data) { + st.equals(data, 'message'); + lambda.createFunction({}, function(err, data) { + st.equals(data, 'message'); + st.end(); + }) + }); + }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
16
Merge pull request #10 from dwyl/fixed-multiple-functions-bug
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
444
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, "test"); }); var sns = new AWS.SNS(); var dynamoDb = new AWS.DynamoDB(); st.equals(AWS.SNS.isSinonProxy, true); st.equals(AWS.DynamoDB.isSinonProxy, true); st.equals(sns.publish.isSinonProxy, true); st.equals(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #17 from mkjois/master Added ability to mock nested services <DFF> @@ -100,22 +100,100 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, "test"); }); + awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ + callback(null, "test"); + }); var sns = new AWS.SNS(); + var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB(); st.equals(AWS.SNS.isSinonProxy, true); + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equals(AWS.DynamoDB.isSinonProxy, true); st.equals(sns.publish.isSinonProxy, true); + st.equals(docClient.put.isSinonProxy, true); st.equals(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); + st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); + st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) + t.test('a nested service can be mocked properly', function(st){ + awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); + var docClient = new AWS.DynamoDB.DocumentClient(); + awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { + callback(null, 'test'); + }); + awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { + callback(null, 'test'); + }); + + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(docClient.put.isSinonProxy, true); + st.equals(docClient.get.isSinonProxy, true); + + docClient.put({}, function(err, data){ + st.equals(data, 'message'); + docClient.get({}, function(err, data){ + st.equals(data, 'test'); + + awsMock.restore('DynamoDB.DocumentClient', 'get'); + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false); + + awsMock.restore('DynamoDB.DocumentClient'); + st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); + st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); + st.end(); + }); + }) + }); + t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { + awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); + awsMock.mock('DynamoDB', 'getItem', 'test'); + var docClient = new AWS.DynamoDB.DocumentClient(); + var dynamoDb = new AWS.DynamoDB(); + + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(AWS.DynamoDB.isSinonProxy, true); + st.equals(docClient.get.isSinonProxy, true); + st.equals(dynamoDb.getItem.isSinonProxy, true); + + awsMock.restore('DynamoDB'); + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); + st.equals(docClient.get.isSinonProxy, true); + st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); + + awsMock.mock('DynamoDB', 'getItem', 'test'); + var dynamoDb = new AWS.DynamoDB(); + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(AWS.DynamoDB.isSinonProxy, true); + st.equals(docClient.get.isSinonProxy, true); + st.equals(dynamoDb.getItem.isSinonProxy, true); + + awsMock.restore('DynamoDB.DocumentClient'); + + // the first assertion is true because DynamoDB is still mocked + st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); + st.equals(AWS.DynamoDB.isSinonProxy, true); + st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false); + st.equals(dynamoDb.getItem.isSinonProxy, true); + + awsMock.restore('DynamoDB'); + st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); + st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); + st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false); + st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); + st.end(); + + }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
78
Merge pull request #17 from mkjois/master
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
445
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, "test"); }); var sns = new AWS.SNS(); var dynamoDb = new AWS.DynamoDB(); st.equals(AWS.SNS.isSinonProxy, true); st.equals(AWS.DynamoDB.isSinonProxy, true); st.equals(sns.publish.isSinonProxy, true); st.equals(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #17 from mkjois/master Added ability to mock nested services <DFF> @@ -100,22 +100,100 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, "test"); }); + awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ + callback(null, "test"); + }); var sns = new AWS.SNS(); + var docClient = new AWS.DynamoDB.DocumentClient(); var dynamoDb = new AWS.DynamoDB(); st.equals(AWS.SNS.isSinonProxy, true); + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equals(AWS.DynamoDB.isSinonProxy, true); st.equals(sns.publish.isSinonProxy, true); + st.equals(docClient.put.isSinonProxy, true); st.equals(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); + st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); + st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) + t.test('a nested service can be mocked properly', function(st){ + awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); + var docClient = new AWS.DynamoDB.DocumentClient(); + awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { + callback(null, 'test'); + }); + awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { + callback(null, 'test'); + }); + + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(docClient.put.isSinonProxy, true); + st.equals(docClient.get.isSinonProxy, true); + + docClient.put({}, function(err, data){ + st.equals(data, 'message'); + docClient.get({}, function(err, data){ + st.equals(data, 'test'); + + awsMock.restore('DynamoDB.DocumentClient', 'get'); + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false); + + awsMock.restore('DynamoDB.DocumentClient'); + st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); + st.equals(docClient.put.hasOwnProperty('isSinonProxy'), false); + st.end(); + }); + }) + }); + t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { + awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); + awsMock.mock('DynamoDB', 'getItem', 'test'); + var docClient = new AWS.DynamoDB.DocumentClient(); + var dynamoDb = new AWS.DynamoDB(); + + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(AWS.DynamoDB.isSinonProxy, true); + st.equals(docClient.get.isSinonProxy, true); + st.equals(dynamoDb.getItem.isSinonProxy, true); + + awsMock.restore('DynamoDB'); + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); + st.equals(docClient.get.isSinonProxy, true); + st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); + + awsMock.mock('DynamoDB', 'getItem', 'test'); + var dynamoDb = new AWS.DynamoDB(); + st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); + st.equals(AWS.DynamoDB.isSinonProxy, true); + st.equals(docClient.get.isSinonProxy, true); + st.equals(dynamoDb.getItem.isSinonProxy, true); + + awsMock.restore('DynamoDB.DocumentClient'); + + // the first assertion is true because DynamoDB is still mocked + st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); + st.equals(AWS.DynamoDB.isSinonProxy, true); + st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false); + st.equals(dynamoDb.getItem.isSinonProxy, true); + + awsMock.restore('DynamoDB'); + st.equals(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); + st.equals(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); + st.equals(docClient.get.hasOwnProperty('isSinonProxy'), false); + st.equals(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); + st.end(); + + }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) {
78
Merge pull request #17 from mkjois/master
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
446
<NME> index.test-d.ts <BEF> import * as AWS from 'aws-sdk'; import { AWSError } from 'aws-sdk'; import { ListObjectsV2Request } from 'aws-sdk/clients/s3'; import { expectError, expectType } from 'tsd'; import { mock, remock, restore, setSDK, setSDKInstance } from '../index'; const awsError: AWSError = { name: 'AWSError', message: 'message', code: 'code', time: new Date(), }; expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); const output: AWS.S3.ListObjectsV2Output = { Name: params.Bucket, MaxKeys: params.MaxKeys, Delimiter: params.Delimiter, Prefix: params.Prefix, KeyCount: 1, IsTruncated: false, ContinuationToken: params.ContinuationToken, Contents: [ { LastModified: new Date(), ETag: '"668d791b0c7d6a7f0f86c269888b4546"', StorageClass: 'STANDARD', Key: 'aws-sdk-mock/index.js', Size: 8524, }, ] }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectError(mock('S3', 'describeObjects', (params, callback) => { expectType<never>(params); expectType<never>(callback); })); expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen')); expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen')); expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen')); expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen')); expectError(mock('StaticDB', 'getItem', "it couldn't")); expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { // $ExpectType string[] const instanceIds = params.InstanceIds; expectType<string[]>(instanceIds); const output: AWS.EC2.StopInstancesResult = { StoppingInstances: instanceIds.map(id => ({ InstanceId: id, PreviousState: { Name: 'running' }, CurrentState: { Name: 'stopping' }, })), }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectType<void>(remock('Snowball', 'makeRequest', undefined)); expectError(remock('Snowball', 'throwRequest', undefined)); expectType<void>(restore('Pricing', 'getProducts')); expectError(restore('Pricing', 'borrowMoney')); expectType<void>(restore('KMS')); expectError(restore('Skynet')); expectError(restore(42)); expectType<void>(restore()); expectError(restore(null)); expectType<void>(setSDK('aws-sdk')); expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk'))); async function foo() { expectType<void>(setSDKInstance(await import('aws-sdk'))); } expectError(setSDKInstance(AWS.S3)); import allClients = require('aws-sdk/clients/all'); expectError(setSDKInstance(allClients)); <MSG> #259: support nested client names for remock and restore methods <DFF> @@ -11,6 +11,9 @@ const awsError: AWSError = { time: new Date(), }; +/** + * mock + */ expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); @@ -83,16 +86,30 @@ expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { expectError(callback(awsError, output)); })); +/** + * Remock + */ expectType<void>(remock('Snowball', 'makeRequest', undefined)); +expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined)); + expectError(remock('Snowball', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentServer', 'get', undefined)); +/** + * Restore + */ expectType<void>(restore('Pricing', 'getProducts')); +expectType<void>(restore('DynamoDB.DocumentClient', 'get')); expectError(restore('Pricing', 'borrowMoney')); +expectError(restore('DynamoDB.DocumentClient', 'unknown')); expectType<void>(restore('KMS')); +expectType<void>(restore('DynamoDB.DocumentClient')); expectError(restore('Skynet')); +expectError(restore('DynamoDB.DocumentServer')); expectError(restore(42)); @@ -100,8 +117,14 @@ expectType<void>(restore()); expectError(restore(null)); +/** + * setSDK + */ expectType<void>(setSDK('aws-sdk')); +/** + * setSDKInstance + */ expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk')));
23
#259: support nested client names for remock and restore methods
0
.ts
test-d
apache-2.0
dwyl/aws-sdk-mock
447
<NME> index.test-d.ts <BEF> import * as AWS from 'aws-sdk'; import { AWSError } from 'aws-sdk'; import { ListObjectsV2Request } from 'aws-sdk/clients/s3'; import { expectError, expectType } from 'tsd'; import { mock, remock, restore, setSDK, setSDKInstance } from '../index'; const awsError: AWSError = { name: 'AWSError', message: 'message', code: 'code', time: new Date(), }; expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); const output: AWS.S3.ListObjectsV2Output = { Name: params.Bucket, MaxKeys: params.MaxKeys, Delimiter: params.Delimiter, Prefix: params.Prefix, KeyCount: 1, IsTruncated: false, ContinuationToken: params.ContinuationToken, Contents: [ { LastModified: new Date(), ETag: '"668d791b0c7d6a7f0f86c269888b4546"', StorageClass: 'STANDARD', Key: 'aws-sdk-mock/index.js', Size: 8524, }, ] }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectError(mock('S3', 'describeObjects', (params, callback) => { expectType<never>(params); expectType<never>(callback); })); expectType<void>(mock('DynamoDB', 'getItem', 'anything could happen')); expectType<void>(mock('DynamoDB.DocumentClient', 'get', 'anything could happen')); expectError(mock('DynamoDB.DocumentServer', 'get', 'nothing can happen')); expectError(mock('DynamoDB.DocumentClient', 'unknown', 'nothing can happen')); expectError(mock('StaticDB', 'getItem', "it couldn't")); expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { // $ExpectType string[] const instanceIds = params.InstanceIds; expectType<string[]>(instanceIds); const output: AWS.EC2.StopInstancesResult = { StoppingInstances: instanceIds.map(id => ({ InstanceId: id, PreviousState: { Name: 'running' }, CurrentState: { Name: 'stopping' }, })), }; expectType<void>(callback(undefined, output)); expectType<void>(callback(undefined, {})); expectError(callback(null, output)); expectError(callback(undefined)); expectType<void>(callback(awsError)); expectError(callback(awsError, output)); })); expectType<void>(remock('Snowball', 'makeRequest', undefined)); expectError(remock('Snowball', 'throwRequest', undefined)); expectType<void>(restore('Pricing', 'getProducts')); expectError(restore('Pricing', 'borrowMoney')); expectType<void>(restore('KMS')); expectError(restore('Skynet')); expectError(restore(42)); expectType<void>(restore()); expectError(restore(null)); expectType<void>(setSDK('aws-sdk')); expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk'))); async function foo() { expectType<void>(setSDKInstance(await import('aws-sdk'))); } expectError(setSDKInstance(AWS.S3)); import allClients = require('aws-sdk/clients/all'); expectError(setSDKInstance(allClients)); <MSG> #259: support nested client names for remock and restore methods <DFF> @@ -11,6 +11,9 @@ const awsError: AWSError = { time: new Date(), }; +/** + * mock + */ expectType<void>(mock('S3', 'listObjectsV2', (params, callback) => { expectType<ListObjectsV2Request>(params); @@ -83,16 +86,30 @@ expectType<void>(remock('EC2', 'stopInstances', (params, callback) => { expectError(callback(awsError, output)); })); +/** + * Remock + */ expectType<void>(remock('Snowball', 'makeRequest', undefined)); +expectType<void>(remock('DynamoDB.DocumentClient', 'get', undefined)); + expectError(remock('Snowball', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentClient', 'throwRequest', undefined)); +expectError(remock('DynamoDB.DocumentServer', 'get', undefined)); +/** + * Restore + */ expectType<void>(restore('Pricing', 'getProducts')); +expectType<void>(restore('DynamoDB.DocumentClient', 'get')); expectError(restore('Pricing', 'borrowMoney')); +expectError(restore('DynamoDB.DocumentClient', 'unknown')); expectType<void>(restore('KMS')); +expectType<void>(restore('DynamoDB.DocumentClient')); expectError(restore('Skynet')); +expectError(restore('DynamoDB.DocumentServer')); expectError(restore(42)); @@ -100,8 +117,14 @@ expectType<void>(restore()); expectError(restore(null)); +/** + * setSDK + */ expectType<void>(setSDK('aws-sdk')); +/** + * setSDKInstance + */ expectType<void>(setSDKInstance(AWS)); expectError(setSDKInstance(import('aws-sdk')));
23
#259: support nested client names for remock and restore methods
0
.ts
test-d
apache-2.0
dwyl/aws-sdk-mock
448
<NME> .travis.yml <BEF> language: node_js node_js: - "12" - "6" - "8" - "10" before_install: - pip install --user codecov after_success: <MSG> Merge pull request #185 from abetomo/add_nodejs12_to_ci_setting Add Node.js 12 to CI setting <DFF> @@ -4,6 +4,7 @@ node_js: - "6" - "8" - "10" + - "12" before_install: - pip install --user codecov after_success:
1
Merge pull request #185 from abetomo/add_nodejs12_to_ci_setting
0
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
449
<NME> .travis.yml <BEF> language: node_js node_js: - "12" - "6" - "8" - "10" before_install: - pip install --user codecov after_success: <MSG> Merge pull request #185 from abetomo/add_nodejs12_to_ci_setting Add Node.js 12 to CI setting <DFF> @@ -4,6 +4,7 @@ node_js: - "6" - "8" - "10" + - "12" before_install: - pip install --user codecov after_success:
1
Merge pull request #185 from abetomo/add_nodejs12_to_ci_setting
0
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
450
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); var s3 = new AWS.S3({paramValidation: true}); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> fix(paramValidation): skip param validation when method has no input rules <DFF> @@ -52,6 +52,15 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { + awsMock.mock('S3', 'getSignedUrl', 'message'); + var s3 = new AWS.S3({paramValidation: true}); + s3.getSignedUrl('getObject', {}, function(err, data) { + st.equals(data, 'message'); + awsMock.restore('S3'); + st.end(); + }); + }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); var s3 = new AWS.S3({paramValidation: true});
9
fix(paramValidation): skip param validation when method has no input rules
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
451
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); var s3 = new AWS.S3({paramValidation: true}); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> fix(paramValidation): skip param validation when method has no input rules <DFF> @@ -52,6 +52,15 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { + awsMock.mock('S3', 'getSignedUrl', 'message'); + var s3 = new AWS.S3({paramValidation: true}); + s3.getSignedUrl('getObject', {}, function(err, data) { + st.equals(data, 'message'); + awsMock.restore('S3'); + st.end(); + }); + }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); var s3 = new AWS.S3({paramValidation: true});
9
fix(paramValidation): skip param validation when method has no input rules
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
452
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #103 from lukemcgregor/patch-1 Fixed minor markdown formatting issue <DFF> @@ -23,7 +23,7 @@ https://github.com/dwyl/learn-aws-lambda * [Documentation](#documentation) * [Background Reading](#background-reading) -## Why? +## Why? Testing your code is *essential* everywhere you need *reliability*.
1
Merge pull request #103 from lukemcgregor/patch-1
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
453
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Merge pull request #103 from lukemcgregor/patch-1 Fixed minor markdown formatting issue <DFF> @@ -23,7 +23,7 @@ https://github.com/dwyl/learn-aws-lambda * [Documentation](#documentation) * [Background Reading](#background-reading) -## Why? +## Why? Testing your code is *essential* everywhere you need *reliability*.
1
Merge pull request #103 from lukemcgregor/patch-1
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
454
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); st.end(); }); }); t.test('method is re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); st.end(); }); }); t.test('service is re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); st.end(); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'puttest'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> add update flag <DFF> @@ -72,7 +72,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('method is re-mocked if a mock already exists', function(st){ + t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); @@ -85,7 +85,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('service is re-mocked if a mock already exists', function(st){ + t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); @@ -98,6 +98,19 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('service is re-mocked if update flag passed', function(st){ + awsMock.mock('SNS', 'subscribe', function(params, callback){ + callback(null, 'message 1'); + }); + var sns = new AWS.SNS(); + awsMock.mock('SNS', 'subscribe', function(params, callback){ + callback(null, 'message 2'); + }, true); + sns.subscribe({}, function(err, data){ + st.equals(data, 'message 2'); + st.end(); + }); + }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -344,7 +357,7 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { - callback(null, 'puttest'); + callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test');
16
add update flag
3
.js
test
apache-2.0
dwyl/aws-sdk-mock
455
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); st.end(); }); }); t.test('method is re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); st.end(); }); }); t.test('service is re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); st.end(); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'puttest'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> add update flag <DFF> @@ -72,7 +72,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('method is re-mocked if a mock already exists', function(st){ + t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); @@ -85,7 +85,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('service is re-mocked if a mock already exists', function(st){ + t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); @@ -98,6 +98,19 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('service is re-mocked if update flag passed', function(st){ + awsMock.mock('SNS', 'subscribe', function(params, callback){ + callback(null, 'message 1'); + }); + var sns = new AWS.SNS(); + awsMock.mock('SNS', 'subscribe', function(params, callback){ + callback(null, 'message 2'); + }, true); + sns.subscribe({}, function(err, data){ + st.equals(data, 'message 2'); + st.end(); + }); + }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -344,7 +357,7 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { - callback(null, 'puttest'); + callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test');
16
add update flag
3
.js
test
apache-2.0
dwyl/aws-sdk-mock
456
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Update README.md Added example of S3.getObject() <DFF> @@ -53,12 +53,16 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); +// S3 getObject mock - return a Bffer object with file data +awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); + /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); +AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ```
4
Update README.md
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
457
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js AWS.mock('SNS', 'publish', 'test-message'); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); // or AWS.restore(); this will restore all the methods and services ``` AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either. Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Update README.md Added example of S3.getObject() <DFF> @@ -53,12 +53,16 @@ AWS.mock('DynamoDB', 'putItem', function (params, callback){ AWS.mock('SNS', 'publish', 'test-message'); +// S3 getObject mock - return a Bffer object with file data +awsMock.mock("S3", "getObject", new Buffer(require("fs").readFileSync("testFile.csv"))); + /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); +AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ```
4
Update README.md
0
.md
md
apache-2.0
dwyl/aws-sdk-mock
458
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Example: ```js var path = require('path'); var AWS = require('aws-sdk-mock'); var AWS_SDK = require('aws-sdk') exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> remove unnecessary line from a exmaple in README <DFF> @@ -173,7 +173,6 @@ Due to transpiling, code written in TypeScript or ES6 may not correctly mock bec Example: ```js -var path = require('path'); var AWS = require('aws-sdk-mock'); var AWS_SDK = require('aws-sdk')
0
remove unnecessary line from a exmaple in README
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
459
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` Example: ```js var path = require('path'); var AWS = require('aws-sdk-mock'); var AWS_SDK = require('aws-sdk') exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> remove unnecessary line from a exmaple in README <DFF> @@ -173,7 +173,6 @@ Due to transpiling, code written in TypeScript or ES6 may not correctly mock bec Example: ```js -var path = require('path'); var AWS = require('aws-sdk-mock'); var AWS_SDK = require('aws-sdk')
0
remove unnecessary line from a exmaple in README
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
460
<NME> .travis.yml <BEF> language: node_js node_js: - "12" - "8" - "10" - "12" before_install: - pip install --user codecov after_success: <MSG> Merge pull request #214 from abetomo/feature/add_nodejs14_to_ci_settings Add Node.js 14 to CI settings <DFF> @@ -4,6 +4,7 @@ node_js: - "8" - "10" - "12" + - "14" before_install: - pip install --user codecov after_success:
1
Merge pull request #214 from abetomo/feature/add_nodejs14_to_ci_settings
0
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
461
<NME> .travis.yml <BEF> language: node_js node_js: - "12" - "8" - "10" - "12" before_install: - pip install --user codecov after_success: <MSG> Merge pull request #214 from abetomo/feature/add_nodejs14_to_ci_settings Add Node.js 14 to CI settings <DFF> @@ -4,6 +4,7 @@ node_js: - "8" - "10" - "12" + - "14" before_install: - pip install --user codecov after_success:
1
Merge pull request #214 from abetomo/feature/add_nodejs14_to_ci_settings
0
.yml
travis
apache-2.0
dwyl/aws-sdk-mock
462
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); }) }); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #24 from jcready/patch-1 Add support for mocking AWS SDK's promises <DFF> @@ -82,6 +82,50 @@ test('AWS.mock function should mock AWS service and method on the service', func }) }); }); + if (typeof(Promise) === 'function') { + t.test('promises are supported', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.restore('Lambda', 'createFunction'); + var error = new Error('on purpose'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + callback(error, 'message'); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}).promise().then(function(data) { + st.equals(data, 'message'); + }).then(function(){ + return lambda.createFunction({}).promise() + }).catch(function(data){ + st.equals(data, error); + st.end(); + }); + }) + t.test('promises can be configured', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + var lambda = new AWS.Lambda(); + function P(handler) { + var self = this + function yay (value) { + self.value = value + } + handler(yay, function(){}) + } + P.prototype.then = function(yay) { if (this.value) yay(this.value) }; + AWS.config.setPromisesDependency(P) + var promise = lambda.getFunction({}).promise() + st.equals(promise.constructor.name, 'P') + promise.then(function(data) { + st.equals(data, 'message'); + st.end(); + }); + }) + } t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
44
Merge pull request #24 from jcready/patch-1
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
463
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); }) }); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #24 from jcready/patch-1 Add support for mocking AWS SDK's promises <DFF> @@ -82,6 +82,50 @@ test('AWS.mock function should mock AWS service and method on the service', func }) }); }); + if (typeof(Promise) === 'function') { + t.test('promises are supported', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.restore('Lambda', 'createFunction'); + var error = new Error('on purpose'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + callback(error, 'message'); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}).promise().then(function(data) { + st.equals(data, 'message'); + }).then(function(){ + return lambda.createFunction({}).promise() + }).catch(function(data){ + st.equals(data, error); + st.end(); + }); + }) + t.test('promises can be configured', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + callback(null, 'message'); + }); + var lambda = new AWS.Lambda(); + function P(handler) { + var self = this + function yay (value) { + self.value = value + } + handler(yay, function(){}) + } + P.prototype.then = function(yay) { if (this.value) yay(this.value) }; + AWS.config.setPromisesDependency(P) + var promise = lambda.getFunction({}).promise() + st.equals(promise.constructor.name, 'P') + promise.then(function(data) { + st.equals(data, 'message'); + st.end(); + }); + }) + } t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
44
Merge pull request #24 from jcready/patch-1
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
464
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { st.end(); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Restoring will not throw errors anymore <DFF> @@ -283,6 +283,13 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); t.end(); + t.test('Restore should not fail when the stub did not exist.', function (st) { + // This test will fail when restoring throws unneeded errors. + var stub = awsMock.mock('CloudSearchDomain', 'search'); + awsMock.restore('SES', 'sendEmail'); + awsMock.restore('CloudSearchDomain', 'doesnotexist'); + st.end(); + }); }); test('AWS.setSDK function should mock a specific AWS module', function(t) {
7
Restoring will not throw errors anymore
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
465
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { st.end(); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Restoring will not throw errors anymore <DFF> @@ -283,6 +283,13 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); t.end(); + t.test('Restore should not fail when the stub did not exist.', function (st) { + // This test will fail when restoring throws unneeded errors. + var stub = awsMock.mock('CloudSearchDomain', 'search'); + awsMock.restore('SES', 'sendEmail'); + awsMock.restore('CloudSearchDomain', 'doesnotexist'); + st.end(); + }); }); test('AWS.setSDK function should mock a specific AWS module', function(t) {
7
Restoring will not throw errors anymore
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
466
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); st.end(); }) }) // t.test('Unmocked method should work as normal', function(st) { // awsMock.mock('SNS', 'publish', 'message'); // var sns = new AWS.SNS(); // sns.subscribe({}, function (err, data) { // console.log(err); // console.log(data); // st.end(); // }); // }) t.end(); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Removes unecessary test <DFF> @@ -23,14 +23,5 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }) }) - // t.test('Unmocked method should work as normal', function(st) { - // awsMock.mock('SNS', 'publish', 'message'); - // var sns = new AWS.SNS(); - // sns.subscribe({}, function (err, data) { - // console.log(err); - // console.log(data); - // st.end(); - // }); - // }) t.end(); });
0
Removes unecessary test
9
.js
test
apache-2.0
dwyl/aws-sdk-mock
467
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); st.end(); }) }) // t.test('Unmocked method should work as normal', function(st) { // awsMock.mock('SNS', 'publish', 'message'); // var sns = new AWS.SNS(); // sns.subscribe({}, function (err, data) { // console.log(err); // console.log(data); // st.end(); // }); // }) t.end(); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Removes unecessary test <DFF> @@ -23,14 +23,5 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }) }) - // t.test('Unmocked method should work as normal', function(st) { - // awsMock.mock('SNS', 'publish', 'message'); - // var sns = new AWS.SNS(); - // sns.subscribe({}, function (err, data) { - // console.log(err); - // console.log(data); - // st.end(); - // }); - // }) t.end(); });
0
Removes unecessary test
9
.js
test
apache-2.0
dwyl/aws-sdk-mock
468
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); ### Configuring promises You'll need to explicitly enable promises on `aws-sdk-mock` if you use `promise()` functionality of the AWS SDK anywhere in your code. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Updated documentation for promises to be more accurate <DFF> @@ -169,7 +169,7 @@ AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); ### Configuring promises -You'll need to explicitly enable promises on `aws-sdk-mock` if you use `promise()` functionality of the AWS SDK anywhere in your code. Set the value of `AWS.Promise` to the constructor for your chosen promise library. +If your environment lacks a global Promise contstructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js
1
Updated documentation for promises to be more accurate
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
469
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` #### Using TypeScript ```typescript import AWSMock from 'aws-sdk-mock'; import AWS from 'aws-sdk'; import { GetItemInput } from 'aws-sdk/clients/dynamodb'; beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { console.log('DynamoDB', 'getItem', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }) const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { console.log('DynamoDB.DocumentClient', 'get', 'mock called'); callback(null, {pk: 'foo', sk: 'bar'}); }); const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` #### Sinon You can also pass Sinon spies to the mock: ```js const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` **NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked** e.g for an AWS Lambda function example 1 will cause an error `ConfigError: Missing region in config` whereas in example 2 the sdk will be successfully mocked. Example 1: ```js const AWS = require('aws-sdk'); const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish } ``` Example 2: ```js const AWS = require('aws-sdk'); exports.handler = function(event, context) { const sns = AWS.SNS(); ### Configuring promises You'll need to explicitly enable promises on `aws-sdk-mock` if you use `promise()` functionality of the AWS SDK anywhere in your code. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } ``` Example 2 (will work): ```js exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); // Not OK AWS.restore('DynamoDB.DocumentClient'); AWS.restore('DynamoDB'); ``` ### Don't worry about the constructor configuration Some constructors of the aws-sdk will require you to pass through a configuration object. ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> If configurations errors still occur it means you passed wrong configuration in your implementation. ### Setting the `aws-sdk` module explicitly Project structures that don't include the `aws-sdk` at the top level `node_modules` project folder will not be properly mocked. An example of this would be installing the `aws-sdk` in a nested project directory. You can get around this by explicitly setting the path to a nested `aws-sdk` module using `setSDK()`. Example: ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code const sqs = new AWS.SQS(); ``` ### Configuring promises If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Updated documentation for promises to be more accurate <DFF> @@ -169,7 +169,7 @@ AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); ### Configuring promises -You'll need to explicitly enable promises on `aws-sdk-mock` if you use `promise()` functionality of the AWS SDK anywhere in your code. Set the value of `AWS.Promise` to the constructor for your chosen promise library. +If your environment lacks a global Promise contstructor (e.g. nodejs 0.10), you can explicitly set the promises on `aws-sdk-mock`. Set the value of `AWS.Promise` to the constructor for your chosen promise library. Example (if Q is your promise library of choice): ```js
1
Updated documentation for promises to be more accurate
1
.md
md
apache-2.0
dwyl/aws-sdk-mock
470
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.is(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> fix: resolve `DeprecationWarning` The following warning was displayed and will be resolved. ``` ./test/index.test.js 2> (node:32243) DeprecationWarning: is() is deprecated, use equal() instead ``` <DFF> @@ -466,7 +466,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ - st.is(err, null); + st.equal(err, null); st.equal(data, 'test'); st.end(); });
1
fix: resolve `DeprecationWarning`
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
471
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.is(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> fix: resolve `DeprecationWarning` The following warning was displayed and will be resolved. ``` ./test/index.test.js 2> (node:32243) DeprecationWarning: is() is deprecated, use equal() instead ``` <DFF> @@ -466,7 +466,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ - st.is(err, null); + st.equal(err, null); st.equal(data, 'test'); st.end(); });
1
fix: resolve `DeprecationWarning`
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
472
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { } }; var request = { promise: (typeof(AWS.Promise) === 'function') ? function() { if (!promise) { promise = new Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> fix: tidy up Promise code <DFF> @@ -127,9 +127,9 @@ function mockServiceMethod(service, client, method, replace) { } }; var request = { - promise: (typeof(AWS.Promise) === 'function') ? function() { + promise: havePromises ? function() { if (!promise) { - promise = new Promise(function (resolve_, reject_) { + promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; });
2
fix: tidy up Promise code
2
.js
js
apache-2.0
dwyl/aws-sdk-mock
473
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { } }; var request = { promise: (typeof(AWS.Promise) === 'function') ? function() { if (!promise) { promise = new Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { userArgs = args.slice(0, -1); userCallback = args[(args.length || 1) - 1]; } else { userArgs = args; } const havePromises = typeof AWS.Promise === 'function'; let promise, resolve, reject, storedResult; const tryResolveFromStored = function() { if (storedResult && promise) { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (storedResult instanceof Readable) { return storedResult; } if (replace instanceof Readable) { return replace; } else { const stream = new Readable(); stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> fix: tidy up Promise code <DFF> @@ -127,9 +127,9 @@ function mockServiceMethod(service, client, method, replace) { } }; var request = { - promise: (typeof(AWS.Promise) === 'function') ? function() { + promise: havePromises ? function() { if (!promise) { - promise = new Promise(function (resolve_, reject_) { + promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; });
2
fix: tidy up Promise code
2
.js
js
apache-2.0
dwyl/aws-sdk-mock
474
<NME> index.test.js <BEF> var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); AWS.config.paramValidation = false; test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }); }); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }); }); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { }); s3.upload({}, {test: 'message'}, function(err, data) { st.equals(data.test, 'message'); awsMock.restore('S3'); st.end(); }); }); st.end(); }); }); }); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); awsMock.restore('S3', 'getObject'); st.end(); }); }); st.end(); }); var s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equals(data, 'message'); awsMock.restore('S3'); st.end(); }); }); st.end(); }); }); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equals(data.Body, 'body'); awsMock.restore('S3', 'getObject'); st.end(); }); }); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }); }); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); }); }); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); if (typeof(Promise) === 'function') { t.test('promises are supported', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('replacement returns thennable', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.end(); }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { }); }); t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ req = s3.getObject('getObject'); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject'); st.end(); })); }); AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); }); awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); }); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); }); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ docClient.query({}, function(err, data){ console.warn(err); st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); }); }); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); }); st.end(); }); t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); st.end(); }); t.end(); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); } catch (e) { console.log(e); } }); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { st.end(); }); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); awsMock.restore(); st.end(); }); t.end(); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message2'); awsMock.restore('SNS'); st.end(); }); }); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); awsMock.restore(); st.end(); }); t.end(); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> support passing a Readable stream as the stub for S3.GetObject - swapped tape with tap to get afterEach, so that the sandbox can be predictably restored after each test. - removed all restore calls that do not test restore feature - skipped the test about a stub being returned because that behavior only applies when the service constructor has already been called when mock is called. the test previously passed due to side effects of unrestored sandbox. <DFF> @@ -1,18 +1,24 @@ -var test = require('tape'); +var tap = require('tap'); +var test = tap.test; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); +var Readable = require('stream').Readable; AWS.config.paramValidation = false; +tap.afterEach(function (done) { + awsMock.restore(); + done(); +}); + test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); - awsMock.restore('SNS'); st.end(); }); }); @@ -23,7 +29,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); - awsMock.restore('SNS'); st.end(); }); }); @@ -37,7 +42,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); s3.upload({}, {test: 'message'}, function(err, data) { st.equals(data.test, 'message'); - awsMock.restore('S3'); st.end(); }); }); @@ -48,7 +52,6 @@ test('AWS.mock function should mock AWS service and method on the service', func s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); - awsMock.restore('S3', 'getObject'); st.end(); }); }); @@ -57,7 +60,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equals(data, 'message'); - awsMock.restore('S3'); st.end(); }); }); @@ -67,7 +69,6 @@ test('AWS.mock function should mock AWS service and method on the service', func s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equals(data.Body, 'body'); - awsMock.restore('S3', 'getObject'); st.end(); }); }); @@ -81,7 +82,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); sns.publish({}, function(err, data){ st.equals(data, 'message'); - awsMock.restore('SNS'); st.end(); }); }); @@ -95,7 +95,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); - awsMock.restore('SNS'); st.end(); }); }); @@ -117,8 +116,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); if (typeof(Promise) === 'function') { t.test('promises are supported', function(st){ - awsMock.restore('Lambda', 'getFunction'); - awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -137,8 +134,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); t.test('replacement returns thennable', function(st){ - awsMock.restore('Lambda', 'getFunction'); - awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') @@ -169,8 +164,6 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); t.test('promises work with async completion', function(st){ - awsMock.restore('Lambda', 'getFunction'); - awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); @@ -189,7 +182,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); t.test('promises can be configured', function(st){ - awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); @@ -224,7 +216,17 @@ test('AWS.mock function should mock AWS service and method on the service', func req = s3.getObject('getObject'); var stream = req.createReadStream(); stream.pipe(concatStream(function() { - awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream works with streams', function(st) { + var bodyStream = new Readable(); + bodyStream.push('body'); + bodyStream.push(null); + awsMock.mock('S3', 'getObject', bodyStream); + var stream = new AWS.S3().getObject('getObject').createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), 'body'); st.end(); })); }); @@ -235,7 +237,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body'); - awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -246,7 +247,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body'); - awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -257,7 +257,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), ''); - awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -268,7 +267,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), ''); - awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -383,7 +381,6 @@ test('AWS.mock function should mock AWS service and method on the service', func docClient.query({}, function(err, data){ console.warn(err); st.equals(data, 'test'); - awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); }); }); @@ -451,12 +448,12 @@ test('AWS.mock function should mock AWS service and method on the service', func }); st.end(); }); - t.test('Mocked service should return the sinon stub', function(st) { + t.skip('Mocked service should return the sinon stub', function(st) { + // TODO: the stub is only returned if an instance was already constructed var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); st.end(); }); - t.end(); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { @@ -466,8 +463,8 @@ test('AWS.mock function should mock AWS service and method on the service', func } catch (e) { console.log(e); } - }); + t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { @@ -477,7 +474,6 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); - awsMock.restore('SNS'); st.end(); }); }); @@ -488,8 +484,6 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); - awsMock.restore(); - st.end(); }); t.end(); @@ -503,7 +497,6 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message2'); - awsMock.restore('SNS'); st.end(); }); }); @@ -515,7 +508,6 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); - awsMock.restore(); st.end(); }); t.end();
22
support passing a Readable stream as the stub for S3.GetObject
30
.js
test
apache-2.0
dwyl/aws-sdk-mock
475
<NME> index.test.js <BEF> var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); AWS.config.paramValidation = false; test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }); }); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }); }); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { }); s3.upload({}, {test: 'message'}, function(err, data) { st.equals(data.test, 'message'); awsMock.restore('S3'); st.end(); }); }); st.end(); }); }); }); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); awsMock.restore('S3', 'getObject'); st.end(); }); }); st.end(); }); var s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equals(data, 'message'); awsMock.restore('S3'); st.end(); }); }); st.end(); }); }); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equals(data.Body, 'body'); awsMock.restore('S3', 'getObject'); st.end(); }); }); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }); }); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); awsMock.restore('SNS'); st.end(); }); }); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); if (typeof(Promise) === 'function') { t.test('promises are supported', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('replacement returns thennable', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.end(); }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { }); }); t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ req = s3.getObject('getObject'); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject'); st.end(); })); }); AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); }); awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body'); awsMock.restore('S3', 'getObject'); st.end(); })); }); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), ''); awsMock.restore('S3', 'getObject'); st.end(); })); }); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ docClient.query({}, function(err, data){ console.warn(err); st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); }); }); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); }); st.end(); }); t.test('Mocked service should return the sinon stub', function(st) { var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); st.end(); }); t.end(); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); } catch (e) { console.log(e); } }); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { st.end(); }); }); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); awsMock.restore('SNS'); st.end(); }); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); awsMock.restore(); st.end(); }); t.end(); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message2'); awsMock.restore('SNS'); st.end(); }); }); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); awsMock.restore(); st.end(); }); t.end(); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> support passing a Readable stream as the stub for S3.GetObject - swapped tape with tap to get afterEach, so that the sandbox can be predictably restored after each test. - removed all restore calls that do not test restore feature - skipped the test about a stub being returned because that behavior only applies when the service constructor has already been called when mock is called. the test previously passed due to side effects of unrestored sandbox. <DFF> @@ -1,18 +1,24 @@ -var test = require('tape'); +var tap = require('tap'); +var test = tap.test; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var concatStream = require('concat-stream'); +var Readable = require('stream').Readable; AWS.config.paramValidation = false; +tap.afterEach(function (done) { + awsMock.restore(); + done(); +}); + test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); - awsMock.restore('SNS'); st.end(); }); }); @@ -23,7 +29,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); - awsMock.restore('SNS'); st.end(); }); }); @@ -37,7 +42,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); s3.upload({}, {test: 'message'}, function(err, data) { st.equals(data.test, 'message'); - awsMock.restore('S3'); st.end(); }); }); @@ -48,7 +52,6 @@ test('AWS.mock function should mock AWS service and method on the service', func s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); - awsMock.restore('S3', 'getObject'); st.end(); }); }); @@ -57,7 +60,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equals(data, 'message'); - awsMock.restore('S3'); st.end(); }); }); @@ -67,7 +69,6 @@ test('AWS.mock function should mock AWS service and method on the service', func s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equals(data.Body, 'body'); - awsMock.restore('S3', 'getObject'); st.end(); }); }); @@ -81,7 +82,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); sns.publish({}, function(err, data){ st.equals(data, 'message'); - awsMock.restore('SNS'); st.end(); }); }); @@ -95,7 +95,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); sns.subscribe({}, function(err, data){ st.equals(data, 'test'); - awsMock.restore('SNS'); st.end(); }); }); @@ -117,8 +116,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); if (typeof(Promise) === 'function') { t.test('promises are supported', function(st){ - awsMock.restore('Lambda', 'getFunction'); - awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); @@ -137,8 +134,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); t.test('replacement returns thennable', function(st){ - awsMock.restore('Lambda', 'getFunction'); - awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') @@ -169,8 +164,6 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); t.test('promises work with async completion', function(st){ - awsMock.restore('Lambda', 'getFunction'); - awsMock.restore('Lambda', 'createFunction'); var error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); @@ -189,7 +182,6 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }); t.test('promises can be configured', function(st){ - awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); @@ -224,7 +216,17 @@ test('AWS.mock function should mock AWS service and method on the service', func req = s3.getObject('getObject'); var stream = req.createReadStream(); stream.pipe(concatStream(function() { - awsMock.restore('S3', 'getObject'); + st.end(); + })); + }); + t.test('request object createReadStream works with streams', function(st) { + var bodyStream = new Readable(); + bodyStream.push('body'); + bodyStream.push(null); + awsMock.mock('S3', 'getObject', bodyStream); + var stream = new AWS.S3().getObject('getObject').createReadStream(); + stream.pipe(concatStream(function(actual) { + st.equals(actual.toString(), 'body'); st.end(); })); }); @@ -235,7 +237,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body'); - awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -246,7 +247,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), 'body'); - awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -257,7 +257,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), ''); - awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -268,7 +267,6 @@ test('AWS.mock function should mock AWS service and method on the service', func var stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equals(actual.toString(), ''); - awsMock.restore('S3', 'getObject'); st.end(); })); }); @@ -383,7 +381,6 @@ test('AWS.mock function should mock AWS service and method on the service', func docClient.query({}, function(err, data){ console.warn(err); st.equals(data, 'test'); - awsMock.restore('DynamoDB.DocumentClient', 'query'); st.end(); }); }); @@ -451,12 +448,12 @@ test('AWS.mock function should mock AWS service and method on the service', func }); st.end(); }); - t.test('Mocked service should return the sinon stub', function(st) { + t.skip('Mocked service should return the sinon stub', function(st) { + // TODO: the stub is only returned if an instance was already constructed var stub = awsMock.mock('CloudSearchDomain', 'search'); st.equals(stub.stub.isSinonProxy, true); st.end(); }); - t.end(); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { @@ -466,8 +463,8 @@ test('AWS.mock function should mock AWS service and method on the service', func } catch (e) { console.log(e); } - }); + t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { @@ -477,7 +474,6 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message'); - awsMock.restore('SNS'); st.end(); }); }); @@ -488,8 +484,6 @@ test('AWS.setSDK function should mock a specific AWS module', function(t) { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); - awsMock.restore(); - st.end(); }); t.end(); @@ -503,7 +497,6 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t var sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equals(data, 'message2'); - awsMock.restore('SNS'); st.end(); }); }); @@ -515,7 +508,6 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); - awsMock.restore(); st.end(); }); t.end();
22
support passing a Readable stream as the stub for S3.GetObject
30
.js
test
apache-2.0
dwyl/aws-sdk-mock
476
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js var AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` ```typescript import * as AWSMock from "aws-sdk-mock"; import * as AWS from "aws-sdk"; import { GetItemInput } from "aws-sdk/clients/dynamodb"; beforeAll(async (done) => { beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { callback(null, {pk: "foo", sk: "bar"}); }) let input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { callback(null, {pk: "foo", sk: "bar"}); }) let input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` You can also pass Sinon spies to the mock: ```js var updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); var expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` Example 1: ```js var AWS = require('aws-sdk'); var sns = AWS.SNS(); var dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish exports.handler = function(event, context) { Example 2: ```js var AWS = require('aws-sdk'); exports.handler = function(event, context) { var sns = AWS.SNS(); var dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` ```js exports.handler = function(event, context) { someAsyncFunction(() => { var sns = AWS.SNS(); var dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); Example 2 (will work): ```js exports.handler = function(event, context) { var sns = AWS.SNS(); var dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); Some constructors of the aws-sdk will require you to pass through a configuration object. ```js var csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> Example: ```js var path = require('path'); var AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code Example (if Q is your promise library of choice): ```js var AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Updated README code example Replace `var` with `const`. Relation: https://github.com/dwyl/aws-sdk-mock/pull/208 <DFF> @@ -49,7 +49,7 @@ npm install aws-sdk-mock --save-dev #### Using plain JavaScript ```js -var AWS = require('aws-sdk-mock'); +const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); @@ -75,7 +75,7 @@ AWS.restore('S3'); ```typescript import * as AWSMock from "aws-sdk-mock"; -import * as AWS from "aws-sdk"; +import * as AWS from "aws-sdk"; import { GetItemInput } from "aws-sdk/clients/dynamodb"; beforeAll(async (done) => { @@ -97,7 +97,7 @@ describe("the module", () => { callback(null, {pk: "foo", sk: "bar"}); }) - let input:GetItemInput = { TableName: '', Key: {} }; + const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); @@ -112,7 +112,7 @@ describe("the module", () => { callback(null, {pk: "foo", sk: "bar"}); }) - let input:GetItemInput = { TableName: '', Key: {} }; + const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); @@ -125,7 +125,7 @@ describe("the module", () => { You can also pass Sinon spies to the mock: ```js -var updateTableSpy = sinon.spy(); +const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test @@ -133,7 +133,7 @@ myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); -var expectedParams = { +const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, @@ -147,9 +147,9 @@ assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct pa Example 1: ```js -var AWS = require('aws-sdk'); -var sns = AWS.SNS(); -var dynamoDb = AWS.DynamoDB(); +const AWS = require('aws-sdk'); +const sns = AWS.SNS(); +const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish @@ -158,11 +158,11 @@ exports.handler = function(event, context) { Example 2: ```js -var AWS = require('aws-sdk'); +const AWS = require('aws-sdk'); exports.handler = function(event, context) { - var sns = AWS.SNS(); - var dynamoDb = AWS.DynamoDB(); + const sns = AWS.SNS(); + const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` @@ -173,8 +173,8 @@ Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { - var sns = AWS.SNS(); - var dynamoDb = AWS.DynamoDB(); + const sns = AWS.SNS(); + const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } @@ -183,8 +183,8 @@ exports.handler = function(event, context) { Example 2 (will work): ```js exports.handler = function(event, context) { - var sns = AWS.SNS(); - var dynamoDb = AWS.DynamoDB(); + const sns = AWS.SNS(); + const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); @@ -223,7 +223,7 @@ AWS.restore('DynamoDB'); Some constructors of the aws-sdk will require you to pass through a configuration object. ```js -var csd = new AWS.CloudSearchDomain({ +const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); @@ -241,8 +241,8 @@ Project structures that don't include the `aws-sdk` at the top level `node_modul Example: ```js -var path = require('path'); -var AWS = require('aws-sdk-mock'); +const path = require('path'); +const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); @@ -274,7 +274,7 @@ If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you c Example (if Q is your promise library of choice): ```js -var AWS = require('aws-sdk-mock'), +const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise;
20
Updated README code example
20
.md
md
apache-2.0
dwyl/aws-sdk-mock
477
<NME> README.md <BEF> # aws-sdk-mock AWSome mocks for Javascript aws-sdk services. [![Build Status](https://img.shields.io/travis/dwyl/aws-sdk-mock/master.svg?style=flat-square)](https://travis-ci.org/dwyl/aws-sdk-mock) [![codecov.io](https://img.shields.io/codecov/c/github/dwyl/aws-sdk-mock/master.svg?style=flat-square)](http://codecov.io/github/dwyl/aws-sdk-mock?branch=master) [![Dependency Status](https://david-dm.org/dwyl/aws-sdk-mock.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock) [![devDependency Status](https://david-dm.org/dwyl/aws-sdk-mock/dev-status.svg?style=flat-square)](https://david-dm.org/dwyl/aws-sdk-mock#info=devDependencies) [![Known Vulnerabilities](https://snyk.io/test/github/dwyl/aws-sdk-mock/badge.svg?targetFile=package.json&style=flat-square)](https://snyk.io/test/github/dwyl/aws-sdk-mock?targetFile=package.json) <!-- broken see: https://github.com/dwyl/aws-sdk-mock/issues/161#issuecomment-444181270 [![NPM](https://nodei.co/npm-dl/aws-sdk-mock.png?months=3)](https://nodei.co/npm/aws-sdk-mock/) --> This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked. If you are *new* to Amazon WebServices Lambda (*or need a refresher*), please checkout our our ***Beginners Guide to AWS Lambda***: <https://github.com/dwyl/learn-aws-lambda> * [Why](#why) * [What](#what) * [Getting Started](#how) * [Documentation](#documentation) * [Background Reading](#background-reading) ## Why? Testing your code is *essential* everywhere you need *reliability*. Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK. ## What? Uses [Sinon.js](https://sinonjs.org/) under the hood to mock the AWS SDK services and their associated methods. ## *How*? (*Usage*) ### *install* `aws-sdk-mock` from NPM ```sh npm install aws-sdk-mock --save-dev ``` ### Use in your Tests #### Using plain JavaScript ```js var AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); callback(null, 'successfully put item in database'); }); AWS.mock('SNS', 'publish', 'test-message'); // S3 getObject mock - return a Buffer object with file data AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); /** TESTS **/ AWS.restore('SNS', 'publish'); AWS.restore('DynamoDB'); AWS.restore('S3'); // or AWS.restore(); this will restore all the methods and services ``` ```typescript import * as AWSMock from "aws-sdk-mock"; import * as AWS from "aws-sdk"; import { GetItemInput } from "aws-sdk/clients/dynamodb"; beforeAll(async (done) => { beforeAll(async (done) => { //get requires env vars done(); }); describe('the module', () => { /** TESTS below here **/ it('should mock getItem from DynamoDB', async () => { // Overwriting DynamoDB.getItem() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { callback(null, {pk: "foo", sk: "bar"}); }) let input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB'); }); it('should mock reading from DocumentClient', async () => { // Overwriting DynamoDB.DocumentClient.get() AWSMock.setSDKInstance(AWS); AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { callback(null, {pk: "foo", sk: "bar"}); }) let input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); AWSMock.restore('DynamoDB.DocumentClient'); }); }); ``` You can also pass Sinon spies to the mock: ```js var updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); var expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1 } }; assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters'); ``` Example 1: ```js var AWS = require('aws-sdk'); var sns = AWS.SNS(); var dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish exports.handler = function(event, context) { Example 2: ```js var AWS = require('aws-sdk'); exports.handler = function(event, context) { var sns = AWS.SNS(); var dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` ```js exports.handler = function(event, context) { someAsyncFunction(() => { var sns = AWS.SNS(); var dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); Example 2 (will work): ```js exports.handler = function(event, context) { var sns = AWS.SNS(); var dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); exports.handler = function(event, context) { const sns = AWS.SNS(); const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); } ``` ### Nested services It is possible to mock nested services like `DynamoDB.DocumentClient`. Simply use this dot-notation name as the `service` parameter to the `mock()` and `restore()` methods: ```js AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, {Item: {Key: 'Value'}}); }); ``` **NB: Use caution when mocking both a nested service and its parent service.** The nested service should be mocked before and restored after its parent: ```js // OK AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.restore('DynamoDB'); AWS.restore('DynamoDB.DocumentClient'); // Not OK AWS.mock('DynamoDB', 'describeTable', 'message'); AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); Some constructors of the aws-sdk will require you to pass through a configuration object. ```js var csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ```js const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); ``` Most mocking solutions with throw an `InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option` when you try to mock this. **aws-sdk-mock** will take care of this during mock creation so you **won't get any configuration errors**!<br> Example: ```js var path = require('path'); var AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); ```js const path = require('path'); const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); /** TESTS **/ ``` ### Setting the `aws-sdk` object explicitly Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the `aws-sdk` object created within `aws-sdk-mock` will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using `setSDKInstance()`. Example: ```js // test code const AWSMock = require('aws-sdk-mock'); import AWS from 'aws-sdk'; AWSMock.setSDKInstance(AWS); AWSMock.mock('SQS', /* ... */); // implementation code Example (if Q is your promise library of choice): ```js var AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; Example (if Q is your promise library of choice): ```js const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise; /** TESTS **/ ``` ## Documentation ### `AWS.mock(service, method, replace)` Replaces a method on an AWS service with a replacement function or string. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.restore(service, method)` Removes the mock to restore the specified AWS service | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Optional | AWS service to restore - If only the service is specified, all the methods are restored | | `method` | string | Optional | Method on AWS service to restore | If `AWS.restore` is called without arguments (`AWS.restore()`) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function. ### `AWS.remock(service, method, replace)` Updates the `replace` method on an existing mocked service. | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `service` | string | Required | AWS service to mock e.g. SNS, DynamoDB, S3 | | `method` | string | Required | method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB' | | `replace` | string or function | Required | A string or function to replace the method | ### `AWS.setSDK(path)` Explicitly set the require path for the `aws-sdk` | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `path` | string | Required | Path to a nested AWS SDK node module | ### `AWS.setSDKInstance(sdk)` Explicitly set the `aws-sdk` instance to use | Param | Type | Optional/Required | Description | | :------------- | :------------- | :------------- | :------------- | | `sdk` | object | Required | The AWS SDK object | ## Background Reading * [Mocking using Sinon.js](http://sinonjs.org/docs/) * [AWS Lambda](https://github.com/dwyl/learn-aws-lambda) **Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving** <MSG> Updated README code example Replace `var` with `const`. Relation: https://github.com/dwyl/aws-sdk-mock/pull/208 <DFF> @@ -49,7 +49,7 @@ npm install aws-sdk-mock --save-dev #### Using plain JavaScript ```js -var AWS = require('aws-sdk-mock'); +const AWS = require('aws-sdk-mock'); AWS.mock('DynamoDB', 'putItem', function (params, callback){ callback(null, "successfully put item in database"); @@ -75,7 +75,7 @@ AWS.restore('S3'); ```typescript import * as AWSMock from "aws-sdk-mock"; -import * as AWS from "aws-sdk"; +import * as AWS from "aws-sdk"; import { GetItemInput } from "aws-sdk/clients/dynamodb"; beforeAll(async (done) => { @@ -97,7 +97,7 @@ describe("the module", () => { callback(null, {pk: "foo", sk: "bar"}); }) - let input:GetItemInput = { TableName: '', Key: {} }; + const input:GetItemInput = { TableName: '', Key: {} }; const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); expect(await dynamodb.getItem(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); @@ -112,7 +112,7 @@ describe("the module", () => { callback(null, {pk: "foo", sk: "bar"}); }) - let input:GetItemInput = { TableName: '', Key: {} }; + const input:GetItemInput = { TableName: '', Key: {} }; const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); expect(await client.get(input).promise()).toStrictEqual( { pk: 'foo', sk: 'bar' }); @@ -125,7 +125,7 @@ describe("the module", () => { You can also pass Sinon spies to the mock: ```js -var updateTableSpy = sinon.spy(); +const updateTableSpy = sinon.spy(); AWS.mock('DynamoDB', 'updateTable', updateTableSpy); // Object under test @@ -133,7 +133,7 @@ myDynamoManager.scaleDownTable(); // Assert on your Sinon spy as normal assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK'); -var expectedParams = { +const expectedParams = { TableName: 'testTableName', ProvisionedThroughput: { ReadCapacityUnits: 1, @@ -147,9 +147,9 @@ assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct pa Example 1: ```js -var AWS = require('aws-sdk'); -var sns = AWS.SNS(); -var dynamoDb = AWS.DynamoDB(); +const AWS = require('aws-sdk'); +const sns = AWS.SNS(); +const dynamoDb = AWS.DynamoDB(); exports.handler = function(event, context) { // do something with the services e.g. sns.publish @@ -158,11 +158,11 @@ exports.handler = function(event, context) { Example 2: ```js -var AWS = require('aws-sdk'); +const AWS = require('aws-sdk'); exports.handler = function(event, context) { - var sns = AWS.SNS(); - var dynamoDb = AWS.DynamoDB(); + const sns = AWS.SNS(); + const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish } ``` @@ -173,8 +173,8 @@ Example 1 (won't work): ```js exports.handler = function(event, context) { someAsyncFunction(() => { - var sns = AWS.SNS(); - var dynamoDb = AWS.DynamoDB(); + const sns = AWS.SNS(); + const dynamoDb = AWS.DynamoDB(); // do something with the services e.g. sns.publish }); } @@ -183,8 +183,8 @@ exports.handler = function(event, context) { Example 2 (will work): ```js exports.handler = function(event, context) { - var sns = AWS.SNS(); - var dynamoDb = AWS.DynamoDB(); + const sns = AWS.SNS(); + const dynamoDb = AWS.DynamoDB(); someAsyncFunction(() => { // do something with the services e.g. sns.publish }); @@ -223,7 +223,7 @@ AWS.restore('DynamoDB'); Some constructors of the aws-sdk will require you to pass through a configuration object. ```js -var csd = new AWS.CloudSearchDomain({ +const csd = new AWS.CloudSearchDomain({ endpoint: 'your.end.point', region: 'eu-west' }); @@ -241,8 +241,8 @@ Project structures that don't include the `aws-sdk` at the top level `node_modul Example: ```js -var path = require('path'); -var AWS = require('aws-sdk-mock'); +const path = require('path'); +const AWS = require('aws-sdk-mock'); AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk')); @@ -274,7 +274,7 @@ If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you c Example (if Q is your promise library of choice): ```js -var AWS = require('aws-sdk-mock'), +const AWS = require('aws-sdk-mock'), Q = require('q'); AWS.Promise = Q.Promise;
20
Updated README code example
20
.md
md
apache-2.0
dwyl/aws-sdk-mock
478
<NME> index.test.js <BEF> 'use strict'; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var streamToArray = require('stream-to-array'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { // let's just consume it and ignore the contents req = s3.getObject('getObject', {}); var stream = req.createReadStream(); streamToArray(stream, function() { st.end(); }); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> test: use concat-stream instead of stream-to-array, support older node <DFF> @@ -2,7 +2,7 @@ var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); -var streamToArray = require('stream-to-array'); +var concatStream = require('concat-stream'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ @@ -160,9 +160,9 @@ test('AWS.mock function should mock AWS service and method on the service', func // let's just consume it and ignore the contents req = s3.getObject('getObject', {}); var stream = req.createReadStream(); - streamToArray(stream, function() { + stream.pipe(concatStream(function() { st.end(); - }); + })); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){
3
test: use concat-stream instead of stream-to-array, support older node
3
.js
test
apache-2.0
dwyl/aws-sdk-mock
479
<NME> index.test.js <BEF> 'use strict'; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); var streamToArray = require('stream-to-array'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { // let's just consume it and ignore the contents req = s3.getObject('getObject', {}); var stream = req.createReadStream(); streamToArray(stream, function() { st.end(); }); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> test: use concat-stream instead of stream-to-array, support older node <DFF> @@ -2,7 +2,7 @@ var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); -var streamToArray = require('stream-to-array'); +var concatStream = require('concat-stream'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ @@ -160,9 +160,9 @@ test('AWS.mock function should mock AWS service and method on the service', func // let's just consume it and ignore the contents req = s3.getObject('getObject', {}); var stream = req.createReadStream(); - streamToArray(stream, function() { + stream.pipe(concatStream(function() { st.end(); - }); + })); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){
3
test: use concat-stream instead of stream-to-array, support older node
3
.js
test
apache-2.0
dwyl/aws-sdk-mock
480
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); st.end(); }); }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); var s3 = new AWS.S3(); var req = s3.getObject('getObject', {}, function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject', {}); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject'); setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); }); t.end(); }); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #63 from juristat-oss/unhandled-rejections fix: unhandled promise rejections when using callbacks <DFF> @@ -136,6 +136,18 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('no unhandled promise rejections when promises are not used', function(st) { + process.on('unhandledRejection', function(reason, promise) { + st.fail('unhandledRejection, reason follows'); + st.error(reason); + }); + awsMock.mock('S3', 'getObject', function(params, callback) { + callback('This is a test error to see if promise rejections go unhandled'); + }); + var S3 = new AWS.S3(); + S3.getObject({}, function(err, data) {}); + st.end(); + }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); @@ -182,14 +194,14 @@ test('AWS.mock function should mock AWS service and method on the service', func t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); var s3 = new AWS.S3(); - var req = s3.getObject('getObject', {}, function(err, data) {}); + var req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback - req = s3.getObject('getObject', {}); + req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents - req = s3.getObject('getObject', {}); + req = s3.getObject('getObject'); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject'); @@ -476,4 +488,3 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t }); t.end(); }); -
15
Merge pull request #63 from juristat-oss/unhandled-rejections
4
.js
test
apache-2.0
dwyl/aws-sdk-mock
481
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); st.end(); }); }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); var s3 = new AWS.S3(); var req = s3.getObject('getObject', {}, function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject', {}); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject'); setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); }); t.end(); }); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #63 from juristat-oss/unhandled-rejections fix: unhandled promise rejections when using callbacks <DFF> @@ -136,6 +136,18 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); + t.test('no unhandled promise rejections when promises are not used', function(st) { + process.on('unhandledRejection', function(reason, promise) { + st.fail('unhandledRejection, reason follows'); + st.error(reason); + }); + awsMock.mock('S3', 'getObject', function(params, callback) { + callback('This is a test error to see if promise rejections go unhandled'); + }); + var S3 = new AWS.S3(); + S3.getObject({}, function(err, data) {}); + st.end(); + }); t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); @@ -182,14 +194,14 @@ test('AWS.mock function should mock AWS service and method on the service', func t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); var s3 = new AWS.S3(); - var req = s3.getObject('getObject', {}, function(err, data) {}); + var req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback - req = s3.getObject('getObject', {}); + req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents - req = s3.getObject('getObject', {}); + req = s3.getObject('getObject'); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject'); @@ -476,4 +488,3 @@ test('AWS.setSDKInstance function should mock a specific AWS module', function(t }); t.end(); }); -
15
Merge pull request #63 from juristat-oss/unhandled-rejections
4
.js
test
apache-2.0
dwyl/aws-sdk-mock
482
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.end(); }); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #13 from boyarskiy/fix added config parameter for requires AWS configurations <DFF> @@ -116,5 +116,17 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) + t.test('should mock services with required configurations', function(st){ + awsMock.mock('CloudSearchDomain', 'search', 'searchString', { + endpoint: 'mockEndpoint' + }); + var csd = new AWS.CloudSearchDomain(); + + csd.search({}, function (err, data) { + st.equals(data, 'searchString'); + awsMock.restore('CloudSearchDomain'); + st.end(); + }); + }) t.end(); });
12
Merge pull request #13 from boyarskiy/fix
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
483
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) t.end(); }); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Merge pull request #13 from boyarskiy/fix added config parameter for requires AWS configurations <DFF> @@ -116,5 +116,17 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }) + t.test('should mock services with required configurations', function(st){ + awsMock.mock('CloudSearchDomain', 'search', 'searchString', { + endpoint: 'mockEndpoint' + }); + var csd = new AWS.CloudSearchDomain(); + + csd.search({}, function (err, data) { + st.equals(data, 'searchString'); + awsMock.restore('CloudSearchDomain'); + st.end(); + }); + }) t.end(); });
12
Merge pull request #13 from boyarskiy/fix
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
484
<NME> index.test.js <BEF> 'use strict'; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ st.end(); }); }) t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); // with or without callback req = s3.getObject('getObject', {}); st.ok(isNodeStream(req.createReadStream())); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> test: cover createReadStream and refactored Promise code <DFF> @@ -2,6 +2,7 @@ var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); +var streamToArray = require('stream-to-array'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ @@ -104,6 +105,26 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }) + t.test('promises work with async completion', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.restore('Lambda', 'createFunction'); + var error = new Error('on purpose'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + setTimeout(callback.bind(this, null, 'message'), 10); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + setTimeout(callback.bind(this, error, 'message'), 10); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}).promise().then(function(data) { + st.equals(data, 'message'); + }).then(function(){ + return lambda.createFunction({}).promise() + }).catch(function(data){ + st.equals(data, error); + st.end(); + }); + }) t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { @@ -135,7 +156,13 @@ test('AWS.mock function should mock AWS service and method on the service', func // with or without callback req = s3.getObject('getObject', {}); st.ok(isNodeStream(req.createReadStream())); - st.end(); + // stream is currently always empty but that's subject to change. + // let's just consume it and ignore the contents + req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + streamToArray(stream, function() { + st.end(); + }); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){
28
test: cover createReadStream and refactored Promise code
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
485
<NME> index.test.js <BEF> 'use strict'; var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ st.end(); }); }) t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); // with or without callback req = s3.getObject('getObject', {}); st.ok(isNodeStream(req.createReadStream())); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> test: cover createReadStream and refactored Promise code <DFF> @@ -2,6 +2,7 @@ var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); var isNodeStream = require('is-node-stream'); +var streamToArray = require('stream-to-array'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ @@ -104,6 +105,26 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }) + t.test('promises work with async completion', function(st){ + awsMock.restore('Lambda', 'getFunction'); + awsMock.restore('Lambda', 'createFunction'); + var error = new Error('on purpose'); + awsMock.mock('Lambda', 'getFunction', function(params, callback) { + setTimeout(callback.bind(this, null, 'message'), 10); + }); + awsMock.mock('Lambda', 'createFunction', function(params, callback) { + setTimeout(callback.bind(this, error, 'message'), 10); + }); + var lambda = new AWS.Lambda(); + lambda.getFunction({}).promise().then(function(data) { + st.equals(data, 'message'); + }).then(function(){ + return lambda.createFunction({}).promise() + }).catch(function(data){ + st.equals(data, error); + st.end(); + }); + }) t.test('promises can be configured', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { @@ -135,7 +156,13 @@ test('AWS.mock function should mock AWS service and method on the service', func // with or without callback req = s3.getObject('getObject', {}); st.ok(isNodeStream(req.createReadStream())); - st.end(); + // stream is currently always empty but that's subject to change. + // let's just consume it and ignore the contents + req = s3.getObject('getObject', {}); + var stream = req.createReadStream(); + streamToArray(stream, function() { + st.end(); + }); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){
28
test: cover createReadStream and refactored Promise code
1
.js
test
apache-2.0
dwyl/aws-sdk-mock
486
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); callback(null, "test"); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equals(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equals(data, 'message'); docClient.get({}, function(err, data){ st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> allow remocking with new values <DFF> @@ -72,7 +72,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('method is not re-mocked if a mock already exists', function(st){ + t.test('method is re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); @@ -81,11 +81,11 @@ test('AWS.mock function should mock AWS service and method on the service', func callback(null, "test"); }); sns.publish({}, function(err, data){ - st.equals(data, 'message'); + st.equals(data, 'test'); st.end(); }); }); - t.test('service is not re-mocked if a mock already exists', function(st){ + t.test('service is re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); @@ -344,10 +344,10 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { - callback(null, 'test'); + callback(null, 'puttest'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { - callback(null, 'test'); + callback(null, 'gettest'); }); st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); @@ -355,9 +355,9 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ - st.equals(data, 'message'); + st.equals(data, 'puttest'); docClient.get({}, function(err, data){ - st.equals(data, 'test'); + st.equals(data, 'gettest'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
7
allow remocking with new values
7
.js
test
apache-2.0
dwyl/aws-sdk-mock
487
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); callback(null, "test"); }); sns.publish({}, function(err, data){ st.equals(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equals(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equals(data, 'message'); docClient.get({}, function(err, data){ st.equals(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> allow remocking with new values <DFF> @@ -72,7 +72,7 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }); - t.test('method is not re-mocked if a mock already exists', function(st){ + t.test('method is re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); @@ -81,11 +81,11 @@ test('AWS.mock function should mock AWS service and method on the service', func callback(null, "test"); }); sns.publish({}, function(err, data){ - st.equals(data, 'message'); + st.equals(data, 'test'); st.end(); }); }); - t.test('service is not re-mocked if a mock already exists', function(st){ + t.test('service is re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); @@ -344,10 +344,10 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); var docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { - callback(null, 'test'); + callback(null, 'puttest'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { - callback(null, 'test'); + callback(null, 'gettest'); }); st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true); @@ -355,9 +355,9 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ - st.equals(data, 'message'); + st.equals(data, 'puttest'); docClient.get({}, function(err, data){ - st.equals(data, 'test'); + st.equals(data, 'gettest'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equals(AWS.DynamoDB.DocumentClient.isSinonProxy, true);
7
allow remocking with new values
7
.js
test
apache-2.0
dwyl/aws-sdk-mock
488
<NME> index.test.js <BEF> var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); }); }) } t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Add minimal createReadStream support Always returns an empty stream. <DFF> @@ -1,6 +1,7 @@ var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); +var isNodeStream = require('is-node-stream'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ @@ -126,6 +127,16 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }) } + t.test('request object supports createReadStream', function(st) { + awsMock.mock('S3', 'getObject', 'body'); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}, function(err, data) {}); + st.ok(isNodeStream(req.createReadStream())); + // with or without callback + req = s3.getObject('getObject', {}); + st.ok(isNodeStream(req.createReadStream())); + st.end(); + }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
11
Add minimal createReadStream support
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
489
<NME> index.test.js <BEF> var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); }); }) } t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message"); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Add minimal createReadStream support Always returns an empty stream. <DFF> @@ -1,6 +1,7 @@ var test = require('tape'); var awsMock = require('../index.js'); var AWS = require('aws-sdk'); +var isNodeStream = require('is-node-stream'); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ @@ -126,6 +127,16 @@ test('AWS.mock function should mock AWS service and method on the service', func }); }) } + t.test('request object supports createReadStream', function(st) { + awsMock.mock('S3', 'getObject', 'body'); + var s3 = new AWS.S3(); + var req = s3.getObject('getObject', {}, function(err, data) {}); + st.ok(isNodeStream(req.createReadStream())); + // with or without callback + req = s3.getObject('getObject', {}); + st.ok(isNodeStream(req.createReadStream())); + st.end(); + }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, "message");
11
Add minimal createReadStream support
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
490
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equals(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> improve test coverage to 100% <DFF> @@ -469,9 +469,11 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(stub.stub.isSinonProxy, true); st.end(); }); + t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { + awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end();
2
improve test coverage to 100%
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
491
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equals(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> improve test coverage to 100% <DFF> @@ -469,9 +469,11 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(stub.stub.isSinonProxy, true); st.end(); }); + t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { + awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end();
2
improve test coverage to 100%
0
.js
test
apache-2.0
dwyl/aws-sdk-mock
492
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); st.equals(sns1.publish.isSinonProxy, true); st.equals(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Fixed lint issues <DFF> @@ -348,16 +348,16 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); - + const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); - + st.equals(AWS.SNS.isSinonProxy, true); st.equals(sns1.publish.isSinonProxy, true); st.equals(sns2.publish.isSinonProxy, true); - + awsMock.restore('SNS', 'publish'); - + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false);
4
Fixed lint issues
4
.js
test
apache-2.0
dwyl/aws-sdk-mock
493
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equals(AWS.SNS.isSinonProxy, true); st.equals(sns1.publish.isSinonProxy, true); st.equals(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> Fixed lint issues <DFF> @@ -348,16 +348,16 @@ test('AWS.mock function should mock AWS service and method on the service', func awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); - + const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); - + st.equals(AWS.SNS.isSinonProxy, true); st.equals(sns1.publish.isSinonProxy, true); st.equals(sns2.publish.isSinonProxy, true); - + awsMock.restore('SNS', 'publish'); - + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false);
4
Fixed lint issues
4
.js
test
apache-2.0
dwyl/aws-sdk-mock
494
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { return promise; } : undefined, createReadStream: function() { if (replace instanceof Readable) { return replace; } else { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && typeof result.then === 'function') { storedResult = result } } stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> issue#97 - Stream depending on params for S3.getObject <DFF> @@ -164,6 +164,9 @@ function mockServiceMethod(service, client, method, replace) { return promise; } : undefined, createReadStream: function() { + if (storedResult instanceof Readable) { + return storedResult; + } if (replace instanceof Readable) { return replace; } else { @@ -204,7 +207,7 @@ function mockServiceMethod(service, client, method, replace) { if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && - typeof result.then === 'function') { + (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } }
4
issue#97 - Stream depending on params for S3.getObject
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
495
<NME> index.js <BEF> 'use strict'; /** * Helpers to mock the AWS SDK Services using sinon.js under the hood * Export two functions: * - mock * - restore * * Mocking is done in two steps: * - mock of the constructor for the service on AWS * - mock of the method on the service **/ const sinon = require('sinon'); const traverse = require('traverse'); let _AWS = require('aws-sdk'); const Readable = require('stream').Readable; const AWS = {}; const services = {}; /** * Sets the aws-sdk to be mocked. */ AWS.setSDK = function(path) { _AWS = require(path); }; AWS.setSDKInstance = function(sdk) { _AWS = sdk; }; /** * Stubs the service and registers the method that needs to be mocked. */ AWS.mock = function(service, method, replace) { // If the service does not exist yet, we need to create and stub it. if (!services[service]) { services[service] = {}; /** * Save the real constructor so we can invoke it later on. * Uses traverse for easy access to nested services (dot-separated) */ services[service].Constructor = traverse(_AWS).get(service.split('.')); services[service].methodMocks = {}; services[service].invoked = false; mockService(service); } // Register the method to be mocked out. if (!services[service].methodMocks[method]) { services[service].methodMocks[method] = { replace: replace }; // If the constructor was already invoked, we need to mock the method here. if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } } return services[service].methodMocks[method]; }; /** * Stubs the service and registers the method that needs to be re-mocked. */ AWS.remock = function(service, method, replace) { if (services[service].methodMocks[method]) { restoreMethod(service, method); services[service].methodMocks[method] = { replace: replace }; } if (services[service].invoked) { services[service].clients.forEach(client => { mockServiceMethod(service, client, method, replace); }) } return services[service].methodMocks[method]; } /** * Stub the constructor for the service on AWS. * E.g. calls of new AWS.SNS() are replaced. */ function mockService(service) { const nestedServices = service.split('.'); const method = nestedServices.pop(); const object = traverse(_AWS).get(nestedServices); const serviceStub = sinon.stub(object, method).callsFake(function(...args) { services[service].invoked = true; /** * Create an instance of the service by calling the real constructor * we stored before. E.g. const client = new AWS.SNS() * This is necessary in order to mock methods on the service. */ const client = new services[service].Constructor(...args); services[service].clients = services[service].clients || []; services[service].clients.push(client); // Once this has been triggered we can mock out all the registered methods. for (const key in services[service].methodMocks) { mockServiceMethod(service, client, key, services[service].methodMocks[key].replace); }; return client; }); services[service].stub = serviceStub; }; /** * Wraps a sinon stub or jest mock function as a fully functional replacement function */ function wrapTestStubReplaceFn(replace) { if (typeof replace !== 'function' || !(replace._isMockFunction || replace.isSinonProxy)) { return replace; } return (params, cb) => { // If only one argument is provided, it is the callback if (!cb) { cb = params; params = {}; } // Spy on the users callback so we can later on determine if it has been called in their replace const cbSpy = sinon.spy(cb); try { // Call the users replace, check how many parameters it expects to determine if we should pass in callback only, or also parameters const result = replace.length === 1 ? replace(cbSpy) : replace(params, cbSpy); // If the users replace already called the callback, there's no more need for us do it. if (cbSpy.called) { return; } if (typeof result.then === 'function') { result.then(val => cb(undefined, val), err => cb(err)); } else { cb(undefined, result); } } catch (err) { cb(err); } }; } /** * Stubs the method on a service. * * All AWS service methods take two argument: * - params: an object. * - callback: of the form 'function(err, data) {}'. */ function mockServiceMethod(service, client, method, replace) { replace = wrapTestStubReplaceFn(replace); services[service].methodMocks[method].stub = sinon.stub(client, method).callsFake(function() { const args = Array.prototype.slice.call(arguments); let userArgs, userCallback; if (typeof args[(args.length || 1) - 1] === 'function') { return promise; } : undefined, createReadStream: function() { if (replace instanceof Readable) { return replace; } else { if (typeof storedResult.then === 'function') { storedResult.then(resolve, reject) } else if (storedResult.reject) { reject(storedResult.reject); } else { resolve(storedResult.resolve); } } }; const callback = function(err, data) { if (!storedResult) { if (err) { storedResult = {reject: err}; } else { storedResult = {resolve: data}; } } if (userCallback) { userCallback(err, data); } tryResolveFromStored(); }; const request = { promise: havePromises ? function() { if (!promise) { promise = new AWS.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); } tryResolveFromStored(); return promise; } : undefined, createReadStream: function() { if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && typeof result.then === 'function') { storedResult = result } } stream._read = function(size) { if (typeof replace === 'string' || Buffer.isBuffer(replace)) { this.push(replace); } this.push(null); }; return stream; } }, on: function(eventName, callback) { return this; }, send: function(callback) { callback(storedResult.reject, storedResult.resolve); } }; // different locations for the paramValidation property const config = (client.config || client.options || _AWS.config); if (config.paramValidation) { try { // different strategies to find method, depending on wether the service is nested/unnested const inputRules = ((client.api && client.api.operations[method]) || client[method] || {}).input; if (inputRules) { const params = userArgs[(userArgs.length || 1) - 1]; new _AWS.ParamValidator((client.config || _AWS.config).paramValidation).validate(inputRules, params); } } catch (e) { callback(e, null); return request; } } // If the value of 'replace' is a function we call it with the arguments. if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } } // Else we call the callback with the value of 'replace'. else { callback(null, replace); } return request; }); } /** * Restores the mocks for just one method on a service, the entire service, or all mocks. * * When no parameters are passed, everything will be reset. * When only the service is passed, that specific service will be reset. * When a service and method are passed, only that method will be reset. */ AWS.restore = function(service, method) { if (!service) { restoreAllServices(); } else { if (method) { restoreMethod(service, method); } else { restoreService(service); } }; }; /** * Restores all mocked service and their corresponding methods. */ function restoreAllServices() { for (const service in services) { restoreService(service); } } /** * Restores a single mocked service and its corresponding methods. */ function restoreService(service) { if (services[service]) { restoreAllMethods(service); if (services[service].stub) services[service].stub.restore(); delete services[service]; } else { console.log('Service ' + service + ' was never instantiated yet you try to restore it.'); } } /** * Restores all mocked methods on a service. */ function restoreAllMethods(service) { for (const method in services[service].methodMocks) { restoreMethod(service, method); } } /** * Restores a single mocked method on a service. */ function restoreMethod(service, method) { if (services[service] && services[service].methodMocks[method]) { if (services[service].methodMocks[method].stub) { // restore this method on all clients services[service].clients.forEach(client => { if (client[method] && typeof client[method].restore === 'function') { client[method].restore(); } }) } delete services[service].methodMocks[method]; } else { console.log('Method ' + service + ' was never instantiated yet you try to restore it.'); } } (function() { const setPromisesDependency = _AWS.config.setPromisesDependency; /* istanbul ignore next */ /* only to support for older versions of aws-sdk */ if (typeof setPromisesDependency === 'function') { AWS.Promise = global.Promise; _AWS.config.setPromisesDependency = function(p) { AWS.Promise = p; return setPromisesDependency(p); }; } })(); module.exports = AWS; <MSG> issue#97 - Stream depending on params for S3.getObject <DFF> @@ -164,6 +164,9 @@ function mockServiceMethod(service, client, method, replace) { return promise; } : undefined, createReadStream: function() { + if (storedResult instanceof Readable) { + return storedResult; + } if (replace instanceof Readable) { return replace; } else { @@ -204,7 +207,7 @@ function mockServiceMethod(service, client, method, replace) { if (typeof replace === 'function') { const result = replace.apply(replace, userArgs.concat([callback])); if (storedResult === undefined && result != null && - typeof result.then === 'function') { + (typeof result.then === 'function' || result instanceof Readable)) { storedResult = result } }
4
issue#97 - Stream depending on params for S3.getObject
1
.js
js
apache-2.0
dwyl/aws-sdk-mock
496
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> When method is restored, it should be restored on all clients <DFF> @@ -310,7 +310,6 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); - t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); @@ -325,10 +324,9 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); - - t.test('methods on all service instances are restored', function(st){ + t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, 'message'); + callback(null, 'message'); }); const sns1 = new AWS.SNS(); @@ -345,7 +343,25 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); - + t.test('all methods on all service instances are restored', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, 'message'); + }); + + const sns1 = new AWS.SNS(); + const sns2 = new AWS.SNS(); + + st.equals(AWS.SNS.isSinonProxy, true); + st.equals(sns1.publish.isSinonProxy, true); + st.equals(sns2.publish.isSinonProxy, true); + + awsMock.restore('SNS'); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); + st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false); + st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); + st.end(); + }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message');
21
When method is restored, it should be restored on all clients
5
.js
test
apache-2.0
dwyl/aws-sdk-mock
497
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); }); t.test('multiple methods can be mocked on the same service', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}, function(err, data) { st.equal(data, 'message'); lambda.createFunction({}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); }); if (typeof Promise === 'function') { t.test('promises are supported', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); awsMock.mock('S3', 'getObject', function(params, callback) { callback('This is a test error to see if promise rejections go unhandled'); }); const S3 = new AWS.S3(); S3.getObject({}, function(err, data) {}); st.end(); }); t.test('promises work with async completion', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { setTimeout(callback.bind(this, null, 'message'), 10); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { setTimeout(callback.bind(this, error, 'message'), 10); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> When method is restored, it should be restored on all clients <DFF> @@ -310,7 +310,6 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); - t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); @@ -325,10 +324,9 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); - - t.test('methods on all service instances are restored', function(st){ + t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ - callback(null, 'message'); + callback(null, 'message'); }); const sns1 = new AWS.SNS(); @@ -345,7 +343,25 @@ test('AWS.mock function should mock AWS service and method on the service', func st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); - + t.test('all methods on all service instances are restored', function(st){ + awsMock.mock('SNS', 'publish', function(params, callback){ + callback(null, 'message'); + }); + + const sns1 = new AWS.SNS(); + const sns2 = new AWS.SNS(); + + st.equals(AWS.SNS.isSinonProxy, true); + st.equals(sns1.publish.isSinonProxy, true); + st.equals(sns2.publish.isSinonProxy, true); + + awsMock.restore('SNS'); + + st.equals(AWS.SNS.hasOwnProperty('isSinonProxy'), false); + st.equals(sns1.publish.hasOwnProperty('isSinonProxy'), false); + st.equals(sns2.publish.hasOwnProperty('isSinonProxy'), false); + st.end(); + }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message');
21
When method is restored, it should be restored on all clients
5
.js
test
apache-2.0
dwyl/aws-sdk-mock
498
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); st.end(); }); }) t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); var s3 = new AWS.S3(); var req = s3.getObject('getObject', {}, function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject', {}); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> fix: unhandled promise rejections when using callbacks See issue #53 <DFF> @@ -136,6 +136,19 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }) + t.test('no unhandled promise rejections when promises are not used', function(st) { + process.on('unhandledRejection', function(reason, promise) { + st.fail('unhandledRejection, reason follows'); + st.error(reason); + }); + awsMock.mock('S3', 'getObject', function(params, callback) { + console.dir(callback); + callback('This is a test error to see if promise rejections go unhandled'); + }); + var S3 = new AWS.S3(); + S3.getObject({}, function(err, data) {}); + st.end(); + }) t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); @@ -182,14 +195,14 @@ test('AWS.mock function should mock AWS service and method on the service', func t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); var s3 = new AWS.S3(); - var req = s3.getObject('getObject', {}, function(err, data) {}); + var req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback - req = s3.getObject('getObject', {}); + req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents - req = s3.getObject('getObject', {}); + req = s3.getObject('getObject'); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject');
16
fix: unhandled promise rejections when using callbacks
3
.js
test
apache-2.0
dwyl/aws-sdk-mock
499
<NME> index.test.js <BEF> 'use strict'; const tap = require('tap'); const test = tap.test; const awsMock = require('../index.js'); const AWS = require('aws-sdk'); const isNodeStream = require('is-node-stream'); const concatStream = require('concat-stream'); const Readable = require('stream').Readable; const jest = require('jest-mock'); const sinon = require('sinon'); AWS.config.paramValidation = false; tap.afterEach(() => { awsMock.restore(); }); test('AWS.mock function should mock AWS service and method on the service', function(t){ t.test('mock function replaces method with a function that returns replace string', function(st){ awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('mock function replaces method with replace function', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('method which accepts any number of arguments can be mocked', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3(); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); awsMock.mock('S3', 'upload', function(params, options, callback) { callback(null, options); }); s3.upload({}, {test: 'message'}, function(err, data) { st.equal(data.test, 'message'); st.end(); }); }); }); t.test('method fails on invalid input if paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', notKey: 'k'}, function(err, data) { st.ok(err); st.notOk(data); st.end(); }); }); t.test('method with no input rules can be mocked even if paramValidation is set', function(st) { awsMock.mock('S3', 'getSignedUrl', 'message'); const s3 = new AWS.S3({paramValidation: true}); s3.getSignedUrl('getObject', {}, function(err, data) { st.equal(data, 'message'); st.end(); }); }); t.test('method succeeds on valid input when paramValidation is set', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3({paramValidation: true}); s3.getObject({Bucket: 'b', Key: 'k'}, function(err, data) { st.notOk(err); st.equal(data.Body, 'body'); st.end(); }); }); t.test('method is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'test'); }); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('service is not re-mocked if a mock already exists', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'test'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'test'); st.end(); }); }); t.test('service is re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); t.test('all instances of service are re-mocked when remock called', function(st){ awsMock.mock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 1'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); awsMock.remock('SNS', 'subscribe', function(params, callback){ callback(null, 'message 2'); }); sns1.subscribe({}, function(err, data){ st.equal(data, 'message 2'); sns2.subscribe({}, function(err, data){ st.equal(data, 'message 2'); st.end(); }); }); st.end(); }); }) t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { callback(error, 'message'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('replacement returns thennable', function(st){ const error = new Error('on purpose'); awsMock.mock('Lambda', 'getFunction', function(params) { return Promise.resolve('message') }); awsMock.mock('Lambda', 'createFunction', function(params, callback) { return Promise.reject(error) }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('no unhandled promise rejections when promises are not used', function(st) { process.on('unhandledRejection', function(reason, promise) { st.fail('unhandledRejection, reason follows'); st.error(reason); }); t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); var s3 = new AWS.S3(); var req = s3.getObject('getObject', {}, function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject', {}); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject', {}); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject'); }); const lambda = new AWS.Lambda(); lambda.getFunction({}).promise().then(function(data) { st.equal(data, 'message'); }).then(function(){ return lambda.createFunction({}).promise(); }).catch(function(data){ st.equal(data, error); st.end(); }); }); t.test('promises can be configured', function(st){ awsMock.mock('Lambda', 'getFunction', function(params, callback) { callback(null, 'message'); }); const lambda = new AWS.Lambda(); function P(handler) { const self = this; function yay (value) { self.value = value; } handler(yay, function(){}); } P.prototype.then = function(yay) { if (this.value) yay(this.value) }; AWS.config.setPromisesDependency(P); const promise = lambda.getFunction({}).promise(); st.equal(promise.constructor.name, 'P'); promise.then(function(data) { st.equal(data, 'message'); st.end(); }); }); } t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); let req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents req = s3.getObject('getObject'); const stream = req.createReadStream(); stream.pipe(concatStream(function() { st.end(); })); }); t.test('request object createReadStream works with streams', function(st) { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); awsMock.mock('S3', 'getObject', bodyStream); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with returned streams', function(st) { awsMock.mock('S3', 'getObject', () => { const bodyStream = new Readable(); bodyStream.push('body'); bodyStream.push(null); return bodyStream; }); const stream = new AWS.S3().getObject('getObject').createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with strings', function(st) { awsMock.mock('S3', 'getObject', 'body'); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream works with buffers', function(st) { awsMock.mock('S3', 'getObject', Buffer.alloc(4, 'body')); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), 'body'); st.end(); })); }); t.test('request object createReadStream ignores functions', function(st) { awsMock.mock('S3', 'getObject', function(){}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('request object createReadStream ignores non-buffer objects', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); const stream = req.createReadStream(); stream.pipe(concatStream(function(actual) { st.equal(actual.toString(), ''); st.end(); })); }); t.test('call on method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.on, 'function'); st.end(); }); t.test('call send method of request object', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); st.equal(typeof req.send, 'function'); st.end(); }); t.test('all the methods on a service are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); st.equal(AWS.SNS.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('only the method on the service is restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('method on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS', 'publish'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), true); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all methods on all service instances are restored', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); const sns1 = new AWS.SNS(); const sns2 = new AWS.SNS(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(sns1.publish.isSinonProxy, true); st.equal(sns2.publish.isSinonProxy, true); awsMock.restore('SNS'); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(sns1.publish.hasOwnProperty('isSinonProxy'), false); st.equal(sns2.publish.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('all the services are restored when no arguments given to awsMock.restore', function(st){ awsMock.mock('SNS', 'publish', function(params, callback){ callback(null, 'message'); }); awsMock.mock('DynamoDB', 'putItem', function(params, callback){ callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback){ callback(null, 'test'); }); const sns = new AWS.SNS(); const docClient = new AWS.DynamoDB.DocumentClient(); const dynamoDb = new AWS.DynamoDB(); st.equal(AWS.SNS.isSinonProxy, true); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(sns.publish.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(dynamoDb.putItem.isSinonProxy, true); awsMock.restore(); st.equal(AWS.SNS.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(sns.publish.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.putItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('a nested service can be mocked properly', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'put', 'message'); const docClient = new AWS.DynamoDB.DocumentClient(); awsMock.mock('DynamoDB.DocumentClient', 'put', function(params, callback) { callback(null, 'test'); }); awsMock.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { callback(null, 'test'); }); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.put.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); docClient.put({}, function(err, data){ st.equal(data, 'message'); docClient.get({}, function(err, data){ st.equal(data, 'test'); awsMock.restore('DynamoDB.DocumentClient', 'get'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); awsMock.restore('DynamoDB.DocumentClient'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.put.hasOwnProperty('isSinonProxy'), false); st.end(); }); }); }); t.test('a nested service can be mocked properly even when paramValidation is set', function(st){ awsMock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, 'test'); }); const docClient = new AWS.DynamoDB.DocumentClient({paramValidation: true}); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(docClient.query.isSinonProxy, true); docClient.query({}, function(err, data){ st.equal(err, null); st.equal(data, 'test'); st.end(); }); }); t.test('a mocked service and a mocked nested service can coexist as long as the nested service is mocked first', function(st) { awsMock.mock('DynamoDB.DocumentClient', 'get', 'message'); awsMock.mock('DynamoDB', 'getItem', 'test'); const docClient = new AWS.DynamoDB.DocumentClient(); let dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); awsMock.mock('DynamoDB', 'getItem', 'test'); dynamoDb = new AWS.DynamoDB(); st.equal(AWS.DynamoDB.DocumentClient.isSinonProxy, true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.isSinonProxy, true); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB.DocumentClient'); // the first assertion is true because DynamoDB is still mocked st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), true); st.equal(AWS.DynamoDB.isSinonProxy, true); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.isSinonProxy, true); awsMock.restore('DynamoDB'); st.equal(AWS.DynamoDB.DocumentClient.hasOwnProperty('isSinonProxy'), false); st.equal(AWS.DynamoDB.hasOwnProperty('isSinonProxy'), false); st.equal(docClient.get.hasOwnProperty('isSinonProxy'), false); st.equal(dynamoDb.getItem.hasOwnProperty('isSinonProxy'), false); st.end(); }); t.test('Mocked services should use the implementation configuration arguments without complaining they are missing', function(st) { awsMock.mock('CloudSearchDomain', 'search', function(params, callback) { return callback(null, 'message'); }); const csd = new AWS.CloudSearchDomain({ endpoint: 'some endpoint', region: 'eu-west' }); awsMock.mock('CloudSearchDomain', 'suggest', function(params, callback) { return callback(null, 'message'); }); csd.search({}, function(err, data) { st.equal(data, 'message'); }); csd.suggest({}, function(err, data) { st.equal(data, 'message'); }); st.end(); }); t.skip('Mocked service should return the sinon stub', function(st) { // TODO: the stub is only returned if an instance was already constructed const stub = awsMock.mock('CloudSearchDomain', 'search'); st.equal(stub.stub.isSinonProxy, true); st.end(); }); t.test('Restore should not fail when the stub did not exist.', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('Lambda'); awsMock.restore('SES', 'sendEmail'); awsMock.restore('CloudSearchDomain', 'doesnotexist'); st.end(); } catch (e) { console.log(e); } }); t.test('Restore should not fail when service was not mocked', function (st) { // This test will fail when restoring throws unneeded errors. try { awsMock.restore('CloudFormation'); awsMock.restore('UnknownService'); st.end(); } catch (e) { console.log(e); } }); t.test('Mocked service should allow chained calls after listening to events', function (st) { awsMock.mock('S3', 'getObject'); const s3 = new AWS.S3(); const req = s3.getObject({Bucket: 'b', notKey: 'k'}); st.equal(req.on('httpHeaders', ()=>{}), req); st.end(); }); t.test('Mocked service should return replaced function when request send is called', function(st) { awsMock.mock('S3', 'getObject', {Body: 'body'}); let returnedValue = ''; const s3 = new AWS.S3(); const req = s3.getObject('getObject', {}); req.send(async (err, data) => { returnedValue = data.Body; }); st.equal(returnedValue, 'body'); st.end(); }); t.test('mock function replaces method with a sinon stub and returns successfully using callback', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a sinon stub and returns successfully using promise', function(st) { const sinonStub = sinon.stub(); sinonStub.returns('message'); awsMock.mock('DynamoDB', 'getItem', sinonStub); const db = new AWS.DynamoDB(); db.getItem({}).promise().then(function(data){ st.equal(data, 'message'); st.equal(sinonStub.called, true); st.end(); }); }); t.test('mock function replaces method with a jest mock and returns successfully', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock returning successfully and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn().mockReturnValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and resolves successfully', function(st) { const jestMock = jest.fn().mockResolvedValue('message'); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(data, 'message'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and fails successfully', function(st) { const jestMock = jest.fn(() => { throw new Error('something went wrong') }); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock and rejects successfully', function(st) { const jestMock = jest.fn().mockRejectedValue(new Error('something went wrong')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err){ st.equal(err.message, 'something went wrong'); st.equal(jestMock.mock.calls.length, 1); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem({}, function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation and allows mocked method to be called with only callback', function(st) { const jestMock = jest.fn((params, cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.test('mock function replaces method with a jest mock with implementation expecting only a callback', function(st) { const jestMock = jest.fn((cb) => cb(null, 'item')); awsMock.mock('DynamoDB', 'getItem', jestMock); const db = new AWS.DynamoDB(); db.getItem(function(err, data){ st.equal(jestMock.mock.calls.length, 1); st.equal(data, 'item'); st.end(); }); }); t.end(); }); test('AWS.setSDK function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('SNS', 'publish', 'message'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message'); st.end(); }); }); t.test('Modules with multi-parameter constructors can be set for mocking', function(st) { awsMock.setSDK('aws-sdk'); awsMock.mock('CloudFront.Signer', 'getSignedUrl'); const signer = new AWS.CloudFront.Signer('key-pair-id', 'private-key'); st.type(signer, 'Signer'); st.end(); }); t.test('Setting the aws-sdk to the wrong module can cause an exception when mocking', function(st) { awsMock.setSDK('sinon'); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDK('aws-sdk'); st.end(); }); t.end(); }); test('AWS.setSDKInstance function should mock a specific AWS module', function(t) { t.test('Specific Modules can be set for mocking', function(st) { const aws2 = require('aws-sdk'); awsMock.setSDKInstance(aws2); awsMock.mock('SNS', 'publish', 'message2'); const sns = new AWS.SNS(); sns.publish({}, function(err, data){ st.equal(data, 'message2'); st.end(); }); }); t.test('Setting the aws-sdk to the wrong instance can cause an exception when mocking', function(st) { const bad = {}; awsMock.setSDKInstance(bad); st.throws(function() { awsMock.mock('SNS', 'publish', 'message'); }); awsMock.setSDKInstance(AWS); st.end(); }); t.end(); }); <MSG> fix: unhandled promise rejections when using callbacks See issue #53 <DFF> @@ -136,6 +136,19 @@ test('AWS.mock function should mock AWS service and method on the service', func st.end(); }); }) + t.test('no unhandled promise rejections when promises are not used', function(st) { + process.on('unhandledRejection', function(reason, promise) { + st.fail('unhandledRejection, reason follows'); + st.error(reason); + }); + awsMock.mock('S3', 'getObject', function(params, callback) { + console.dir(callback); + callback('This is a test error to see if promise rejections go unhandled'); + }); + var S3 = new AWS.S3(); + S3.getObject({}, function(err, data) {}); + st.end(); + }) t.test('promises work with async completion', function(st){ awsMock.restore('Lambda', 'getFunction'); awsMock.restore('Lambda', 'createFunction'); @@ -182,14 +195,14 @@ test('AWS.mock function should mock AWS service and method on the service', func t.test('request object supports createReadStream', function(st) { awsMock.mock('S3', 'getObject', 'body'); var s3 = new AWS.S3(); - var req = s3.getObject('getObject', {}, function(err, data) {}); + var req = s3.getObject('getObject', function(err, data) {}); st.ok(isNodeStream(req.createReadStream())); // with or without callback - req = s3.getObject('getObject', {}); + req = s3.getObject('getObject'); st.ok(isNodeStream(req.createReadStream())); // stream is currently always empty but that's subject to change. // let's just consume it and ignore the contents - req = s3.getObject('getObject', {}); + req = s3.getObject('getObject'); var stream = req.createReadStream(); stream.pipe(concatStream(function() { awsMock.restore('S3', 'getObject');
16
fix: unhandled promise rejections when using callbacks
3
.js
test
apache-2.0
dwyl/aws-sdk-mock