Commit b55abbad authored by Giuseppe Tropea's avatar Giuseppe Tropea
Browse files

translated to python

parent 84d18be7
Loading
Loading
Loading
Loading

parsespec/extractbehaviours.js

deleted100644 → 0
+0 −166
Original line number Original line Diff line number Diff line
const fs = require("fs");
const outputLogger = new console.Console(fs.createWriteStream("./output.log"));

let fullapi = fs.readFileSync('API.json', "utf8");
fullapi = JSON.parse(fullapi);

var i_am_inside = false;

let testcases_fromspec = [];
var testcasemetadata = {};
testcasemetadata.seqnumber = 0;
testcasemetadata.progressive_subid = 0;
number_of_blocks = fullapi.blocks.length;
current_index = 0;
while(current_index < number_of_blocks) {
    block = fullapi.blocks[current_index];
    let type = block.t;
    let value = block.c;
    if (is_a_apigroup_header(type, value)) {
        if(value[2][0].t != "Str") {
            console.log("H2 group not Str!");
            process.exit();
        }
        // we collect all the words composing the higher-level clause name, example: "5.6 Context Information Provision"
        // but skip the first token because it is the clause number
        testcasemetadata.descriptive_group = value[2].slice(1).filter(el => el.t != "Space").map(el => el.c).join(" ");
    }
    if (is_a_apioperation_header(type, value)) {
        if(value[2][0].t != "Str") {
            console.log("H3 operation not Str!");
            exit();
        }
        // we create metadata for all testcases of this operation:
        // the first token is the clause number
        testcasemetadata.clause_number = value[2][0].c;
        // the group identifier is composed of the first two words of the group descriptive header string, by removing spaces
        testcasemetadata.group_fromspec = compact_string_array(testcasemetadata.descriptive_group.split(" ").slice(0, 2));
        // the subgroup is composed of the remaining (after 2 till end) words of the group descriptive header string
        testcasemetadata.subgroup_fromspec = compact_string_array(testcasemetadata.descriptive_group.split(" ").slice(2));
        // then we collect, for the name of the operation, all the words composing the lowe-level name, example "5.6.1 Create Entity"
        // but skip the first token because it is the clause number  
        testcasemetadata.descriptive_operation = value[2].slice(1).filter(el => el.t != "Space").map(el => el.c).join(" ");
        console.log("         H3 - "+testcasemetadata.descriptive_group+" - "+testcasemetadata.descriptive_operation);
        // the operation identifier is composed from the descriptive header string of the operation itself, by removing spaces
        testcasemetadata.operation_fromspec = compact_string_array(testcasemetadata.descriptive_operation.split(" "));
        // now we need to infer the sub-sub-group, which is the object of the operation, f.e. if the
        // operation is "Create Entity", the the sub-sub-group is "Entity"
    }
    if (is_a_behaviour_header(type, value) && i_am_inside === false) {
        i_am_inside = true;
        testcasemetadata.seqnumber++;
        console.log("entering "+value[2][0].c+" META "+testcasemetadata.group_fromspec+" "+testcasemetadata.subgroup_fromspec+" "+testcasemetadata.operation_fromspec);
    }
    else if (i_am_inside === true && type === "Header") { // i get out once i reach whatever Header follows
        i_am_inside = false;
        // ressetting the subindex
        testcasemetadata.progressive_subid = 0;
        console.log("exiting "+value[2][0].c);
        current_index--; // parse the current exit block again because we might have two good blocks back-to-back
    }
    else if (i_am_inside === true) {
        if (type === "BulletList" || type === "Para") {
            testcasemetadata.progressive_subid++;
            testcasemetadata.tp_id_fromspec = testcasemetadata.seqnumber.toString().padStart(3, '0') + "_" + testcasemetadata.progressive_subid.toString().padStart(2, '0')
            testcasemetadata.description = value.filter(el => el.t === "Str").map(el => el.c).join(" ");
            // push a deep copy of the object into the array
            testcases_fromspec.push(JSON.parse(JSON.stringify(testcasemetadata)));
            console.log("..collecting BLock "+current_index+" of "+value.length+" in "+testcasemetadata.tp_id_fromspec);
            outputLogger.log(testcasemetadata.tp_id_fromspec)
            outputLogger.log(testcasemetadata.group_fromspec+"/"+testcasemetadata.subgroup_fromspec+"/"+testcasemetadata.operation_fromspec+"/");
            outputLogger.log(testcasemetadata.clause_number);
            outputLogger.log(testcasemetadata.description);
            outputLogger.log("");
        }
        else {
            console.log("..not collecting "+type+": "+value);
        }
    }
    current_index++;
}

// The URL of the REST endpoint of the NoSQL database
const dburl = "http://ec2-18-153-159-20.eu-central-1.compute.amazonaws.com:5555/fromspec";
// Making a DELETE request
fetch(dburl, { method: 'DELETE' })
  .then(response => console.log(`Delete response status: ${response.status}`))
  .catch(error => console.error('Error:', error));
// Set the appropriate headers for JSON
const headers = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  // Include any other headers the API requires
};
// Making the POST request
fetch(dburl, {
  method: 'POST',
  headers: headers,
  body: JSON.stringify(testcases_fromspec)
})
.then(response => {
  console.log(`Post response status: ${response.status}`);
  return response.text();
})
.then(text => console.log(text))
.catch(error => console.error('Error:', error));







// check if we are entering a level-4 header that spells "5.x.x.x Behaviour"
// or a level-3 common Behaviour greater than 5.5.2
function is_a_behaviour_header(type, value) {
    if (type === "Header" && value[0] === 4 && value[2][0].c.startsWith("5.") && value[2][2].c === "Behaviour") {
        return true;
    }

    if(is_a_apioperation_header(type, value) && value[2][0].c.startsWith("5.5.")) {
        subclause_of_clause_five = parseInt(value[2][0].c.substring(4)); // from the 4th char, i.e. skipping "5.5." at the beginning
        console.log(subclause_of_clause_five);
        if(subclause_of_clause_five >= 4 && subclause_of_clause_five <= 99) {
            // if we are in subclause 5.5.4 onwards, but not 5.6.X
            console.log(subclause_of_clause_five);
            return true;
        }
    }

    if(is_a_apioperation_header(type, value) && value[2][0].c.startsWith("5.13.")) {
        subclause_of_clause_five = parseInt(value[2][0].c.substring(5)); // from the 4th char, i.e. skipping "5.13." at the beginning
        console.log(subclause_of_clause_five);
        if(subclause_of_clause_five >= 2 && subclause_of_clause_five <= 99) {
            // if we are in subclause 5.5.4 onwards, but not 5.6.X
            console.log(subclause_of_clause_five);
            return true;
        }
    }

    return false;
}

// check if we are parsing a level-2 API group header
function is_a_apigroup_header(type, value) {
    if (type === "Header" && value[0] === 2 && value[2][0].c.startsWith("5.")) {
        return true;
    }
    return false;
}

// check if we are parsing a level-3 API operation header
function is_a_apioperation_header(type, value) {
    if (type === "Header" && value[0] === 3 && value[2][0].c.startsWith("5.")) {
        return true;
    }
    return false;
}

// creates an identifier out of a sequence of words composing the name of an API operation
function compact_string_array(array_of_strings) {
    identifier = array_of_strings.join("");
    if(identifier === "") {
        return "Generic"
    }
    return identifier;
}
 No newline at end of file
+124 −0
Original line number Original line Diff line number Diff line
import json
import requests

# Function translations
def is_a_behaviour_header(type, value):
    if type == "Header" and value[0] == 4 and value[2][0]['c'].startswith("5.") and value[2][2]['c'] == "Behaviour":
        return True
    if is_a_apioperation_header(type, value) and value[2][0]['c'].startswith("5.5."):
        subclause_of_clause_five = int(value[2][0]['c'][4:])
        return 4 <= subclause_of_clause_five <= 99
    if is_a_apioperation_header(type, value) and value[2][0]['c'].startswith("5.13."):
        subclause_of_clause_five = int(value[2][0]['c'][5:])
        return 2 <= subclause_of_clause_five <= 99
    return False

def is_a_apigroup_header(type, value):
    return type == "Header" and value[0] == 2 and value[2][0]['c'].startswith("5.")

def is_a_apioperation_header(type, value):
    return type == "Header" and value[0] == 3 and value[2][0]['c'].startswith("5.")

def compact_string_array(array_of_strings):
    return "".join(array_of_strings) or "Generic"

def extract_text(content):
    if isinstance(content, str):
        return content
    elif isinstance(content, list):
        return extract_text(content[0]['c'])
    else:
        print("TYPOOY ")
        print(type(content))
        exit(1)

# Reading from API.json
with open('API.json', 'r', encoding='utf-8') as file:
    fullapi = json.load(file)

i_am_inside = False
testcases_fromspec = []
testcasemetadata = {'seqnumber': 0, 'progressive_subid': 0}
number_of_blocks = len(fullapi['blocks'])
current_index = 0

# Main loop
while current_index < number_of_blocks:
    block = fullapi['blocks'][current_index]
    type = block['t']
    value = block['c']

    # check if we are parsing a level-2 API group header
    if is_a_apigroup_header(type, value):
        if value[2][0]['t'] != "Str":
            print("H2 group not Str!")
            exit()
        # we collect all the words composing the higher-level clause name, example: "5.6 Context Information Provision"
        # but skip the first token because it is the clause number
        testcasemetadata['descriptive_group'] = " ".join(el['c'] for el in value[2][1:] if el['t'] != "Space")

    # check if we are parsing a level-3 API operation header
    if is_a_apioperation_header(type, value):
        if value[2][0]['t'] != "Str":
            print("H3 operation not Str!")
            exit()
        # we create metadata for all testcases of this operation:
        # the first token is the clause number
        testcasemetadata['clause_number'] = value[2][0]['c']
        print(f"         {current_index}. H3 - {testcasemetadata['clause_number']}", end=" - ")
        # the group identifier is composed of the first two words of the group descriptive header string, by removing spaces
        testcasemetadata['group_fromspec'] = compact_string_array(testcasemetadata['descriptive_group'].split(" ")[:2])
        print(f"{testcasemetadata['group_fromspec']}", end=" - ")
        # the subgroup is composed of the remaining (after 2 till end) words of the group descriptive header string
        testcasemetadata['subgroup_fromspec'] = compact_string_array(testcasemetadata['descriptive_group'].split(" ")[2:])
        print(f"{testcasemetadata['subgroup_fromspec']}", end=" - ")
        # then we collect, for the name of the operation, all the words composing the lower-level name, example "5.6.1 Create Entity"
        # but skip the first token because it is the clause number  
        testcasemetadata['descriptive_operation'] = " ".join(extract_text(el['c']) for el in value[2][1:] if el['t'] != "Space")
        print(f"         H3 - {testcasemetadata['descriptive_group']} - {testcasemetadata['descriptive_operation']}")
        # the operation identifier is composed from the descriptive header string of the operation itself, by removing spaces
        testcasemetadata['operation_fromspec'] = compact_string_array(testcasemetadata['descriptive_operation'].split(" "))

    # check if we are entering a level-4 header that spells "5.x.x.x Behaviour"
    # or a level-3 common Behaviour greater than 5.5.2
    if is_a_behaviour_header(type, value) and not i_am_inside:
        i_am_inside = True
        testcasemetadata['seqnumber'] += 1
        entering_text = value[2][0]['c']
        print(f"entering {entering_text} META {testcasemetadata['group_fromspec']} {testcasemetadata['subgroup_fromspec']} {testcasemetadata['operation_fromspec']}")

    elif i_am_inside and type == "Header":
        # i get out once i reach whatever Header follows
        i_am_inside = False
        testcasemetadata['progressive_subid'] = 0
        exiting_text = value[2][0]['c']
        print(f"exiting {exiting_text}")
        current_index -= 1  # parse the current exit block again because we might have two good blocks back-to-back

    elif i_am_inside:
        if type in ["Para"]:
            testcasemetadata['progressive_subid'] += 1
            testcasemetadata['tp_id_fromspec'] = f"{str(testcasemetadata['seqnumber']).zfill(3)}_{str(testcasemetadata['progressive_subid']).zfill(2)}"
            testcasemetadata['description'] = " ".join(el['c'] for el in value if el['t'] == "Str")
            # push a deep copy of the object into the array
            testcases_fromspec.append(testcasemetadata.copy())
            print(f"..collecting Block {current_index} of {len(value)} in {testcasemetadata['tp_id_fromspec']}")
            # [Add logging to file or other operations here]
        else:
            print(f"..not collecting {type}: {value}")

    current_index += 1

# HTTP Requests
dburl = "http://ec2-18-153-159-20.eu-central-1.compute.amazonaws.com:5555/fromspec"

response = requests.delete(dburl)
print(f"Delete response status: {response.status_code}")

headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}
response = requests.post(dburl, headers=headers, json=testcases_fromspec)
print(f"Post response status: {response.status_code}")
print(response.text)