Skip to content

Commit

Permalink
chore: add test for TD003 plugin (#462)
Browse files Browse the repository at this point in the history
add test for TD003 plugin.  No function change.
  • Loading branch information
DinoChiesa committed Aug 28, 2024
1 parent 4abdd24 commit 4973d8d
Show file tree
Hide file tree
Showing 17 changed files with 509 additions and 32 deletions.
77 changes: 45 additions & 32 deletions lib/package/plugins/TD003-targetNameAttr.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
/*
Copyright 2019-2020 Google LLC
Copyright 2019-2020,2024 Google LLC
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
https://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.
Expand All @@ -18,41 +21,51 @@ const plugin = {
name: "TargetEndpoint Name",
message: "Check TargetEndpoint name attribute against file name.",
fatal: false,
severity: 2, // 1 = warn, 2 = error
severity: 2, // 1 = warn, 2 = error
nodeType: "Endpoint",
enabled: true
};

const path = require('path'),
debug = require("debug")("apigeelint:" + ruleId);

const onTargetEndpoint = function(endpoint, cb) {
let shortFilename = path.basename(endpoint.getFileName()),
basename = shortFilename.split(".xml")[0],
nameFromAttribute = endpoint.getName(),
flagged = false;

try {
debug(`onTargetEndpoint shortfile(${shortFilename}) nameFromAttr(${nameFromAttribute})`);
if (basename !== nameFromAttribute) {
let nameAttr = endpoint.select('//@name');
endpoint.addMessage({
plugin,
line: nameAttr[0].lineNumber,
column: nameAttr[0].columnNumber,
message: `File basename (${basename}) does not match endpoint name (${nameFromAttribute}).`
});
flagged = true;
}
if (typeof(cb) == 'function') {
cb(null, flagged);
}
}
catch (exc1) {
console.error('exception: ' + exc1);
debug(`onTargetEndpoint exc(${exc1})`);
}
};
const path = require("path"),
debug = require("debug")("apigeelint:" + ruleId);

const onTargetEndpoint = function (endpoint, cb) {
const shortFilename = path.basename(endpoint.getFileName()),
basename = shortFilename.split(".xml")[0],
nameFromAttribute = endpoint.getName();
let flagged = false;

try {
debug(
`onTargetEndpoint shortfile(${shortFilename}) nameFromAttr(${nameFromAttribute})`
);
if (!nameFromAttribute) {
const rootElement = endpoint.getElement();
endpoint.addMessage({
plugin,
line: rootElement.lineNumber,
column: rootElement.columnNumber,
message: `TargetEndpoint has no name attribute.`
});
flagged = true;
} else if (basename !== nameFromAttribute) {
const nameAttr = endpoint.select("//@name");
endpoint.addMessage({
plugin,
line: nameAttr[0].lineNumber,
column: nameAttr[0].columnNumber,
message: `File basename (${basename}) does not match endpoint name (${nameFromAttribute}).`
});
flagged = true;
}
if (typeof cb == "function") {
cb(null, flagged);
}
} catch (exc1) {
console.error("exception: " + exc1);
debug(`onTargetEndpoint exc(${exc1})`);
}
};

module.exports = {
plugin,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<APIProxy name="flightdata">
<ConfigurationVersion majorVersion="4" minorVersion="0"/>
<CreatedAt>1491498008040</CreatedAt>
<Description/>
<DisplayName>flightdata</DisplayName>
<LastModifiedAt>1491517153495</LastModifiedAt>
<Policies/>
<Resources/>
<Spec/>
<TargetServers/>
<validate>false</validate>
</APIProxy>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<AssignMessage name='AM-Clean-Response-Headers'>
<Remove>
<Headers>
<Header name='X-Robots-Tag'/>
<Header name='Cache-Control'/>
<Header name='Pragma'/>
<Header name='Expires'/>
<Header name='P3P'/>
<Header name='Content-Security-Policy'/>
<Header name='X-Content-Type-Options'/>
<Header name='X-XSS-Protection'/>
<Header name='Server'/>
<Header name='Set-Cookie'/>
<Header name='Accept-Ranges'/>
<Header name='Vary'/>
<Header name='Content-Disposition'/>
</Headers>
</Remove>
<IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables>
</AssignMessage>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<AssignMessage name='AM-Inject-Proxy-Revision-Header'>
<Set>
<Headers>
<Header name='apiproxy'>{apiproxy.name} r{apiproxy.revision}</Header>
</Headers>
</Set>
</AssignMessage>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<AssignMessage name='AM-PreparedQuery-1'>
<AssignVariable>
<Name>bq_query</Name>
<Template>SELECT airline, code FROM [bigquery-samples.airline_ontime_data.airline_id_codes] WHERE airline != 'Description' group by airline, code order by airline limit 32</Template>
</AssignVariable>
</AssignMessage>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<AssignMessage name='AM-PreparedQuery-2'>
<AssignVariable>
<Name>bq_query</Name>
<Template>SELECT airline, code FROM [bigquery-samples.airline_ontime_data.airline_id_codes] WHERE airline != 'Description' group by airline, code order by airline limit 100</Template>
</AssignVariable>
</AssignMessage>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<AssignMessage name='AM-PreparedQuery-3'>
<AssignVariable>
<Name>bq_query</Name>
<Template>SELECT airline, code FROM [bigquery-samples.airline_ontime_data.airline_id_codes] WHERE airline != 'Description' group by airline, code order by airline limit 500</Template>
</AssignVariable>
</AssignMessage>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<AssignMessage name='AM-PreparedQuery-4'>
<AssignVariable>
<Name>bq_query</Name>
<Template>SELECT airline, count(*) AS total_count FROM [bigquery-samples.airline_ontime_data.flights] WHERE departure_airport = '{param1}' AND date = '{param2}' GROUP BY airline</Template>
</AssignVariable>
</AssignMessage>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<AssignMessage name='AM-Query'>
<AssignTo>request</AssignTo>
<AssignVariable>
<Name>target.copy.pathsuffix</Name>
<Value>false</Value>
</AssignVariable>
<Set>
<Headers>
<Header name='Accept'>application/json</Header>
</Headers>
<Payload contentType='application/json'>{"query": "{bq_query}"}
</Payload>
<Verb>POST</Verb>
</Set>
</AssignMessage>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<ExtractVariables name='EV-PathParams-4'>
<Source>request</Source>
<URIPath>
<Pattern ignoreCase="true">/airports/{param1}/counts/{param2}</Pattern>
</URIPath>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</ExtractVariables>
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Javascript name='JS-Convert-Response'>
<Source><![CDATA[
var c = JSON.parse(context.getVariable('response.content'));
if (Number(c.totalRows) >0) {
var fieldnames = c.schema.fields.map(function(field){
return field.name;
});
var rows = c.rows.map(function(row) {
var values = row.f.map(function(f){ return f.v; });
var result = {};
fieldnames.forEach(function(name, ix){ result[name] = values[ix]; });
return result;
});
c.rows = rows;
}
delete c.kind;
delete c.jobReference;
context.setVariable('response.content', JSON.stringify(c,null,2)+'\n');
]]>
</Source>
</Javascript>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<RaiseFault name='RF-Unknown-Request'>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<FaultResponse>
<Set>
<Payload contentType='application/json'>{
"error" : {
"code" : 404.01,
"message" : "that request was unknown; try a different request."
}
}
</Payload>
<StatusCode>404</StatusCode>
<ReasonPhrase>Not Found</ReasonPhrase>
</Set>
</FaultResponse>
</RaiseFault>
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
<ProxyEndpoint name="endpoint1">

<HTTPProxyConnection>
<BasePath>/flightdata</BasePath>
<Properties/>
<VirtualHost>secure</VirtualHost>
</HTTPProxyConnection>

<FaultRules/>
<DefaultFaultRule name="default-fault-rule">
<Step>
<Name>AM-Inject-Proxy-Revision-Header</Name>
</Step>
<AlwaysEnforce>true</AlwaysEnforce>
</DefaultFaultRule>

<PreFlow name="PreFlow">
<Request>
</Request>
<Response/>
</PreFlow>

<PostFlow name="PostFlow">
<Request/>
<Response>
<Step>
<Name>JS-Convert-Response</Name>
</Step>
<Step>
<Name>AM-Inject-Proxy-Revision-Header</Name>
</Step>
</Response>
</PostFlow>

<PostClientFlow name="PostFlow">
<Request/>
<Response>
</Response>
</PostClientFlow>

<Flows>

<!-- emit one flow for each item in the config -->


<Flow name="airlines32">
<Request>
<!-- if query is parameterized, extract the fields -->

<Step>
<Name>AM-PreparedQuery-1</Name>
</Step>
</Request>
<Response>
</Response>
<Condition>proxy.pathsuffix MatchesPath "/airlines32" and request.verb = "GET"</Condition>
</Flow>


<Flow name="airlines100">
<Request>
<!-- if query is parameterized, extract the fields -->

<Step>
<Name>AM-PreparedQuery-2</Name>
</Step>
</Request>
<Response>
</Response>
<Condition>proxy.pathsuffix MatchesPath "/airlines100" and request.verb = "GET"</Condition>
</Flow>


<Flow name="airlines500">
<Request>
<!-- if query is parameterized, extract the fields -->

<Step>
<Name>AM-PreparedQuery-3</Name>
</Step>
</Request>
<Response>
</Response>
<Condition>proxy.pathsuffix MatchesPath "/airlines500" and request.verb = "GET"</Condition>
</Flow>


<Flow name="airport-counts">
<Request>
<!-- if query is parameterized, extract the fields -->

<Step>
<Name>EV-PathParams-4</Name>
</Step>

<Step>
<Name>AM-PreparedQuery-4</Name>
</Step>
</Request>
<Response>
</Response>
<Condition>proxy.pathsuffix MatchesPath "/airports/*/counts/*" and request.verb = "GET"</Condition>
</Flow>


<Flow name="unknown request">
<Request>
<Step>
<Name>RF-Unknown-Request</Name>
</Step>
</Request>
<Response>
</Response>
</Flow>

</Flows>

<RouteRule name="default">
<TargetEndpoint>target-1</TargetEndpoint>
</RouteRule>

</ProxyEndpoint>
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<TargetEndpoint name="target-1">
<PreFlow name="PreFlow">
<Request>
<Step>
<Name>AM-Query</Name>
</Step>
</Request>
<Response>
<Step>
<Name>AM-Clean-Response-Headers</Name>
</Step>
</Response>
</PreFlow>

<PostFlow name="PostFlow">
<Request/>
<Response>
</Response>
</PostFlow>

<Flows/>

<HTTPTargetConnection>

<!-- tell Apigee to invoke this with a Google Access Token -->
<Authentication>
<GoogleAccessToken>
<Scopes>
<Scope>https://www.googleapis.com/auth/cloud-platform</Scope>
</Scopes>
</GoogleAccessToken>
</Authentication>

<SSLInfo>
<Enabled>true</Enabled>
<IgnoreValidationErrors>false</IgnoreValidationErrors>
</SSLInfo>
<Properties/>
<!-- assemble the target path -->
<URL>https://bigquery.googleapis.com/bigquery/v2/projects/infinite-chain-292422/queries</URL>
</HTTPTargetConnection>
</TargetEndpoint>
Loading

0 comments on commit 4973d8d

Please sign in to comment.